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
:
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
:
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));
}
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.
There I left you the code for the recursive approach:
class Program
{
static void Main(string[] args)
{
double recursiveL = CalculateL(100, 100);
double notRecursiveLWrong = NotRecursiveCalculateLWrong(100, 100);
double notRecursiveLRight = NotRecursiveCalculateLRight(100, 100);
}
private static double CalculateL(double p, int maxSteps)
{
if (maxSteps == 0)
{
return (1 / (p + 1));
}
else
{
return (1 / (p + CalculateL(p, maxSteps - 1)));
}
}
private static double NotRecursiveCalculateLWrong(double p, int maxSteps)
{
double result = 0;
for (int i = 0; i < maxSteps; i++)
{
result = (1 / (p + result));
}
return result;
}
private static double NotRecursiveCalculateLRight(double p, int maxSteps)
{
double result = 1 / (p + 1);
for (int i = 0; i < maxSteps; i++)
{
result = (1 / (p + result));
}
return result;
}
}
While making it I was thinking about the fact that for this problem, recursion isn't needed and now I can see that I'm not the only one.
I added my not recursive approach.
Edit:
If you try my code you will see that every method returns the same value, WATCHOUT, this is cause of the low precision in floating points.
The correct approach is NotRecursiveCalculateLRight
which is stated in @John 's answer.