Skip to content
Advertisement

Overwriting an array in Numpy function Python

I am trying to write a numpy function that iterates with itself to update the values of its function. If for example Random_numb was equal to [50, 74, 5, 69, 50]. So the calculations would go like, 10* 50 = 500 for the first calculation, with the equation Starting_val = Starting_val * Random_numb. The Starting_Val would equal to 500 so for the second calculation it would go as 500 * 74 = 37000. Updating the Startin_Val to 37000 from 500. Iterating through the Random_numb as it does the calculations, using element 1: 50 for calculation 1 and element 2 74 for calculation 2 and so on. The calculations would go on until the end of the Random_numb array.

import numpy as np
Starting_val = 10
Random_numb = random.randint(100, size=(5))
Starting_val = Starting_val * Random_numb 

Advertisement

Answer

IIUC you’re looking for prod:

import numpy as np

Starting_val = 10
Random_numb = np.array([50, 74, 5, 69, 50])

Random_numb.prod(initial=Starting_val)
#638250000

If you’re interested in the multiplied values of the array it’ll be cumprod:

Starting_val * Random_numb.cumprod()
# array([      500,     37000,    185000,  12765000, 638250000])
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement