-3

I have the following list

alist = [0.141, 0.29, 0.585, 0.547, 0.233]

and I find the cumulative summation with

np.cumsum(alist)
array([ 0.141,  0.431,  1.016,  1.563,  1.796])

When I convert this array to a list, some decimal values show up. How can I avoid these decimals?

list(np.cumsum(alist))
[0.14099999999999999,
 0.43099999999999994,
 1.016,
 1.5630000000000002,
 1.7960000000000003]

This may be a duplicate, but I couldn't find the answer.

cs95
  • 379,657
  • 97
  • 704
  • 746
tcokyasar
  • 582
  • 1
  • 9
  • 26
  • 1
    Note that this hasn't got much to do with `cumsum` or with array vs. list apart from them being printed differently. Just type `0.141 + 0.29` to see it's in the numbers themselves. – Paul Panzer Feb 18 '18 at 00:46

1 Answers1

2

It's important to understand that floating point numbers are not stored in base 10 decimal format.

Therefore, you have to be crystal clear why you want to remove "the extra decimal places" that you see:

  1. Change formatting to make the numbers look prettier / consistent.
  2. Work with precision as if you are performing base-10 arithmetic.

If the answer is (1), then use np.round.

If the answer is (2), then use python's decimal module.

The below example demonstrates that np.round does not change the underlying representation of floats.

import numpy as np

alist = [0.141, 0.29, 0.585, 0.547, 0.233]

lst = np.round(np.cumsum(alist), decimals=3)
print(lst)
# [ 0.141  0.431  1.016  1.563  1.796]

np.set_printoptions(precision=20)
print(lst)
# [ 0.14099999999999998646  0.43099999999999999423  1.01600000000000001421
#   1.56299999999999994493  1.79600000000000004086]

np.set_printoptions(precision=3)
print(lst)
# [ 0.141  0.431  1.016  1.563  1.796]
jpp
  • 159,742
  • 34
  • 281
  • 339