平方根Python 2.7.12 [英] Square root Python 2.7.12

查看:111
本文介绍了平方根Python 2.7.12的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么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

此处结果不正确.

为什么会这样?

推荐答案

因为

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆