Skip to main content

lib_jsl_integration/
runge_kutta_4.rs

1//! The classical fourth-order Runge-Kutta method with a fixed step.
2//!
3//! See the book entry [Runge-Kutta methods](https://jwkunz.github.io/lib_jsl/book/integration/runge-kutta.html).
4
5use crate::stiff_ode::OdeSolution;
6use lib_jsl_core::ErrorsJSL;
7
8/// Solves `y' = f(t, y)` from `(t0, y0)` to `t1` with `n_steps` steps of the classical
9/// fourth-order Runge-Kutta method (RK4), returning the state after every step.
10///
11/// Each step costs four evaluations of `f` and has local error `O(h⁵)`, so the global error is
12/// `O(h⁴)`: halving the step divides it by about 16. There is no error control; use
13/// [`dormand_prince_solve`](crate::dormand_prince::dormand_prince_solve) when the accuracy must be
14/// guaranteed or the solution changes on very different time scales.
15pub fn rk4_solve<F>(f: F, t0: f64, y0: &[f64], t1: f64, n_steps: usize) -> Result<OdeSolution, ErrorsJSL>
16where
17    F: Fn(f64, &[f64]) -> Vec<f64>,
18{
19    if y0.is_empty() || n_steps == 0 || !t0.is_finite() || !t1.is_finite() {
20        return Err(ErrorsJSL::InvalidInputRange("RK4 needs a non-empty state, at least one step and a finite span."));
21    }
22    let n = y0.len();
23    let h = (t1 - t0) / n_steps as f64;
24    let mut solution = OdeSolution { t: vec![t0], y: vec![y0.to_vec()], rejected_steps: 0, nfev: 0, jacobian_evaluations: 0 };
25    let mut y = y0.to_vec();
26    let eval = |t: f64, y: &[f64]| -> Result<Vec<f64>, ErrorsJSL> {
27        let v = f(t, y);
28        if v.len() != n {
29            return Err(ErrorsJSL::IncompatibleArraySizes((v.len(), n)));
30        }
31        Ok(v)
32    };
33    let axpy = |y: &[f64], a: f64, k: &[f64]| -> Vec<f64> { y.iter().zip(k).map(|(y, k)| y + a * k).collect() };
34    for step in 0..n_steps {
35        let t = t0 + step as f64 * h;
36        // ANCHOR: rk4_step
37        let k1 = eval(t, &y)?;
38        let k2 = eval(t + 0.5 * h, &axpy(&y, 0.5 * h, &k1))?;
39        let k3 = eval(t + 0.5 * h, &axpy(&y, 0.5 * h, &k2))?;
40        let k4 = eval(t + h, &axpy(&y, h, &k3))?;
41        for i in 0..n {
42            y[i] += h / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]);
43        }
44        // ANCHOR_END: rk4_step
45        solution.nfev += 4;
46        solution.t.push(if step + 1 == n_steps { t1 } else { t + h });
47        solution.y.push(y.clone());
48    }
49    Ok(solution)
50}
51
52
53#[cfg(test)]
54mod test {
55    use super::*;
56    use std::f64::consts::PI;
57
58    /// The harmonic oscillator y'' = −y as a first-order system.
59    fn oscillator(_t: f64, y: &[f64]) -> Vec<f64> {
60        vec![y[1], -y[0]]
61    }
62
63    #[test]
64    fn fourth_order_convergence_on_a_system() {
65        let error = |n| {
66            let s = rk4_solve(oscillator, 0.0, &[1.0, 0.0], 2.0 * PI, n).unwrap();
67            let y = s.y.last().unwrap();
68            ((y[0] - 1.0).powi(2) + y[1].powi(2)).sqrt()
69        };
70        let ratio = error(50) / error(100);
71        assert!((ratio - 16.0).abs() < 0.5, "{ratio}");
72        assert!(error(200) < 1e-7);
73        let s = rk4_solve(oscillator, 0.0, &[1.0, 0.0], 1.0, 10).unwrap();
74        assert_eq!((s.t.len(), s.nfev, *s.t.last().unwrap()), (11, 40, 1.0));
75    }
76
77    #[test]
78    fn validation() {
79        assert!(rk4_solve(oscillator, 0.0, &[], 1.0, 10).is_err());
80        assert!(rk4_solve(oscillator, 0.0, &[1.0, 0.0], 1.0, 0).is_err());
81        assert!(rk4_solve(|_, _| vec![1.0], 0.0, &[1.0, 0.0], 1.0, 4).is_err());
82    }
83
84}