numpy.sin(pi) returns negative value

后端 未结 4 734
面向向阳花
面向向阳花 2020-12-19 20:51

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,

相关标签:
4条回答
  • 2020-12-19 21:26

    In reality a <> 0 because in reality numpy.pi is not Pi (what is Pi in reality anyway?) - it is just its approximation and numpy.sin is not sine - it is its approximation as well. So you have to take some error into account, for example

    print( -0.0000001 < a < 0.0000001 )
    

    or use some other tricks (representing Pi differently - not as a float number ).

    0 讨论(0)
  • 2020-12-19 21:29
    >>> import numpy
    >>> a = numpy.sin(2. * numpy.pi)
    >>> numpy.allclose(a, 0)
    True
    >>> numpy.clip(numpy.array([-0.1, 1.0, 2.0]), 0, np.inf)
    array([ 0.,  1.,  2.])
    
    0 讨论(0)
  • 2020-12-19 21:35

    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)
    

    You may also want to read this.

    0 讨论(0)
  • 2020-12-19 21:49

    When I calculate

    numpy.sin(2 * numpy.pi)
    

    I get

    -2.4492935982947064e-16 # i.e. -0.0000000000000002
    

    This is a classic floating point accuracy error. You are better taking a tolerance approach to testing the value:

    if abs(a) < 0.0001:
    
    0 讨论(0)
提交回复
热议问题