Weird result returned from adding floats depending on order I add them
Grant Edwards
grante at visi.com
Tue Feb 20 10:05:29 EST 2007
On 2007-02-20, joanne matthews (RRes-Roth) <joanne.matthews at bbsrc.ac.uk> wrote:
> I'm getting different results when I add up a list of floats depending
> on the order that I list the floats.
That's how floats work.
> For example, the following returns
> False:
> def check():
> totalProp=0
> inputs=[0.2,0.2,0.2,0.1,0.2,0,0.1]
> for each in inputs:
>
> totalProp+=each
> print "totalProp=",totalProp
> if totalProp != 1:
Floating point operations are not exact. This test requires
them to be.
[...]
> Can anyone tell me whats going on
IEEE floating point can not exactly represent 0.2 nor 0.1, so
you get approximations.
> and how I can avoid the problem.
Don't use floating point if you expect exact results.
--
Grant Edwards grante Yow! I feel better about
at world problems now!
visi.com
More information about the Python-list
mailing list