Christopher Flach Christopher Flach - 2 months ago 29
Python Question

Cumulative Sum List

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)

Answer

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.

Comments