为什么在使用python和numpy时sin(180)不为零? [英] Why is sin(180) not zero when using python and numpy?
问题描述
有人知道为什么下限值不等于0吗?
Does anyone know why the below doesn't equal 0?
import numpy as np
np.sin(np.radians(180))
或:
np.sin(np.pi)
当我将其输入python时,它的值为1.22e-16.
When I enter it into python it gives me 1.22e-16.
推荐答案
数字π
不能完全表示为浮点数.因此,np.radians(180)
不会给您π
,它会给您3.1415926535897931
.
The number π
cannot be represented exactly as a floating-point number. So, np.radians(180)
doesn't give you π
, it gives you 3.1415926535897931
.
sin(3.1415926535897931)
实际上与1.22e-16
类似.
那么,您如何处理呢?
您必须计算出或至少猜测出适当的绝对和/或相对误差范围,然后您编写:代替x == y
:
You have to work out, or at least guess at, appropriate absolute and/or relative error bounds, and then instead of x == y
, you write:
abs(y - x) < abs_bounds and abs(y-x) < rel_bounds * y
(这也意味着您必须组织计算,以使相对于y
的相对误差大于相对于x
的误差.在您的情况下,因为y
是常数0
,所以这很简单-只是向后做.)
(This also means that you have to organize your computation so that the relative error is larger relative to y
than to x
. In your case, because y
is the constant 0
, that's trivial—just do it backward.)
Numpy提供了一个在整个数组中为您执行此操作的功能, allclose
:
Numpy provides a function that does this for you across a whole array, allclose
:
np.allclose(x, y, rel_bounds, abs_bounds)
(这实际上检查了abs(y - x) < abs_ bounds + rel_bounds * y)
,但这几乎总是足够的,并且在不满足要求的情况下,您可以轻松地重新组织代码.)
(This actually checks abs(y - x) < abs_ bounds + rel_bounds * y)
, but that's almost always sufficient, and you can easily reorganize your code when it's not.)
在您的情况下:
np.allclose(0, np.sin(np.radians(180)), rel_bounds, abs_bounds)
那么,您如何知道正确的界限呢?在SO答案中,没有任何方法可以教给您足够的错误分析. Wikipedia上的不确定性的传播提供了一个高层次的概述.如果您真的不知道,可以使用默认值,相对值1e-5
和绝对值1e-8
So, how do you know what the right bounds are? There's no way to teach you enough error analysis in an SO answer. Propagation of uncertainty at Wikipedia gives a high-level overview. If you really have no clue, you can use the defaults, which are 1e-5
relative and 1e-8
absolute.
这篇关于为什么在使用python和numpy时sin(180)不为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!