Skip to main content

xsf/scipy_special/
agm.rs

1//! Translated from scipy/special/_agm.pxd
2
3use core::f64::consts::FRAC_PI_4;
4
5const SQRT_HALF_MAX: f64 = 9.480_751_908_109_176e+153; // sqrt(np.finfo(float).max / 2.0)
6const INV_SQRT_HALF_MAX: f64 = 1.054_768_661_486_3e-154; // 1.0 / SQRT_HALF_MAX;
7
8/// Arithmetic-geometric mean, iterative implementation
9/// a and b must be positive (not zero, not nan).
10#[inline]
11fn agm_iter(a: f64, b: f64) -> f64 {
12    let (mut a, mut b) = (a, b);
13    let mut count = 20;
14    let mut amean = 0.5 * a + 0.5 * b;
15    while count > 0 && amean != a && amean != b {
16        (a, b) = (amean, a.sqrt() * b.sqrt());
17        amean = 0.5 * a + 0.5 * b;
18        count -= 1;
19    }
20
21    amean
22}
23
24/// Arithmetic-geometric mean
25///
26/// Corresponds to [`scipy.special.agm`][scipy].
27///
28/// [scipy]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.agm.html
29#[must_use]
30#[inline]
31pub fn agm(a: f64, b: f64) -> f64 {
32    if a.is_nan() || b.is_nan() {
33        f64::NAN
34    } else if (a < 0.0 && b > 0.0) || (a > 0.0 && b < 0.0) {
35        // a and b have opposite sign
36        f64::NAN
37    } else if (a.is_infinite() || b.is_infinite()) && (a == 0.0 || b == 0.0) {
38        // one value is inf and the other is 0
39        f64::NAN
40    } else if a == 0.0 || b == 0.0 {
41        // at least one of the arguments is 0
42        0.0
43    } else if a == b {
44        a
45    } else {
46        let (sgn, a, b) = if a < 0.0 { (-1.0, -a, -b) } else { (1.0, a, b) };
47
48        // At this point, a and b are both positive and not nan.
49
50        if INV_SQRT_HALF_MAX < a && a < SQRT_HALF_MAX && INV_SQRT_HALF_MAX < b && b < SQRT_HALF_MAX
51        {
52            let e = 4.0 * a * b / (a + b).powi(2);
53            sgn * FRAC_PI_4 * (a + b) / crate::ellipkm1(e)
54        } else {
55            // At least one value is "extreme" (very big or very small).
56            // Use the iteration to avoid overflow or underflow.
57            sgn * agm_iter(a, b)
58        }
59    }
60}