Hello and thank you for your time and support.
My generalized question is: How should one roll back in a recursive function where specific values have to be returned?
My specific case:
In this problem, I have to check whether a given polynomial has any roots in a given interval, defined by it's margins: x1 and x2.
I have to do this by continuously halving the interval [x1,x2] until the difference between them is at most a value close to zero (for this value, I used the foundroot variable), in which case a root has been found.
This process is done by the recursive findaroot method with parameters x1 and x2 (the interval margins).
Here is how the method works:
The method first checks whether the value for f(x1) and f(x2) (the function's values in x1 and x2) have the same sign, in which case, there is no root in the interval, and returns the noroot value;
Then , it checks whether a root has been found (if x1-x2<=foundroot);
If a root has not been found, it returns minimum between the returned values for one of the intervals, noroot being a very high number in my case. Of course, this doesn't work if a root exceeds the value of noroot.
My question is:
Here is my written code:
//found root variable + value assigned if root is not found in interval (x1,x2)
static final double foundroot = 0.000001;
static final double noroot=999999;
//finds root
static double findaroot(double x1, double x2)
{
if( Math.signum( f(x1,0) ) == Math.signum( f(x2,0) ) )
{
return noroot;
}
else
{
if(Math.abs(x1-x2)<=foundroot)
{
return x1;
}
else
{
return Math.min( findaroot(x1,(x1+x2)/2) , findaroot((x1+x2)/2,x2));
}
}
}
If there's anything unclear, please ask. If you believe my questions/title are unspecific or unclear, please tell me how to modify them.
I will make clarifications as best I can to provide a clear description and, hopefully, a clear answer.
Thank you!
Using a magic number (no root), can be avoided by using a meaningful return value. In this case, you could consider switching to Double instead of double, and using the null value as a "no result" indicator.
This can be applied generically: If you are using recursive functions to calculate a certain outcome, but need to escape as well, using the null value is an acceptable escape. You could consider compound answers as well in case you need more than 1 escape (e.g. the reason for deciding no answer can be found). Use an object to construct your result in that case.
So in this case, alter your function to e.g.
static final double threshold = 0.000001;
//finds root; returns null if none is found
static Double findaroot(double x1, double x2)
{
if( Math.signum( f(x1,0) ) == Math.signum( f(x2,0) ) )
{
return null;
}
else
{
if(Math.abs(x1-x2)<=threshold)
{
return x1;
}
else
{
return Math.min( findaroot(x1,(x1+x2)/2) , findaroot((x1+x2)/2,x2));
}
}
}