fn bisection_method(a: f64, b: f64, tolerance: f64) -> f64 {
let mut a = a;
let mut b = b;
if f(a) * f(b) >= 0.0 {
panic!("Bisection method requires that f(a) and f(b) have opposite signs.");
}
let mut midpoint: f64;
while (b - a).abs() >= tolerance {
midpoint = (a + b) / 2.0;
// Check if midpoint is the root
if f(midpoint).abs() < tolerance {
return midpoint;
}
// Determine the subinterval to continue with
if f(a) * f(midpoint) < 0.0 {
b = midpoint; // Root is in the left subinterval
} else {
a = midpoint; // Root is in the right subinterval
}
}
(a + b) / 2.0 // Return the midpoint as the approximation to the root
}
fn main() {
let a = 1.0;
let b = 2.0;
let tolerance = 1e-4;
let root = bisection_method(a, b, tolerance);
println!("The root is approximately: {:.6}", root);