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

joanne matthews (RRes-Roth) joanne.matthews at bbsrc.ac.uk
Tue Feb 20 07:29:10 EST 2007


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 on and how I can
avoid the problem. Thanks

Joanne Matthews



More information about the Python-list mailing list