平方根Python 2.7.12

编程入门 行业动态 更新时间:2024-10-18 18:15:13
本文介绍了平方根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

此处结果不正确.

为什么会这样?

推荐答案

因为 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

本文发布于:2023-11-28 21:08:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643959.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:平方根   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!