Write function for exponential aggregation using R/Python

76 views Asked by At
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)))

Attaching calculation table for easy understanding

enter image description here

Please help me to write function to resolve the above issue using R and python code

2

There are 2 answers

2
gold_cy On BEST ANSWER

Not sure how to do this in R but it is pretty straightforward in Python. You will need numpy for this in order to get the exponential of -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]
0
ekoam On

To me, this question feels more a math problem than a programming one? Anyway, here is an R solution:

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])
}

Output:

exp_agg(c(10, 20, 30, 40, 50), 0.04)

[1]  10.00000  19.21579  56.51717 110.83305 181.14850