Programming Question
Paul Duffin
pduffin at mailserver.hursley.ibm.com
Tue Sep 21 11:19:11 EDT 1999
Paul Duffin wrote:
>
> 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
> > ...
>
> You could use decimal in this case instead.
>
> a = -40
> b = 40
> i = 1
> while a <= b
> print a / 10
> a=a+1
>
> which is more accurate because you don't accumulate errors.
>
This should be divide by 10.0 and not 10 as Charles Waldner corrected.
Otherwise you get integer division.
--
Paul Duffin
DT/6000 Development Email: pduffin at hursley.ibm.com
IBM UK Laboratories Ltd., Hursley Park nr. Winchester
Internal: 7-246880 International: +44 1962-816880
More information about the Python-list
mailing list