Iterating a Numpy array through arithmetic functions

与世无争的帅哥 提交于 2021-02-10 14:16:29

问题


In the code I have gotten from my previous issue: issue I could use iterations whilst modifying the a value of multiplication. I want to use the .prod function but with iterations of multiplication, division and addition. The calculations will go as follows, for the first calculation 10 + 10 *50/100 = 15 with the equation (Starting_val + Starting_val * Random_numb/100). The first element in Random_numb is 50 and Starting_val is updated to the value of 15. So for the second calculations it will be 15 + 15 *74/100 = 26.1 The value of the Starting_val is updated from 15 to 26.1 in the second calculation. I do not how to iterate this function with numpy. I wish to not use a for loop for this function.

import numpy as np

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

Random_numb.prod(initial=Starting_val)
Starting_val + Starting_val * Random_numb/100

Expected Output:

[15, 26.1, 27.405, 46.314, 69.471 ]

回答1:


Simple artithmetic transformations give you

Starting_val * np.cumprod(Random_numb / 100 + 1)

Result:

array([15.      , 26.1     , 27.405   , 46.31445 , 69.471675])


来源:https://stackoverflow.com/questions/66091981/iterating-a-numpy-array-through-arithmetic-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!