问题描述
Input -->[10,20,30,40,50]
Desired Output ---> [10,19.21,56.51,110.83,181.14]
**Calculation**
10-->10
20-->20*exp(-0.04)
30-->30*exp(-0.04)+((30*exp(-0.04))*exp(-0.04))
40--->40*exp(-0.04)+((40*exp(-0.04))*exp(-0.04))+(((40*exp(-0.04))*exp(-0.04))*exp(-0.04)))
附上计算表以便于理解
请帮助我编写函数以使用R和python代码解决上述问题
解决方法
不确定如何在R
中执行此操作,但是在Python
中却非常简单。为此,您将需要numpy
才能获得-0.04
的指数。
import numpy as np
def data_agg(data):
results = []
exp = np.exp(-0.04)
for num in data:
iters = (num // 10) - 1
if iters == 0:
results.append(num)
else:
tmp = 0
while iters > 0:
tmp += num * pow(exp,iters)
iters -= 1
results.append(round(tmp,3))
return results
data_agg(data)
>> [10,19.216,56.517,110.833,181.149]
,
对我来说,这个问题比编程的问题更像是数学问题?无论如何,这是一个R解决方案:
exp_agg <- function(vect,rate) {
n <- seq_along(vect) - 1
m <- exp(-rate) * (1 - exp(-rate * n)) / (1 - exp(-rate))
vect * c(1,m[-1L])
}
输出:
exp_agg(c(10,20,30,40,50),0.04)
[1] 10.00000 19.21579 56.51717 110.83305 181.14850