Skip to main content

xsf/scipy_special/
wright.rs

1//! Translated into pure Rust from `xsf/wright.h` (scipy/xsf@527cef1). Original author: Piers
2//! Lawrence (ACM TOMS 917).
3
4use crate::numpy::nextafter;
5use crate::xsf::c64::{C64, ViaC64, c64};
6use crate::xsf::cephes::dd_real::two_sum;
7use num_complex::Complex64;
8
9const TWOITERTOL: f64 = f64::EPSILON;
10const I: C64 = C64::I;
11
12/// `a + b`, rounded up
13fn add_round_up(a: f64, b: f64) -> f64 {
14    if a.is_nan() || b.is_nan() {
15        return f64::NAN;
16    }
17
18    let (s, err) = two_sum(a, b);
19    if err > 0.0 {
20        // fl(a + b) rounded down
21        nextafter(s, f64::INFINITY)
22    } else {
23        // fl(a + b) rounded up or didn't round
24        s
25    }
26}
27
28/// `a + b`, rounded down
29fn add_round_down(a: f64, b: f64) -> f64 {
30    if a.is_nan() || b.is_nan() {
31        return f64::NAN;
32    }
33
34    let (s, err) = two_sum(a, b);
35    if err < 0.0 {
36        nextafter(s, f64::NEG_INFINITY)
37    } else {
38        s
39    }
40}
41
42fn wrightomega_ext(z: C64) -> C64 {
43    let pi = core::f64::consts::PI;
44    let mut s = 1.0;
45
46    // extract real and imaginary parts of z
47    let (x, y) = (z.re, z.im);
48
49    // compute if we are near the branch cuts
50    let mut ympi = y - pi;
51    let mut yppi = y + pi;
52    let near = 0.1e-1;
53
54    // Test for floating point exceptions
55    if x.is_nan() || y.is_nan() {
56        // NaN output for NaN inpu
57        return C64::NAN;
58    } else if x.is_infinite() && x.is_sign_negative() && (-pi < y) && (y <= pi) {
59        // Signed zeros between branches
60        return if y.abs() <= pi / 2.0 {
61            if y >= 0.0 { C64::ZERO } else { c64(0.0, -0.0) }
62        } else {
63            if y >= 0.0 {
64                c64(-0.0, 0.0)
65            } else {
66                c64(-0.0, -0.0)
67            }
68        };
69    } else if x.is_infinite() || y.is_infinite() {
70        // Asymptotic for large z
71        return c64(x, y);
72    }
73
74    // Test if exactly on the singular points
75    if x == -1.0 && y.abs() == pi {
76        return c64(-1.0, 0.0);
77    }
78
79    // Choose approximation based on region
80    let mut w: C64;
81    #[allow(clippy::manual_range_contains)]
82    if -2.0 < x && x <= 1.0 && 1.0 < y && y < 2.0 * pi {
83        // Region 1: upper branch point
84        // Series about z = -1 + Pi*I
85        let pz = (2.0 * (z + 1.0 - I * pi)).conj().sqrt().conj();
86        w = -1.0
87            + (I + (1.0 / 3.0
88                + (-1.0 / 36.0 * I + (1.0 / 270.0 + 1.0 / 4320.0 * I * pz) * pz) * pz)
89                * pz)
90                * pz;
91    } else if -2.0 < x && x <= 1.0 && -2.0 * pi < y && y < -1.0 {
92        // Region 2: lower branch point
93        // Series about z = -1 - Pi*I
94        let pz = (2.0 * (z + 1.0 + I * pi)).conj().sqrt().conj();
95        w = -1.0
96            + (-I
97                + (1.0 / 3.0 + (1.0 / 36.0 * I + (1.0 / 270.0 - 1.0 / 4320.0 * I * pz) * pz) * pz)
98                    * pz)
99                * pz;
100    } else if x <= -2.0 && -pi < y && y <= pi {
101        // Region 3: between branch cuts
102        // Series: About -infinity
103        let pz = z.exp();
104        w = (1.0 + (-1.0 + (3.0 / 2.0 + (-8.0 / 3.0 + 125.0 / 24.0 * pz) * pz) * pz) * pz) * pz;
105        if w == C64::ZERO {
106            // sf_error(underflow)
107            return w;
108        }
109    } else if (-2.0 < x && x <= 1.0 && -1.0 <= y && y <= 1.0)
110        || ((-2.0 < x) && (x - 0.1e1) * (x - 0.1e1) + y * y <= pi * pi)
111    {
112        // Region 4: Mushroom
113        // Series about z=1
114        let pz = z - 1.0;
115        w = 1.0 / 2.0
116            + 1.0 / 2.0 * z
117            + (1.0 / 16.0 + (-1.0 / 192.0 + (-1.0 / 3072.0 + 13.0 / 61440.0 * pz) * pz) * pz)
118                * pz
119                * pz;
120    } else {
121        let (t, pz) = if x <= -0.105e1 && pi < y && y - pi <= -0.75e0 * (x + 0.1e1) {
122            // Region 5: Top wing
123            // Negative log series
124            let t = z - I * pi;
125            (t, (-t).ln())
126        } else if x <= -0.105e1 && 0.75e0 * (x + 0.1e1) < y + pi && y + pi <= 0.0e0 {
127            // Region 6: Bottom wing
128            // Negative log series
129            let t = z + I * pi;
130            (t, (-t).ln())
131        } else {
132            // Region 7: Everywhere else
133            // Series solution about infinity
134            (z, z.ln())
135        };
136        w = t - pz;
137        if z.norm() > 1e50 {
138            // Series is accurate and the iterative scheme could overflow
139            //
140            // Unlike in xsf, this skips the negligible correction terms below, which can overflow.
141            return w;
142        }
143        let mut fac = pz / t;
144        w += fac;
145        fac /= t;
146        w += fac * (0.5 * pz - 1.0);
147        fac /= t;
148        w += fac * (pz * pz / 3.0 - 3.0 * pz / 2.0 + 1.0);
149    }
150
151    // Regularize if near branch cuts
152    let z = if x <= -0.1e1 + near && (ympi.abs() <= near || yppi.abs() <= near) {
153        s = -1.0;
154        if ympi.abs() <= near {
155            /* Recompute ympi with directed rounding */
156            ympi = add_round_up(y, -pi);
157
158            if ympi <= 0.0 {
159                ympi = add_round_down(y, -pi);
160            }
161
162            x + I * ympi
163        } else {
164            // Recompute yppi with directed rounding
165            yppi = add_round_up(y, pi);
166
167            if yppi <= 0.0 {
168                yppi = add_round_down(y, pi);
169            }
170
171            x + I * yppi
172        }
173    } else {
174        z
175    };
176
177    // Iteration one
178    w = s * w;
179    let r = z - s * w - w.ln();
180    let wp1 = s * w + 1.0;
181    let e = r / wp1 * (2.0 * wp1 * (wp1 + 2.0 / 3.0 * r) - r)
182        / (2.0 * wp1 * (wp1 + 2.0 / 3.0 * r) - 2.0 * r);
183    w *= 1.0 + e;
184
185    // Iteration two
186    if ((2.0 * w * w - 8.0 * w - 1.0) * r.norm().powf(4.0)).norm()
187        >= TWOITERTOL * 72.0 * wp1.norm().powf(6.0)
188    {
189        let r = z - s * w - w.ln();
190        let wp1 = s * w + 1.0;
191        let e = r / wp1 * (2.0 * wp1 * (wp1 + 2.0 / 3.0 * r) - r)
192            / (2.0 * wp1 * (wp1 + 2.0 / 3.0 * r) - 2.0 * r);
193        w *= 1.0 + e;
194    }
195
196    // Undo regularization
197    s * w
198}
199
200fn wrightomega_real(x: f64) -> f64 {
201    if x.is_nan() {
202        return x;
203    }
204
205    // if (isinf(x)) {
206    //     if (x > 0.0) {
207    //         return x;
208    //     } else {
209    //         return 0.0;
210    //     }
211    // }
212    if x.is_infinite() {
213        // Positive infinity is asymptotically x
214        // Negative infinity is zero
215        return if x.is_sign_positive() { x } else { 0.0 };
216    }
217
218    // if (x < -50.0) {
219    //     w = exp(x);
220    //     if (w == 0.0) {
221    //         sf_error("wrightomega", SF_ERROR_UNDERFLOW, "underflow in exponential series");
222    //     }
223    //     return w;
224    // }
225    if x < -50.0 {
226        // Skip the iterative scheme because it exp(x) is already accurate to double precision.
227        let w = x.exp();
228        if w == 0.0 {
229            // underflow in exponential series
230        }
231        return w;
232    }
233    // if (x > 1e20) {
234    //     return x;
235    // }
236    if x > 1e20 {
237        // Skip the iterative scheme because the result is just x to double precision
238        return x;
239    }
240
241    // Split into three distinct intervals (-inf,-2), [-2,1), [1,inf)
242    // if (x < -2.0) {
243    //     w = exp(x);
244    // } else if (x < 1) {
245    //     w = exp(2.0*(x-1.0)/3.0);
246    // } else {
247    //     w = log(x);
248    //     w = x - w + w/x;
249    // }
250    let w = if x < -2.0 {
251        // exponential is approx < 1.3-1 accurate
252        x.exp()
253    } else if x < 1.0 {
254        // on [-2,1) approx < 1.5e-1 accurate
255        (2.0 * (x - 1.0) / 3.0).exp()
256    } else {
257        // infinite series with 2 terms approx <1.7e-1 accurate
258        let w = x.ln();
259        x - w + w / x
260    };
261
262    // Iteration one of Fritsch, Shafer, and Crowley (FSC) iteration
263    // r = x - w - log(w);
264    let r = x - w - w.ln();
265    // wp1 = w + 1.0;
266    let wp1 = w + 1.0;
267    // e = r/wp1*(2.0*wp1*(wp1+2.0/3.0*r)-r)/(2.0*wp1*(wp1+2.0/3.0*r)-2.0*r);
268    let e = r / wp1 * (2.0 * wp1 * (wp1 + 2.0 / 3.0 * r) - r)
269        / (2.0 * wp1 * (wp1 + 2.0 / 3.0 * r) - 2.0 * r);
270    // w = w*(1.0+e);
271    let w = w * (1.0 + e);
272
273    // Iteration two (if needed based on the condition number)
274    // if (fabs((2.0*w*w-8.0*w-1.0)*pow(fabs(r),4.0)) >= TWOITERTOL*72.0*pow(fabs(wp1),6.0)) {
275    //     r = x - w - log(w);
276    //     wp1 = w+1.0;
277    //     e = r/wp1*(2.0*wp1*(wp1+2.0/3.0*r)-r)/(2.0*wp1*(wp1+2.0/3.0*r)-2.0*r);
278    //     w = w*(1.0+e);
279    // }
280    // return w;
281    if ((2.0 * w * w - 8.0 * w - 1.0) * r.abs().powf(4.0)).abs()
282        >= TWOITERTOL * 72.0 * wp1.abs().powf(6.0)
283    {
284        let r = x - w - w.ln();
285        let wp1 = w + 1.0;
286        let e = r / wp1 * (2.0 * wp1 * (wp1 + 2.0 / 3.0 * r) - r)
287            / (2.0 * wp1 * (wp1 + 2.0 / 3.0 * r) - 2.0 * r);
288        w * (1.0 + e)
289    } else {
290        w
291    }
292}
293
294pub trait WrightOmegaArg: crate::sealed::Sealed {
295    fn wrightomega(self) -> Self;
296}
297
298impl WrightOmegaArg for f64 {
299    #[inline]
300    fn wrightomega(self) -> Self {
301        wrightomega_real(self)
302    }
303}
304
305impl WrightOmegaArg for Complex64 {
306    #[inline]
307    fn wrightomega(self) -> Self {
308        self.via(wrightomega_ext)
309    }
310}
311
312/// Wright Omega function, $\omega(z)$
313///
314/// Translated into pure Rust from [`scipy.special.wrightomega`][scipy].
315///
316/// [scipy]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.wrightomega.html
317///
318/// # Definition
319///
320/// Defined as the solution to
321///
322/// $$
323/// \omega + \ln(\omega) = z \\ ,
324/// $$
325///
326/// where $\ln$ is the principal branch of the complex logarithm.
327///
328/// # See also
329/// - [`lambertw`](crate::lambertw): Lambert W function
330#[must_use]
331#[inline]
332pub fn wrightomega<T: WrightOmegaArg>(z: T) -> T {
333    z.wrightomega()
334}