The following code:
a = numpy.sin(2. * numpy.pi)
print(a < 0)
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.
In reality a <> 0 because in reality
numpy.pi
is not Pi (what is Pi in reality anyway?) - it is just its approximation andnumpy.sin
is not sine - it is its approximation as well. So you have to take some error into account, for exampleor use some other tricks (representing Pi differently - not as a float number ).
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:You may also want to read this.
When I calculate
I get
This is a classic
float
ing point accuracy error. You are better taking a tolerance approach to testing the value: