xsf/scipy_special/powm1.rs
1//! Translated from Boost.Math `boost/math/special_functions/powm1.hpp` (boostorg/math@51fde38),
2//! with the edge cases of `powm1_wrap` in `scipy/special/boost_special_functions.h`
3//! (scipy/scipy@4fb704a).
4
5/// $x^y - 1$
6///
7/// Accurate when $x^y$ is close to 1, e.g. for $x$ near 1 or small $y$. Returns NaN if $x < 0$
8/// and $y$ is not a finite integer.
9///
10/// Corresponds to [`scipy.special.powm1`][scipy].
11///
12/// [scipy]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.powm1.html
13///
14/// # See also
15/// - [`expm1`](crate::expm1) for $e^x - 1$
16/// - [`log1p`](crate::log1p) for $\ln(1 + x)$
17#[must_use]
18pub fn powm1(x: f64, y: f64) -> f64 {
19 // SciPy's `powm1_wrap`: x^0 = 1^y = 1, also for NaN or infinite x or y
20 if y == 0.0 || x == 1.0 {
21 return 0.0;
22 }
23 if x == 0.0 {
24 if y < 0.0 {
25 return f64::INFINITY;
26 } else if y > 0.0 {
27 return -1.0;
28 }
29 }
30
31 // Boost's `powm1_imp_dispatch`
32 if x < 0.0 {
33 // y must be an integer; `fract` is NaN for infinite y, which Boost's `trunc` rejects
34 if y.fract() != 0.0 {
35 return f64::NAN;
36 }
37 if y % 2.0 == 0.0 {
38 return powm1_imp(-x, y);
39 }
40 }
41 powm1_imp(x, y)
42}
43
44/// Boost's `powm1_imp`
45fn powm1_imp(x: f64, y: f64) -> f64 {
46 if (y * (x - 1.0)).abs() < 0.5 || y.abs() < 0.2 {
47 // We don't have any good/quick approximation for log(x) * y
48 // so just try it and see:
49 let l = y * x.ln();
50 if l < 0.5 {
51 return l.exp_m1();
52 }
53 // fall through....
54 }
55
56 // Unlike in SciPy, which returns 0 if x^y overflows for y < 0, the result is infinite.
57 x.powf(y) - 1.0
58}