why do I get this behavior from a while loop?

Discussion in 'Python' started by S. Chris Colbert, Nov 27, 2009.

  1. This seems strange to me, but perhaps I am just missing something:

    In [12]: t = 0.
    In [13]: time = 10.

    In [14]: while t < time:
    ....: print t
    ....: t += 1.
    ....:
    ....:
    0.0
    1.0
    2.0
    3.0
    4.0
    5.0
    6.0
    7.0
    8.0
    9.0

    In [15]: t = 0.

    In [16]: time = 10.

    In [17]: while t < time:
    ....: print t
    ....: t += 0.1
    ....:
    ....:
    0.0
    0.1
    0.2
    0.3
    <--snip-->
    9.4
    9.5
    9.6
    9.7
    9.8
    9.9
    10.0


    I would think that second loop should terminate at 9.9, no?

    I am missing something fundamental?

    Cheers!

    Chris
     
    S. Chris Colbert, Nov 27, 2009
    #1
    1. Advertisements


  2. Yes. The lack of precision that floating points suffer from (nothing
    python-specific), and the rounding-behavior of printing them.
    .... print repr(t)
    .... t += .1
    ....
    0.0
    0.10000000000000001
    <snip/>
    9.8999999999999808
    9.9999999999999805

    Diez
     
    Diez B. Roggisch, Nov 27, 2009
    #2
    1. Advertisements

  3. S. Chris Colbert

    Paul Rudin Guest

    Try replacing with: print "%0.20f" % t


    The thing you're missing is that floating point arithmetic isn't (in
    general) exact - but when it's printed it's rounded.
     
    Paul Rudin, Nov 27, 2009
    #3
  4. Steven D'Aprano, Nov 27, 2009
    #4
  5. What a newbie mistake for me to make.

    I appreciate the replies everyone!

    Cheers,

    Chris
     
    S. Chris Colbert, Nov 27, 2009
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.