I am trying to write a program that when given a function and a high and low value, it finds the zero between the high and low. I have written it recursively in a binary search style. When I run a JUnit test, it gives me a stack overflow error unless I give it the base case. Here is the code I am using. Function code:
public class Function implements FunctionInterface{
public static double f(double x){
return x*x-4;
}
}
Code to find zero:
public class NumericalAnalysis {
public double solveForZero(Function f, double low, double high) {
double h = high;
double l = low;
double mid = (h+l)/2;
double x = Function.f(mid);
if(x == 0.0) {
return mid;
}else if(x < 0.0){
l = mid;
return solveForZero(f, h, l);
}else if (x > 0.0){
h = mid;
return solveForZero(f, h, l);
}
return mid;
}
}
Test Code:
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.After;
import org.junit.AfterClass;
public class TestNumericalAnalysis{
private NumericalAnalysis myAnalyzer;
@Before
public void setUp(){
myAnalyzer = new NumericalAnalysis();
}
@Test
public void testSolveForZero(){
double ans = myAnalyzer.solveForZero(new Function(), 0.0, 100.0);
assertEquals(4.0, ans, 0.001);
}
}
The function that I am using is x*x-4, the high is 100.0, and the low is 0.0. My hope is that I am missing something incredibly simple and not seeing it.