V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
hakono
V2EX  ›  Python

怪了, Python 算出来的组合的结果为什么是错的

  •  
  •   hakono · 2019-04-17 19:07:11 +08:00 · 2154 次点击
    这是一个创建于 1808 天前的主题,其中的信息可能已经有所发展或是发生改变。

    就是高中数学的那个排列组合的组合,C。从 n 样东西里,取出 m 样,计算有几种取法

    就是那个组合的 nCm

    公式写出来就是 n!/( (n-m)!*m! )

    wiki 介绍


    然后我用 python 算了下,发现结果和其他语言算出来不一样 比如 n=64, n=32( 从 64 样里取出 32 个),用mathematica来算,得到的结果是:

    1832624140942590534

    有兴趣可以访问wolframalpha 这里看看我输入的公式

    而如果用 python 来算,无论是调用科学计算包scipy还是直接自己写函数,算出的结果都是:

    1832624140942590464

    from scipy.special import comb
    
    print("%d" % comb(64,32))
    
    输出:1832624140942590464
    

    如果自己实现计算函数的话也是算出来

    1832624140942590464

    有的搞不懂哪里出的问题

    3 条回复    2019-04-17 21:50:01 +08:00
    ayase252
        1
    ayase252  
       2019-04-17 19:21:26 +08:00
    https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.special.comb.html
    comb 有个默认为 false 的 extra 参数,会用浮点数去算,改成 true 就对了
    wheeler
        2
    wheeler  
       2019-04-17 19:22:04 +08:00
    https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.comb.html#scipy.special.comb

    Python 3.6.7 (default, Oct 22 2018, 11:32:17)
    [GCC 8.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from scipy.special import comb
    >>> comb(64,32, exact=True)
    1832624140942590534
    >>>
    hakono
        3
    hakono  
    OP
       2019-04-17 21:50:01 +08:00
    @ayase252
    @wheeler
    原来如此,感谢解答,原来是精度问题。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2822 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 14:33 · PVG 22:33 · LAX 07:33 · JFK 10:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.