为什么math模块返回错误的结果?
Why does the math module return the wrong result?
A = 12345678917 print 'A =',A B = sqrt(A**2) print 'B =',int(B)结果
A = 12345678917 B = 12345678917在这里,结果是正确的.
Here, the result is correct.
A = 123456758365483459347856 print 'A =',A B = sqrt(A**2) print 'B =',int(B)结果
A = 123456758365483459347856 B = 123456758365483467538432此处结果不正确.
为什么会这样?
推荐答案因为 math.sqrt(..) 首先将数字转换为浮点,并且浮点具有有限的 mantisse :它只能正确表示数字的一部分.因此,float(A**2)不等于A**2.接下来,它计算出math.sqrt,它也大致正确.
Because math.sqrt(..) first casts the number to a floating point and floating points have a limited mantisse: it can only represent part of the number correctly. So float(A**2) is not equal to A**2. Next it calculates the math.sqrt which is also approximately correct.
大多数使用浮点运算的函数将永远不会完全不符合其整数对应函数.浮点计算本质上是近似的.
Most functions working with floating points will never be fully correct to their integer counterparts. Floating point calculations are almost inherently approximative.
如果计算出A**2,则得到:
>>> 12345678917**2 152415787921658292889L现在,如果将其转换为float(..),则会得到:
Now if one converts it to a float(..), one gets:
>>> float(12345678917**2) 1.5241578792165828e+20但是,如果您现在问两者是否相等:
But if you now ask whether the two are equal:
>>> float(12345678917**2) == 12345678917**2 False因此信息在转换为浮点数时已经丢失.
So information has been lost while converting it to a float.
您可以在Wikipedia文章中有关 IEEE-754的文章中了解有关浮子如何工作以及为什么它们是近似值的更多信息. ,关于浮点如何工作的正式定义.
You can read more about how floats work and why these are approximative in the Wikipedia article about IEEE-754, the formal definition on how floating points work.
更多推荐
平方根Python 2.7.12
发布评论