Skip to main content

lib_jsl_special_functions/
lambert_w.rs

1//! The Lambert W function on every complex branch.
2//!
3//! `W_k(z)` solves `w e^w = z` on branch `k ∈ ℤ` (Corless, Gonnet, Hare, Jeffrey and Knuth,
4//! 1996). `W_0` and `W_{−1}` are real on `[−1/e, ∞)` and `[−1/e, 0)`; the branch cut of `W_0` is
5//! `(−∞, −1/e]`, and the real interval of `W_{−1}` is reached from the upper half plane (so
6//! `W_{−1}(x + 0i)` is real there, matching [`crate::lambert_w_m1`]). For real arguments,
7//! [`crate::lambert_w0`] and [`crate::lambert_w_m1`] are faster.
8//!
9//! See the book entry [The Lambert W function](https://jwkunz.github.io/lib_jsl/book/special_functions/lambert-w.html#the-lambert-w-function).
10
11use num_complex::Complex;
12use std::f64::consts::{E, PI};
13
14type C64 = Complex<f64>;
15
16/// The Lambert W function `W_k(z)` on branch `k`. Returns `−∞` for `W_k(0)` with `k ≠ 0` and
17/// NaN for non-finite input.
18pub fn lambert_w(k: i32, z: C64) -> C64 {
19    if !z.re.is_finite() || !z.im.is_finite() {
20        return C64::new(f64::NAN, f64::NAN);
21    }
22    if z == C64::new(0.0, 0.0) {
23        return if k == 0 { z } else { C64::new(f64::NEG_INFINITY, 0.0) };
24    }
25    let branch_point = C64::new(-1.0 / E, 0.0);
26    let distance = (z - branch_point).norm();
27    let upper = z.im >= 0.0;
28    let mut w = if (k == 0 && distance < 1.0) || (distance < 0.3 && ((k == -1 && upper) || (k == 1 && !upper))) {
29        // Series about the branch point in p = ±√(2(ez + 1)).
30        let mut p = (2.0 * (E * z + 1.0)).sqrt();
31        if k != 0 {
32            p = -p;
33        }
34        -1.0 + p - p * p / 3.0 + 11.0 / 72.0 * p * p * p
35    } else if k == 0 && z.norm() < 0.5 {
36        // Near the origin W ≈ z / (1 + z).
37        z / (1.0 + z)
38    } else if k == 0 && z.norm() < 3.0 {
39        (1.0 + z).ln()
40    } else {
41        // Asymptotic expansion; ln z + 2πik is bounded away from zero here.
42        let l1 = z.ln() + C64::new(0.0, 2.0 * PI * k as f64);
43        l1 - l1.ln() + l1.ln() / l1
44    };
45    // Halley iteration on f(w) = w e^w − z.
46    for _ in 0..100 {
47        let ew = w.exp();
48        let f = w * ew - z;
49        let wp1 = w + 1.0;
50        let denom = ew * wp1 - (w + 2.0) * f / (2.0 * wp1);
51        if denom.norm() == 0.0 || !denom.re.is_finite() || !denom.im.is_finite() {
52            break;
53        }
54        let dw = f / denom;
55        w -= dw;
56        if dw.norm() <= 4.0 * f64::EPSILON * (1.0 + w.norm()) {
57            break;
58        }
59    }
60    w
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use crate::inverse_x_log_x::{lambert_w0, lambert_w_m1};
67
68    fn residual(w: C64, z: C64) -> f64 {
69        (w * w.exp() - z).norm() / z.norm().max(1e-300)
70    }
71
72    #[test]
73    fn agrees_with_the_real_branches_and_known_values() {
74        for &x in &[-0.3678, -0.36, -0.2, -0.01, 0.0, 0.3, 1.0, 10.0, 1e6] {
75            let w = lambert_w(0, C64::new(x, 0.0));
76            assert!((w.re - lambert_w0(x)).abs() < 1e-12 * (1.0 + w.re.abs()) && w.im.abs() < 1e-12, "W0({x}) = {w}");
77        }
78        for &x in &[-0.3678, -0.3, -0.1, -1e-3, -1e-10] {
79            let w = lambert_w(-1, C64::new(x, 0.0));
80            assert!((w.re - lambert_w_m1(x)).abs() < 1e-11 * w.re.abs() && w.im.abs() < 1e-12, "W-1({x}) = {w}");
81        }
82        // W_0(i) and the omega constant W_0(1).
83        let wi = lambert_w(0, C64::new(0.0, 1.0));
84        assert!((wi - C64::new(0.374_699_020_737_117_5, 0.576_412_723_031_435_3)).norm() < 1e-14);
85        assert!((lambert_w(0, C64::new(1.0, 0.0)).re - 0.567_143_290_409_783_8).abs() < 1e-15);
86        // W_0 below the branch point is complex: W_0(−1) = −0.3181… + 1.3372…i.
87        let wm = lambert_w(0, C64::new(-1.0, 0.0));
88        assert!((wm - C64::new(-0.318_131_505_204_764_1, 1.337_235_701_430_689_4)).norm() < 1e-13, "{wm}");
89        assert_eq!(lambert_w(2, C64::new(0.0, 0.0)).re, f64::NEG_INFINITY);
90    }
91
92    #[test]
93    fn solves_w_exp_w_on_many_branches_with_the_asymptotic_imaginary_part() {
94        for k in -4..=4 {
95            for &(re, im) in &[(1.0, 0.0), (-2.0, 0.5), (0.1, -3.0), (-0.36, 1e-3), (50.0, 20.0), (-1e-4, -1e-4)] {
96                let z = C64::new(re, im);
97                let w = lambert_w(k, z);
98                assert!(residual(w, z) < 1e-13, "k={k} z={z}: {w}");
99                // Each branch occupies a strip of imaginary parts (Corless et al., figure 4).
100                let (lo, hi) = match k {
101                    0 => (-PI, PI),
102                    k if k > 0 => ((2 * k - 2) as f64 * PI, (2 * k + 1) as f64 * PI),
103                    k => ((2 * k - 1) as f64 * PI, (2 * k + 2) as f64 * PI),
104                };
105                assert!(w.im >= lo - 1e-12 && w.im <= hi + 1e-12, "k={k} z={z}: {w} outside its strip");
106            }
107            // For large |z|, W_k(z) ≈ ln z + 2πik − ln(ln z + 2πik), which identifies the branch.
108            let z = C64::new(3e5, -7e5);
109            let l1 = z.ln() + C64::new(0.0, 2.0 * PI * k as f64);
110            assert!((lambert_w(k, z) - (l1 - l1.ln())).norm() < 0.5, "branch k={k}");
111        }
112        // Conjugate symmetry W_k(conj z) = conj W_{−k}(z) off the cut.
113        let z = C64::new(0.7, 1.9);
114        assert!((lambert_w(2, z.conj()) - lambert_w(-2, z).conj()).norm() < 1e-13);
115    }
116}