Reputation: 85
I'm trying to create a cumulative list, but my output clearly isn't cumulative. Does anyone know what I'm doing wrong? Thanks
import numpy as np
import math
import random
l=[]
for i in range (50):
def nextTime(rateParameter):
return -math.log(1.0 - random.random()) / rateParameter
a = np.round(nextTime(1/15),0)
l.append(a)
np.cumsum(l)
print(l)
Upvotes: 0
Views: 1596
Reputation: 30268
If you are using numpy
then numpy
is the way to go, however, if all you need to do is provide a cumulative sum then Python3 comes with itertools.accumulate
:
def nextTime(rateParameter):
while True:
yield -math.log(1.0 - random.random()) / rateParameter
>>> list(it.accumulate(map(round, it.islice(nextTime(1/15), 50))))
[2, 9, 14, 26, 27, ...]
Upvotes: 0
Reputation: 78554
The cumulative sum is not taken in place, you have to assign the return value:
cum_l = np.cumsum(l)
print(cum_l)
You don't need to place that function in the for
loop. Putting it outside will avoid defining a new function at every iteration and your code will still produce the expected result.
Upvotes: 1