I tried to make this a general purpose integral function but I want to know if it's efficient and idiomatic Rust.
use std::mem;
/// calculates the signed area between the function f and the x axis from
/// x = a to b using a trapezoidal Riemann sum. precision is the number of
/// trapezoids to calculate
pub fn integral<F>(a: f64, b: f64, f: F, precision: u32) -> f64
where F: Fn(f64) -> f64 {
let mut a = a;
let mut b = b;
let mut sign = 1.0;
if a > b {
mem::swap(&mut a, &mut b);
sign = -1.0;
}
let delta = (b - a).abs() / precision as f64;
let mut result = 0.0;
for trapezoid in 0..precision {
let left_side = a + (delta * trapezoid as f64);
let right_size = left_side + delta;
result += 0.5 * (f(left_side) + f(right_size)) * delta;
}
result * sign
}
And here's a test case
fn f(x: f64) -> f64 {
(3.0 * x * x) + (4.0 * x) + 7.0
}
fn main() {
let a = integral(0.0, 11.5, f, 1000000);
println!("{}", a); // expect approx 1865.88
}