Double equals 0 problem in C

前端 未结 5 1968
执笔经年
执笔经年 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:42

    Don't use exact equality operations when dealing with floating point numbers. Although your number may look like 0, it likely to be something like 0.00000000000000000000001.

    You'll see this if you use %.50f instead of %f in your format strings. The latter uses a sensible default for decimal places (6 in your case) but the former explicitly states you want a lot.

    For safety, use a delta to check if it's close enough, such as:

    if (fabs (val) < 0.0001) {
        // close enough.
    }
    

    Obviously, the delta depends entirely on your needs. If you're talking money, 10-5 may be plenty. If you're a physicist, you should probably choose a smaller value.

    Of course, if you're a mathematician, no inaccuracy is small enough :-)

提交回复
热议问题