Unexpected loss of precision when dividing doubles

前端 未结 8 1999
慢半拍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 15:17

    While the academic discussion going on is great for learning about the limitations of programming languages, you may find the simplest solution to the problem is an data structure for arbitrary precision arithmetic.

    This will have some overhead, but you should be able to find something with fairly guaranteeable accuracy.

    0 讨论(0)
  • 2021-02-09 15:23

    The following code:

    #include <iostream>
    using namespace std;
    
    double getSlope(double a, double b, double c, double d){
        double slope;
        slope=(d-b)/(c-a);
        return slope;
    }
    
    int main( ) {
        double s = getSlope(2.71156, -1.64161, 2.70413, -1.72219);
        cout << s << endl;
    }
    

    gives a result of 10.8452 with g++. How are you printing out the result in your code?

    0 讨论(0)
提交回复
热议问题