V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Mar 23, 2016 · 3987 views
    This topic created in 3687 days ago, the information mentioned may be changed or developed.
    #coding=utf8
    
    if __name__ == '__main__':
        x = 0.5
        while x != 1.0:
            x = x + 0.1
            print x
    
    
    Supplement 1  ·  Mar 23, 2016
    #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 replies    2016-03-24 03:46:56 +08:00
    fds
        2
    fds  
       Mar 23, 2016
    浮点数判断相等不能直接用 ==,需要

    while abs(x - 1) < 0.00001:
    fds
        3
    fds  
       Mar 23, 2016
    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  
       Mar 23, 2016
    换成>=不好吗?
    znoodl
        5
    znoodl  
       Mar 23, 2016 via iPhone
    浮点数 对比相等通病
    fds
        6
    fds  
       Mar 23, 2016
    哦 写错了 是

    while abs(x - 1) > 0.00001:
    bp0
        7
    bp0  
       Mar 23, 2016
    @kingmo888 换成>= 可以退出循环,但是结果可能不是 @1989922yan 想要的。毕竟 1.0 和 1.1 差别还是很大的。
    rming
        8
    rming  
       Mar 23, 2016
    学习了
    bp0
        9
    bp0  
       Mar 23, 2016
    @kingmo888 应该是换成<=,如果换成>= 则不会进入循环,直接输出 0.5 了。按照程序逻辑, @1989922yan 应该是想要输出 1.0 这个结果才对。
    kingmo888
        10
    kingmo888  
       Mar 23, 2016
    @bp0 哈,你说的对,我疏忽了。
    expkzb
        11
    expkzb  
       Mar 23, 2016 via iPhone
    学习了,还有这么坑的
    wangxiwei18
        12
    wangxiwei18  
       Mar 23, 2016
    等号两边的空格去掉试试
    1989922yan
        13
    1989922yan  
    OP
       Mar 23, 2016
    @9hills 目测已是正解。 THX * 10^1000
    cxbig
        14
    cxbig  
       Mar 24, 2016 via iPhone
    float 对比和计算是大坑……
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   952 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 55ms · UTC 21:16 · PVG 05:16 · LAX 14:16 · JFK 17:16
    ♥ Do have faith in what you're doing.