Unexpected loss of precision when dividing doubles

前端 未结 8 1997
慢半拍i
慢半拍i 2021-02-09 14:33

I have a function getSlope which takes as parameters 4 doubles and returns another double calculated using this given parameters in the following way:

double QSw         


        
8条回答
  •  粉色の甜心
    2021-02-09 14:58

    Patrick seems to be right about (c-a) being the main cause:

    d-b = -1,72219 - (-1,64161) = -0,08058

    c-a = 2,70413 - 2,71156 = -0,00743

    S = (d-b)/(c-a)= -0,08058 / -0,00743 = 10,845222

    You start out with six digits precision, through the subtraction you get a reduction to 3 and four digits. My best guess is that you loose additonal precision because the number -0,00743 can not be represented exaclty in a double. Try using intermediate variables with a bigger precision, like this:

    double QSweep::getSlope(double a, double b, double c, double d)
    {
        double slope;
        long double temp1, temp2;
    
        temp1 = (d-b);
        temp2 = (c-a);
        slope = temp1/temp2;
    
        return slope;
    }
    

提交回复
热议问题