public class Bisection {
private double left;
private double right;
private double EPSILON;
// Constructor
public Bisection(double left, double right, double EPSILON) {
this.left = left;
this.right = right;
this.EPSILON = EPSILON;
// Direct call
this.biSect();
}
// Get the Function Value
double functionValue(double x) {
return Function.solve(x);
}
// Check the starting case is valid or not
public boolean isValid(double a, double b) {
if (this.functionValue(a) * this.functionValue(b) <= 0) return true;
else return false;
}
// Bisection Method
public void biSect() {
// Verify the initial values
if (!isValid(this.left, this.right)) {
System.out.println("Invalid Initial Values");
return;
}
// Default root
double root = 0.0;
int iterationCount = 0;
System.out.println("Solving Equation Using Bisection Method: ");
while (this.right - this.left > this.EPSILON) {
System.out.print("Iteration: " + (++iterationCount) + " | ");
root = (this.left + this.right) / 2;
System.out.println("a: " + this.left + ", b: " + this.right + ", root: " + root);
if (functionValue(root) == 0.0) {
System.out.println("Solution Found!");
break;
} else if (functionValue(root) * functionValue(this.left) < 0) {
this.right = root;
} else {
this.left = root;
}
}
System.out.println("\nFinally using bisection method the root is: " + root);
}
}