Weird result returned from adding floats depending on order I add them

Laurent Pointal laurent.pointal at limsi.fr
Tue Feb 20 07:56:03 EST 2007


joanne matthews (RRes-Roth) a écrit :
> I'm getting different results when I add up a list of floats depending
> on the order that I list the floats. 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:
>         	print "Your proportions must add up to 1"
>    
>         	return False
>    	return True
> 
> However, if I swap, the 4th and 5th list items like this:
> 
> totalProp=0
> inputs=[0.2,0.2,0.2,0.2,0.1,0,0.1]
> for each in inputs:
>         
>    totalProp+=each
>    print "totalProp=",totalProp
>    if totalProp != 1:
>         print "Your proportions must add up to 1"
>    
>         return False
>    return True
> 
> I get True returned. Can anyone tell me whats going 

Its related to the internal representation of real numbers using a
finite number of binary digits - intermediate additions may (here the
order is have an impact) produce results which have no representation,
and lead to dismiss of an epsilon value.

http://en.wikipedia.org/wiki/Floating_point

> on and how I can
> avoid the problem. Thanks

Use an ad-hoc library with numerical types using a different
representation (other posters may give examples of libraries they use).



More information about the Python-list mailing list