Python余弦函数精度 [英] Python cosine function precision
问题描述
从数学中我们知道90度角的余弦为0,但Python表示它的余弦要大得多。
From mathematics we know that the cosine of a 90 degree angle is 0 but Python says it's a bit more than that.
import math
math.cos(math.radians(90))
6.123233995736766e-17
Python和数字 0之间有什么关系?
What's the matter between Python and the number "0"?
推荐答案
在我之后重复:
计算机无法处理实数。
Computers cannot process real numbers.
Python使用double精度IEEE浮点数,精度四舍五入至53个二进制数,并且对范围有限制。由于π/ 2是一个无理数,因此计算机会将其四舍五入为最接近的可表示数字(或四舍五入为可表示的数字-有些运算具有精确的舍入,有些运算的误差大于1/2 ULP)。
Python uses double precision IEEE floats, which round to 53 binary digits of precision and have limits on range. Since π/2 is an irrational number, the computer rounds it to the nearest representable number (or to a close representable number — some operations have exact rounding, some have error greater than 1/2 ULP).
因此,您从未要求计算机计算 cos(π/ 2)
,您实际上是要求计算机计算 cos (π/ 2 +ε)
,其中ε是计算π/ 2的舍入误差。然后再次将结果四舍五入。
Therefore, you never asked the computer to compute cos(π/2)
, you really asked it to compute cos(π/2+ε)
, where ε is the roundoff error for computing π/2. The result is then rounded again.
可能性1:该程序执行符号计算,而不是数字计算。这适用于Mathematica和Maxima之类的程序,不适用于Excel。
Possibility 1: The program does symbolic computations, not numeric ones. This applies to programs like Mathematica and Maxima, not Excel.
可能性2:该程序正在隐藏数据(最有可能)。 Excel只会显示您要求的数字,例如,
Possibility 2: The program is hiding the data (most likely). Excel will only show you the digits you ask for, e.g.,
>>> '%.10f' % math.cos(math.radians(90))
'0.0000000000'
Python具有用于打印浮点数的微调功能,因此它们在往返文本和返回时均能幸免。这意味着默认情况下,Python打印的位数比 printf
多。
Python has a finely tuned function for printing out floats so that they survive a round trip to text and back. This means that Python prints more digits by default than, for example, printf
.
可能性3: 您使用的程序有两个舍入错误被取消。
Possibility 3: The program you are using had two round-off errors that canceled.
这篇关于Python余弦函数精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!