Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A small depiction of issues with floating point arithmetic in python.
def naive_add(lis):
total = 0
for elem in lis:
total += elem
return total
def recursive_add(lis):
if len(lis) == 1:
return lis[0]
elif len(lis) == 0:
return 0
else:
mid = len(lis)/2
return recursive_add(lis[:mid]) + recursive_add(lis[mid:])
def generate_big_list_of_smalls():
mylist = [1000000000]+[.0001]*10000000
# 1,000,000,000
# .0001 * 10,000,000 = 1,000
print "list generated"
return mylist
def test_adding(mylist):
nsum = naive_add(mylist)
rsum = recursive_add(mylist)
psum = sum(mylist)
print "naive:", nsum
print "recursive", rsum
print "built-in", psum
li = generate_big_list_of_smalls()
test_adding(li)
# ⚲python floating_math.py
# list generated
# naive: 1000001000.17
# recursive: 1000001000.0
# built-in: 1000001000.17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment