Last active
December 10, 2015 00:09
-
-
Save akaptur/4348873 to your computer and use it in GitHub Desktop.
A small depiction of issues with floating point arithmetic in python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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