Programming Question

Richard van de Stadt stadt at cs.utwente.nl
Tue Sep 21 11:40:56 EDT 1999


Matthew Hirsch wrote:
> 
> Hi,
> 
> I'm still a little confused about precision and roundoff error.  Can
> someone please explain to me why this loop isn't working.  I'm trying to
> get a printout of all 81 numbers between -4.0 and 4.0 in 0.1
> increments.  The problem is that in the final iteration, a's value is
> becoming greater than 4.  It shows up as something like
> 4.0000000000000000000xxxxx.  What can I do to get around this problem?
> I would greatly appreciate anybody's help.
> 
> Thanks,
> Matt
> 
> Here's the loop:
> 
> >>> a=-4.0
> >>> b=4.0
> >>> i=.1
> >>> while a <= b:
> ...     print a
> ...     a=a+i
> ...

This does what you want:
>>> for i in range(-40, 40, 1.0):
>>>	print i/10.0

I don't know why this doesn't work:
>>> for i in range(-4, 4, .1):
>>>	print i

Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: zero step for range()

That's a worse roundoff error, stating that
.1 equals zero :-)

Richard.




More information about the Python-list mailing list