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
1989922yan
V2EX  ›  Python

为什么会一直循环下去?

  •  
  •   1989922yan · 2016-03-23 18:12:11 +08:00 · 2935 次点击
    这是一个创建于 2927 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #coding=utf8
    
    if __name__ == '__main__':
        x = 0.5
        while x != 1.0:
            x = x + 0.1
            print x
    
    
    第 1 条附言  ·  2016-03-23 20:26:35 +08:00
    #coding=utf8
    
    if __name__ == '__main__':
        x = 0.8    # 如果换成0.8就对了,不过,可能还是浮点数问题
                       # 只是补充一下
        #print(x+0.5 != 1.0)
        while x!=1.0:
            print(x != 1.0)
            print(type(x))
            x = x + 0.1
            print x
    
    14 条回复    2016-03-24 03:46:56 +08:00
    9hills
        1
    9hills  
       2016-03-23 18:19:57 +08:00   ❤️ 1
    fds
        2
    fds  
       2016-03-23 18:20:44 +08:00
    浮点数判断相等不能直接用 ==,需要

    while abs(x - 1) < 0.00001:
    fds
        3
    fds  
       2016-03-23 18:26:57 +08:00
    Python 3.5 的 math.isclose(x, 1) 也不错。但估计你用的版本没有这么高。
    http://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python
    kingmo888
        4
    kingmo888  
       2016-03-23 18:29:56 +08:00
    换成>=不好吗?
    znoodl
        5
    znoodl  
       2016-03-23 18:30:57 +08:00 via iPhone
    浮点数 对比相等通病
    fds
        6
    fds  
       2016-03-23 18:32:44 +08:00
    哦 写错了 是

    while abs(x - 1) > 0.00001:
    bp0
        7
    bp0  
       2016-03-23 18:34:06 +08:00
    @kingmo888 换成>= 可以退出循环,但是结果可能不是 @1989922yan 想要的。毕竟 1.0 和 1.1 差别还是很大的。
    rming
        8
    rming  
       2016-03-23 18:34:15 +08:00
    学习了
    bp0
        9
    bp0  
       2016-03-23 18:38:16 +08:00
    @kingmo888 应该是换成<=,如果换成>= 则不会进入循环,直接输出 0.5 了。按照程序逻辑, @1989922yan 应该是想要输出 1.0 这个结果才对。
    kingmo888
        10
    kingmo888  
       2016-03-23 18:50:37 +08:00
    @bp0 哈,你说的对,我疏忽了。
    expkzb
        11
    expkzb  
       2016-03-23 18:57:08 +08:00 via iPhone
    学习了,还有这么坑的
    wangxiwei18
        12
    wangxiwei18  
       2016-03-23 19:07:29 +08:00
    等号两边的空格去掉试试
    1989922yan
        13
    1989922yan  
    OP
       2016-03-23 20:32:22 +08:00
    @9hills 目测已是正解。 THX * 10^1000
    cxbig
        14
    cxbig  
       2016-03-24 03:46:56 +08:00 via iPhone
    float 对比和计算是大坑……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3230 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:09 · PVG 20:09 · LAX 05:09 · JFK 08:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.