C's pow() function as per header file <math.h> not working properly

前端 未结 2 1609
陌清茗
陌清茗 2020-12-22 11:28

I see that for the following code produces the result as below, any idea on why is the output like this?

#include 
#include 

in         


        
2条回答
  •  一生所求
    2020-12-22 12:12

    As with every one of the billion other questions on SO to do with floating point :-), the answer is that not all numbers can be represented exactly.

    And, even if they can be represented exacly, you may get a bad result from something like pow which may work within a loop. In other words, no matter how small the error on an operation, if you do it a lot of times, the error becomes large.

    Try printing out the return from pow(10,4) with a %.50f or other floating point specifier, and I'll guarantee you'll see something like 9999.9999999237623465 instead of 10000.

    For what it's worth, the correct results are produced under gcc 3.4.4 under CygWin so it's likely that you're using a less-exact implementation of pow.

提交回复
热议问题