-
Notifications
You must be signed in to change notification settings - Fork 72
/
trapezoidal_integration.rs
59 lines (50 loc) · 1.44 KB
/
trapezoidal_integration.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
pub fn trapezoidal_integral<F>(a: f64, b: f64, f: F, precision: u32) -> f64
where
F: Fn(f64) -> f64,
{
if a > b {
return trapezoidal_integral(b, a, f, precision);
}
let delta = (b - a) / precision as f64;
(0..precision)
.map(|trapezoid| {
let left_side = a + (delta * trapezoid as f64);
let right_side = left_side + delta;
0.5 * (f(left_side) + f(right_side)) * delta
})
.sum()
}
#[allow(dead_code)]
fn main() {
let f = |x: f64| x.powi(3);
let result = trapezoidal_integral(0.0, 1.0, f, 1000);
println!("{}", result);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_integral() {
let f = |x: f64| x.powi(2);
let result = trapezoidal_integral(0.0, 1.0, f, 1000);
assert!((result - 1.0 / 3.0).abs() < 0.0001);
}
#[test]
fn test_precision() {
let f = |x: f64| x.powi(2);
let result = trapezoidal_integral(0.0, 1.0, f, 10000);
assert!((result - 1.0 / 3.0).abs() < 0.00001);
}
#[test]
fn test_negative() {
let f = |x: f64| x.powi(2);
let result = trapezoidal_integral(-1.0, 1.0, f, 10000);
assert!((result - 2.0 / 3.0).abs() < 0.00001);
}
#[test]
fn test_negative_precision() {
let f = |x: f64| x.powi(2);
let result = trapezoidal_integral(-1.0, 1.0, f, 100000);
assert!((result - 2.0 / 3.0).abs() < 0.000001);
}
}