Home > Net >  How to convert a recursive algorithm to a function that outputs a number, given the time
How to convert a recursive algorithm to a function that outputs a number, given the time

Time:02-17

I have a recursive algorithm that runs multiple times, replacing currentValue each time with the output of the previous run (except for the first run, where the value is supplied by the user). Each run calculates the value one year later.

value = constant
  population_factor * coeff_population_factor
  currentValue * coeff_currentValue
  initialValue * coeff_initialValue%
  duration_of_period * coeff_duration_of_period

I would like to be able to convert that into a function of time, so that for a given value t in years, it would return the expected value at that point? I think that would be a regression algorithm, but I'm not sure how to get to that.

I have modelled the curve using the the formula above in excel to get my coefficients, but that obviously only runs on my computer and I'd like to run this in the cloud using node or something, so I can develop some front-ends against it. Ideally some pointers using pure maths or JS, or a library, even, would be greatly appreciated!

CodePudding user response:

I believe you are looking for a for loop. Try this:

# define all of the variables here
currentValue = #put the first-run value here
for i in range(t):
    currentValue = constant \
                     (population_factor * coeff_population_factor) \
                     (currentValue * coeff_currentValue) \
                     (initialValue * coeff_initialValue) \
                     (duration_of_period * coeff_duration_of_period)
# currentValue will have the final result once outside of the for loop

It is not recursive and still gives the accurate answer!

  • Related