推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
EdwardChu
V2EX  ›  Python

为什么 np.sin(np.pi)的结果不为 0?

  •  
  •   EdwardChu · Jan 31, 2019 · 5354 views
    This topic created in 2662 days ago, the information mentioned may be changed or developed.
    import numpy as np

    print(np.sin(np.pi))
    print(np.sin(0.5*np.pi))

    结果分别是
    1.2246467991473532e-16
    1.0
    5 replies    2019-03-04 14:35:51 +08:00
    LGA1150
        2
    LGA1150  
       Feb 1, 2019 via Android
    因为π不能用有限空间的浮点数表示,只是一个近似值,所以你只能得到一个很接近 0 的值,而不是 0
    同理 tan(π/2)
    这叫 Catastrophic Cancellation
    这也是比较浮点数时不能用==的原因
    至于为什么第二个可以输出 1.0,是因为前面的 1.0000...占据了有效数字位(双精度可以保证 15~16 个有效数字),使误差被舍去了
    LGA1150
        3
    LGA1150  
       Feb 1, 2019 via Android
    #2 又查了下资料发现 Catastrophic Cancellation 好像不是这个意思。。
    necomancer
        4
    necomancer  
       Mar 4, 2019
    因为 Numpy 主打数值计算,精度误差不可避免。希望 sin(pi) 是精确值可以考虑 Mathematica 或者 SymPy:

    In [1]: import sympy

    In [2]: sympy.pi
    Out[2]: pi

    In [3]: sympy.sin
    Out[3]: sin

    In [4]: sympy.sin(sympy.pi)
    Out[4]: 0
    necomancer
        5
    necomancer  
       Mar 4, 2019
    至于为什么 pi/2 更准:

    In [1]: 1.0 == 1.0
    Out[1]: True

    In [2]: 1.0 == 1.0+1e-16
    Out[2]: True

    In [3]: 1.0 == 1.0+1e-15
    Out[3]: False

    In [4]: 1.0 == 1.0+1e-16
    Out[4]: True

    In [5]: 1.0 == 1.0+1.2e-16
    Out[5]: False

    具体代码可以去查查
    https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/dbl-64/s_sin.c;hb=HEAD#l281

    do_sin 函数里似乎用了麦克劳林级数。所以返回的都是近似值。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2822 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 10:50 · PVG 18:50 · LAX 03:50 · JFK 06:50
    ♥ Do have faith in what you're doing.