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
huge2046
V2EX  ›  Python

float 数据运算精度, dict 存储问题求教?

  •  1
     
  •   huge2046 · 2018-11-06 16:42:12 +08:00 · 965 次点击
    这是一个创建于 1998 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #ecoding=utf-8
    
    item = {'sum':0}
    for num in [0.32, 0.09]:
        item['sum'] += num
    
    print item
    print item['sum']
    
    运行结果:
    {'sum': 0.41000000000000003}
    0.41
    

    print item 的结果为 0.41000000000000003 我可以理解 因为 float 数据存储导致精度问题

    但是 print item['sum'] sum 的值和 print item 中 sum 的值不同无法理解,按道理他们指向同一块内存 值都应该为 0.41000000000000003

    第 1 条附言  ·  2018-11-07 15:06:02 +08:00
    python 指向同一块内存 输出值不同
    1 条回复    2018-11-13 23:56:09 +08:00
    cgsv
        1
    cgsv  
       2018-11-13 23:56:09 +08:00 via iPhone
    同一块地址输出值不同是因为 print item 时输出的值是 str(item),而在字典或其他容器内部输出的值是 repr(item)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4820 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 09:53 · PVG 17:53 · LAX 02:53 · JFK 05:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.