Skip to content

Instantly share code, notes, and snippets.

@williamjshipman
Last active October 18, 2019 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save williamjshipman/b44cdb7028ec7b72d297d9e13244dbf6 to your computer and use it in GitHub Desktop.
Save williamjshipman/b44cdb7028ec7b72d297d9e13244dbf6 to your computer and use it in GitHub Desktop.
Code for "My computer can't add (part 1)"
if __name__ == '__main__':
import timeit
print 'Initialising high-accuracy decimal values...'
array_max = Decimal('1e6')
deci_two = Decimal(2)
values_decimal = np.arange(-array_max/deci_two, array_max/deci_two + Decimal(1), Decimal(1)) / array_max
values_decimal[0] -= Decimal('1e-4')
values = np.float32(values_decimal)
values_rev = np.random.permutation(values)
true_answer = Decimal('-1e-4')
print('\nTesting plain addition...')
print('Expected answer: {:s}'.format(str(true_answer)))
# Print some pretty headings for the results.
print('\n{:30s}|{:15s}|{:15s}|{:15s}'.format('Test', 'Result', 'Abs. error', 'Time (s)'))
Initialising high-accuracy decimal values...
Testing plain addition...
Expected answer: -0.0001
Test |Result |Abs. error |Time (s)
Serial summation |0.001457870007 |0.001557870000 |0.230740897506
Numpy Sum |0.001457870007 |0.001557870000 |0.000810961717
Serial Kahan |-0.000097185373 |0.000002814627 |0.687989271230
import numpy as np
def serial_kahan_sum(values):
zero_value = np.zeros(1, values.dtype)[0]
s = zero_value
c = zero_value
r x in values:
s, c = SCS(s, x+c)
return s, c
def serial_sum(values):
s = np.zeros(1, values.dtype)[0]
for x in values:
s += x return s
return s
def SCS(a, b):
sum = a + b
return sum, b - (sum - a)
runtime = min(timeit.Timer('result = serial_sum(values)', setup='from __main__ import *').repeat(repeat=10, number=2)) / 2
result = serial_sum(values)
check_error(true_answer, result, runtime, 'Serial summation');
runtime = min(timeit.Timer('result = values.sum()', setup='from __main__ import *').repeat(repeat=10, number=2)) / 2
result = values.sum()
check_error(true_answer, result, runtime, 'Numpy Sum')
runtime = min(timeit.Timer('result = serial_kahan_sum(values)', setup='from __main__ import *').repeat(repeat=10, number=2)) / 2
result = serial_kahan_sum(values)
check_error(true_answer, result[0], runtime, 'Serial Kahan')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment