Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing partial recursive function in C#

Tags:

c#

recursion

I am having trouble with somwhow implementing a partial recursive function (at least in my mind though).

for any given p and arbitrary maxsteps = 100, calculate L:

enter image description here

like image 906
SHM Avatar asked Apr 23 '26 07:04

SHM


2 Answers

You could pass the maxsteps down to the recursive function and subtract 1 on each step until you reach 0, with is the end condition:

public double L(double p, int maxSteps)
{
    if (maxSteps == 0)
    {
        return 1 / (p + 1);
    }
    return 1 / (p + L(p, maxSteps - 1));
}
like image 100
Mureinik Avatar answered Apr 24 '26 21:04

Mureinik


I appreciate you want a recursive function, but I figured I'd provide a non-recursive alternative in case it turns out to be preferred:

private static double CalculateL(double p, int maxsteps)
{
    double val = 1 / (p + 1);
    for (int i = 1; i <= maxsteps; ++i)
    {
        val = 1 / (p + val);
    }
    return val;
}

I'm not 100% sure about maxsteps, based on the other answers. If the answer isn't right, then you probably want < maxsteps where I've got <= maxsteps.

Also, please read Is floating point math broken? if you're expecting very precise results.

like image 42
DiplomacyNotWar Avatar answered Apr 24 '26 19:04

DiplomacyNotWar