Reputation: 21
I have a loop running in Python, but want to sum the results. Here's my code:
R=0.05
Timestep = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Cash_flow = np.array([-10000, 300, 1000, 2500, 6000, 6100, 6250, 6250, 6300, 6300, 6200])
for i in Timestep:
Present_value = Cash_flow[i]*(1+R)**-(Timestep[i])
print(Present_value)
And here are the results:
-10000.0
285.714285714
907.029478458
2159.59399633
4936.21484875
4779.50961546
4663.84622898
4441.75831331
4264.08798078
4061.03617217
3806.26217195
I would like to make sum these values; is there a simple way of doing so?
Cheers!
Upvotes: 0
Views: 112
Reputation: 140168
avoid the loop & use vector capability of numpy
sum_of_values = np.sum(Cash_flow[:]*(1+R)**-(Timestep[:]))
print(sum_of_values)
(sum
would also work instead of numpy.sum
)
results in:
24305.0530919
yields the same as the "classical" way, only faster and without loop:
sum_of_values=0
for i in Timestep:
sum_of_values += Cash_flow[i]*(1+R)**-(Timestep[i])
Upvotes: 2
Reputation: 4925
You can simply add my_sum = 0
before the for loop and my_sum += Preset_value
inside for loop after you set Preset_value.
At the end of the program (outside of for loop), you can print it with print(my_sum)
Upvotes: 0