What is happening here in pow function?

前端 未结 5 540
北海茫月
北海茫月 2020-12-01 23:53

I have seen various answer here that depicts Strange behavior of pow function in C.
But I Have something different to ask here.

In the below code I

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 00:50

    Why is the output coming out to be different. ? (in the updated appended code)

    We do not know the values are that different.

    When comparing the textual out of int/double, be sure to print the double with sufficient precision to see if it is 100.000000 or just near 100.000000 or in hex to remove all doubt.

    printf("%d %d\n" , x , y);
    // printf("%f %f\n" , k , l);
    // Is it the FP number just less than 100?
    printf("%.17e %.17e\n" , k , l);  // maybe 9.99999999999999858e+01
    printf("%a %a\n" , k , l);        // maybe 0x1.8ffffffffffff0000p+6
    

    Why is the output coming out to be different. ? (in the original code)

    C does not specify the accuracy of most functions. The following are all compliant results.

    // Higher quality functions return 100.0
    pow(10,2) --> 100.0   
    // Lower quality and/or faster one may return nearby results
    pow(10,2) --> 100.0000000000000142...
    pow(10,2) --> 99.9999999999999857...
    

    Assigning a floating point (FP) number to an int simple drops the fraction regardless of how close the fraction is to 1.0

    When converting FP to an integer, better to control the conversion and round to cope with minor computational differences.

    // long int lround(double x);
    long i = lround(pow(10.0,2.0));
    

提交回复
热议问题