why do I get this behavior from a while loop?

S

S. Chris Colbert

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
 
D

Diez B. Roggisch

S. Chris Colbert said:
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?


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
 
P

Paul Rudin

....: print t

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.
 
S

S. Chris Colbert

What a newbie mistake for me to make.

I appreciate the replies everyone!

Cheers,

Chris
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top