I have a list of numbers rounded to the tenth:
myList =
[2.3,
14.4,
21.6,
6.0,
2.6,
4.2,
7.6,
46.7,
8.1,
1.2,
7.6,
6.2,
8.3,
17.7,
27.3,
5.4,
18.6,
6.4,
6.4,
40.4,
28.4,
36.0,
21.5,
4.7,
19.6,
22.0,
18.2,
19.9,
12.1,
20.7,
1.0,
11.8,
1.1,
3.2,
8.0,
6.5,
4.3,
6.4,
4.3,
16.7,
17.8,
2.7,
7.5,
1.5,
2.5,
7.8,
4.4,
10.2,
14.8,
25.1]
When I feed this list into the itertools.accumulate
function and generate a new list (i.e. a running total), some of the values have several decimal places due to floating-point arithmetic.
from itertools import accumulate
accumulated_list = list(accumulate(myList))
accumulated_list
Outputs to:
[2.3,
16.7,
38.3,
44.3,
46.9,
51.1,
58.7,
105.4,
113.5,
114.7,
122.3,
128.5,
136.8,
154.5,
181.8,
187.20000000000002,
205.8,
212.20000000000002,
218.60000000000002,
259.0,
287.4,
323.4,
344.9,
349.59999999999997,
369.2,
391.2,
409.4,
429.29999999999995,
441.4,
462.09999999999997,
463.09999999999997,
474.9,
476.0,
479.2,
487.2,
493.7,
498.0,
504.4,
508.7,
525.4,
543.1999999999999,
545.9,
553.4,
554.9,
557.4,
565.1999999999999,
569.5999999999999,
579.8,
594.5999999999999,
619.6999999999999]
I've referenced some mainstay postings and tutorials but can't get a fix to work on my accumulated_list
:
Limiting floats to two decimal points
https://docs.python.org/3/tutorial/floatingpoint.html
How can the values be resolved to a number rounded to the tenth again? (Not formatting the printing, but rounding the value.)
I've tried using
list(numpy.round(accumulate(myList),1))
or setting the number to a decimal using the decimal
module but to no avail.
list(accumulate(myList.quantize(Decimal('0.1'))))
Adding more information regarding implementing elements as a decimal. myList
from above is generated from a function. How can the elements be implemented as a decimal
?
import numpy as np
def simulate(mean, size):
return list(np.round(np.random.exponential(mean, size), 1))
myList = simulate(15, 50)