package term02.m04_d27;
import term02.m04_d27.functions.ExponentialFunction;
import term02.m04_d27.functions.Function;
public class BinarySearch {
public static void main(String[] args) {
Function f = new ExponentialFunction();
System.out.println(searchRoot(f, 1));
System.out.println(searchRoot(f, Math.E));
}
private static double findLeftBound(Function function, double constant) {
double result = -1;
while (function.getValue(result) > constant) {
result *= 2;
}
return result;
}
private static double findRightBound(Function function, double constant) {
double result = 1;
while (function.getValue(result) < constant) {
result *= 2;
}
return result;
}
private static double searchRoot(Function function, double constant) {
double left = findLeftBound(function, constant);
double right = findRightBound(function, constant);
while (left < right - Function.EPS) {
double mid = (left + right) / 2;
if (function.getValue(mid) < constant) {
left = mid;
} else if (function.getValue(mid) > constant) {
right = mid;
} else {
return mid;
}
}
return left;
}
}