Double equals 0 problem in C

前端 未结 5 1982
执笔经年
执笔经年 2021-01-11 17:56

I was implementing an algorithm to calculate natural logs in C.

double taylor_ln(int z) {
    double sum = 0.0;
    double tmp = 1.0;

    int i = 1;
    whi         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-11 18:43

    Just because a number displays as "0.000000" does not mean it is equal to 0.0. The decimal display of numbers has less precision than a double can store.

    It's possible that your algorithm is getting to a point where it is very close to 0, but the next step moves so little that it rounds to the same thing it was at before, and hence it never gets any closer to 0 (just goes into an infinite loop).

    In general, you should not compare floating-point numbers with == and !=. You should always check if they are within a certain small range (usually called epsilon). For example:

    while(fabs(tmp) >= 0.0001)
    

    Then it will stop when it gets reasonably close to 0.

提交回复
热议问题