numpy.sin(pi) 返回负值

问题描述:

以下代码:

a = numpy.sin(2. * numpy.pi)
print(a < 0)

返回真".但实际上 a = 0.我该如何解决?另外,我有一个矩阵有很多像a"这样的值,我想确保我的矩阵包含非负值.

return "True". But in reality a = 0. How could I fix that? In addition, I have a matrix with a lot of value like "a" and I want to make sure that my matrix contains non-negative value.

这是因为浮点运算和精度的原因.结果是 sin 的最佳近似值,可以表示为浮点数.通常你解决的问题几乎为零:

This because of floating point arithmetic, and accuracy reasons. The result is the best approximation of sin one can get to be representable as a floating point number. Usually you solve near-zero problems like this:

a = numpy.sin(2. * numpy.pi)
print(abs(a) < 1e-10)

您可能还想阅读这篇.