Rust in numerical

fn f(x: f64) -> f64 {
x.powi(3) + 4.0 * x.powi(2) - 10.0
}

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);

}

It is unclear to me what your question is.

I ran you code here: Rust Playground and the output was:

The root is approximately: 1.365234

You could pass the function as a parameter - instead of having it as a hardcoded global:

fn bisection_method<F>(mut a: f64, mut b: f64, tolerance: f64, f: F) -> f64 
where
    F: Fn(f64) -> f64,
let root = bisection_method(a, b, tolerance, |x| x.powi(3) + 4.0 * x.powi(2) - 10.0);

Can you please reformat your question so all code is correctly formated? Find how here:

Also, do you have a question?

1 Like