Skip to content

Instantly share code, notes, and snippets.

@samuelmale
Last active March 18, 2020 07:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save samuelmale/ef63383c9446964bb1df0a8682bf191e to your computer and use it in GitHub Desktop.
Save samuelmale/ef63383c9446964bb1df0a8682bf191e to your computer and use it in GitHub Desktop.
/**
* Java implementation of the Bisection method for solving equations.
*
* @author samuel
*/
public class Bisection {
private static final float TOLORANCE = (float) 0.001;
/**
* Recursively determines the root for a given function
* between two intervals
*
* <p>
* NOTE: This treats the <code>left</code> parameter as a lower bound and <code>right</code>
* parameter as an upper bound; this means <code>left</code> should be smaller than
* <code>right</code>.
* @param left the first interval
* @param right the second interval
* @return the root for the function
*/
public static double bisect(double left, double right) {
// Check if we have a valid intervals
if (function(right) * function(left) >= 0) {
// Interval not compliate to function
// fail
throw new IllegalArgumentException("Intervals don't fit in function");
}
double mid = (left + right) / 2;
// Soft check if middle point is root
if (function(mid) == 0.0) {
return mid;
}
// Decide intervals for next iteration
if (function(right) * function(mid) < 0 && canMoveOn(mid, right)) {
return bisect(mid, right);
} else if (canMoveOn(left, mid)) {
return bisect(left, mid);
} else {
return mid;
}
}
/**
* The function that drives the bisection
*
* @param x
* @return
*/
public static double function(double x) {
return x*x*x - x*x + 2;
}
/**
* Helper method for {@link #bisect} that determines whether the next iteration is
* appropriate depending on the current intervals
*
* @param left lower bound
* @param right upper bound
* @return <code>true</code> if can move on
*/
private static boolean canMoveOn(double left, double right) {
return (right - left) >= TOLORANCE;
}
/**
* Run program
*/
public static void main(String[] args) {
double root = bisect(-200, 300);
System.out.printf("Root is: %.4f", root);
}
}
@mherman22
Copy link

nice though i have tested it and works better with a tolerance of 0.001

@mherman22
Copy link

private static final float TOLORANCE = (float) 0.001;

@samuelmale
Copy link
Author

private static final float TOLORANCE = (float) 0.001;

Nice catch Herman, I have updated the gist :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment