python精度问题?
PHP中文网
PHP中文网 2017-04-17 14:32:00
[Python讨论组]
Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32
>>> print '%.100f' % (9999.0/10000)
0.9999000000000000110134124042815528810024261474609375000000000000000000000000000000000000000000000000

从原理上阐述下为什么产生这样的误差?

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(2)
巴扎黑

python有关浮点数的误差是这么说的:

On a typical machine running Python, there are 53 bits of precision available for a Python float, so the value stored internally when you enter the decimal number 0.1 is the binary fraction

见这里 https://docs.python.org/2/tutorial/floatingpoint.html
你可以试试Decimal, 估计底层没有完全实现一个完整的大数算法,实际上,我觉得这个并不完全是Python规范的内容,而是取决于平台和实现,你可以看下当前平台的float大小

import sys
print sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

python手册里如是说

Floating point numbers are usually implemented using double in C; information about the precision and
internal representation of floating point numbers for the machine on which your program is running is available in
sys.float_info.

上面说的这些都是CPython的实现,而这个在Jython中,又是另一番定义:

    Jython 2.5.3 (2.5:c56500f08d34+, Aug 13 2012, 14:48:36)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_40
Type "help", "copyright", "credits" or "license" for more information.
>>> '%.100f' % (9999.0/10000)
'0.9999000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'

结论: 这个取决于平台实现。

高洛峰

可以参考IEEE的浮点数标准

浮点数在计算机中的存储往往采取这个标准, 其只能精确表示2^x的倍数, 而除此之外的其它数字只能尽量逼近.因此使用浮点数是会有误差的.

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号