amos_bessel_rs/lib.rs
1#![warn(missing_docs, clippy::all, clippy::pedantic)]
2#![allow(
3 clippy::doc_markdown,
4 clippy::too_many_lines,
5 clippy::cast_possible_wrap,
6 clippy::cast_precision_loss,
7 clippy::cast_possible_truncation,
8 clippy::cast_sign_loss
9)]
10//! # amos-bessel-rs: Bessel functions in pure Rust
11//!
12//! A crate implementing pure Rust translations of [Amos' complex
13//! Bessel function algorithms](https://www.netlib.org/amos/)
14//!
15//! The aim of this crate is to translate the Amos Fortran code
16//! into idiomatic Rust, while retaining full compatibility with Amos' code.
17//!
18//! ## Alternatives
19//!
20//! To calculate Bessel functions in Rust there are now several alternatives
21//!
22//! - [This crate](https://docs.rs/amos-bessel-rs/latest/amos_bessel_rs/) - A modern, idiomatic pure-Rust translation of Amos' algorithms.
23//! Features zero-allocation buffer-passing APIs (`_into`), register-resident recurrence loops, and SIMD-friendly Horner polynomial evaluation.
24//! Benchmarks show it consistently matches or outpaces both Fortran AMOS and other translations while offering full `#![no_std]` support.
25//! - [Complex Bessel](http://docs.rs/complex-bessel/latest/complex_bessel/) - A line-by-line translation of Amos code with a very good
26//! [comparison tool](https://github.com/elgar328/complex-bessel-test) to confirm both accuracy and computational speed. Optimised
27//! for accuracy and speed using FMA tools to aid the compiler.
28//! - [Real Bessel](https://crates.io/crates/real-bessel) - A dedicated pure `core` zero-allocation crate that calculates real-only Bessel
29//! functions *J* and *Y* for integer order. Faster for these simple cases.
30//! - [Complex Bessel rs](https://crates.io/crates/complex-bessel-rs/) - A wrapper around the Amos' Fortran functions with a Rust API.
31//! Good if you want guarantees that answers will be identical to Fortran, but requires a Fortran compiler in your toolchain to compile.
32//!
33//! The primary test of this crate is that it gives the same values
34//! (to within approx 10 significant figures, subject to the considerations
35//! below) as the Fortran code for all inputs.
36//!
37//! ## Usage
38//!
39//! The primary interface to this crate are the functions in the crate root:
40//! [bessel_j], [bessel_i], etc.
41//! These functions are implemented for any real `order` (including negative orders)
42//! and real or complex argument `z` (for both `f64` and `f32` via [BesselFloat]). All return a single
43//! value of the function at the given order and argument. If the argument is real then the function
44//! will attempt to return a real output. If the calculated answer is complex, then a [BesselError::ComplexOutputForRealInput]
45//! error will be returned, which contains the complex value, in case it is needed.
46//! If the argument is complex, the output will be complex.
47//!
48//! Other errors returned by these functions are on overflow, failure to converge, or
49//! loss of significance in the answer (triggered by extreme values of inputs). See [BesselError] for more details.
50//!
51//! These functions implement calculation for negative orders using the reflection formulae
52//! from [DLMF](https://dlmf.nist.gov/10).
53//!
54//! ### Amos interface
55//!
56//! Amos' core functions are available in the [amos] module, named `complex_[func]`.
57//! These functions expose additional functionality, but at some loss of simplicity:
58//!
59//! #### Negative orders
60//!
61//! - Like the root functions, the [amos] functions natively support negative orders across all function
62//! families using the reflection identities from DLMF.
63//!
64//! #### Inputs
65//!
66//! - The Amos functions take an additional `scaling` parameter, of type [Scaling], which, if set to [Scaling::Scaled],
67//! returns the scaled Bessel function value. That is, the return value is the function value multiplied by a
68//! (positive or negative) exponential factor to remove the exponential growth or decay that occurs as the argument goes to infinity.
69//! The precise formula for the scaled function value is given in documentation for each function. The simple functions
70//! always return the unscaled function value.
71//!
72//! - The Amos functions take an additional argument `n` which specifies the number of orders to return. The return value is a
73//! vector of `Complex<T>` containing the values of the function at orders `[order, order + 1, ..., order + n - 1]`.
74//! This is implemented because, if multiple orders are required, computing them in a single run of the algorithm
75//! is much more efficient than running it repeatedly.
76//!
77//! #### Return values
78//!
79//! - Sequence functions are available in both allocating forms ([`amos::complex_bessel_j`], etc.) returning `Result<(Vec<Complex<T>>, SequenceInfo), BesselError<T>>`
80//! and zero-allocation slice-filling forms ([`amos::complex_bessel_j_into`], etc.) returning `Result<SequenceInfo, BesselError<T>>`.
81//!
82//! - The returned [`SequenceInfo`] provides metadata about the computation:
83//! - `n_zeros`: the number of elements set to zero due to underflow. Underflow zeroes occur at the **end** of the sequence (highest orders)
84//! for $J_\nu$ and $I_\nu$, and at the **start** of the sequence (lowest orders) for $Y_\nu$, $K_\nu$, and $H_\nu^{(m)}$.
85//! - `partial_loss_of_significance`: `true` if extreme values of $|z|$ or `order` caused argument reduction to lose more than half
86//! of machine precision. The computed values are still returned as `Ok` because the algorithm converged.
87//!
88//! - Errors ([`BesselError`]) implement `Copy` with zero heap allocation and are reserved strictly for true calculation failures
89//! (such as overflow, non-convergence, or complete loss of significance).
90//!
91//! ### Derivatives
92//!
93//! Derivatives of Bessel and Hankel functions with respect to the argument $z$ are provided in the
94//! [`derivatives`] module. For each function family, both the first derivative (e.g. [`derivatives::bessel_j_p`])
95//! and arbitrary $k$-th order derivatives (e.g. [`derivatives::bessel_j_derivative`]) are available:
96//!
97//! ```rust
98//! use amos_bessel_rs::{Scaling, derivatives::{bessel_j_p, bessel_j_derivative}};
99//!
100//! // First derivative J_0'(1.0):
101//! let dj = bessel_j_p(0.0, 1.0).unwrap();
102//!
103//! // Second derivative (d/dz)^2 J_0(1.0):
104//! let d2j = bessel_j_derivative(0.0, 1.0, 2, Scaling::Unscaled).unwrap();
105//! ```
106//!
107//! ## Note on accuracy
108//!
109//! When the magnitude of `z` or (effective) `order` is extremely large, losses of significance
110//! by argument reduction occur in the underlying computations.
111//!
112//! If either one exceeds `u1 = (0.5/eps).sqrt()` (approx `1.3e8` for `f64`), losses exceeding half
113//! of machine precision are likely and `SequenceInfo::partial_loss_of_significance` is set to `true`.
114//! If either `z` or `order` is larger than `u2 = 0.5/eps` (approx `1.8e16` for `f64`), then all
115//! significance is lost and [BesselError::LossOfSignificance] is returned.
116//!
117//! For a full mathematical breakdown of the relative error and phase angle accuracy
118//! based on the original Amos documentation, please see the
119//! [Performance & Accuracy Guide](https://etfrogers.github.io/bessel-rs/).
120//!
121//! ## Branch cuts and signed zero (`-0.0`)
122//!
123//! The functions $Y_\nu$, $K_\nu$, $H_\nu^{(1)}$, and $H_\nu^{(2)}$ possess a
124//! branch cut along the negative real axis $(-\infty, 0]$.
125//!
126//! ### Phase Convention
127//! Following standard DLMF conventions (DLMF 10.11 and 10.25), the principal branch is defined by:
128//!
129//! $$-\pi < \arg(z) \le \pi$$
130//!
131//! The branch cut adheres to the upper half-plane: values on the negative real axis have phase $\arg(z) = +\pi$.
132//!
133//! ### Signed Zero in Floating-Point Arithmetic
134//! In IEEE 754 arithmetic, zero has a distinct sign (`+0.0` vs `-0.0`):
135//! - By standard complex analysis conventions, `Complex::new(-x, 0.0)` corresponds to $\arg(z) = +\pi$ (upper edge of the cut).
136//! - Conversely, `Complex::new(-x, -0.0)` represents an approach from the lower half-plane ($\arg(z) = -\pi$).
137//!
138//! In the underlying Amos algorithm, checks are formulated using `z.im < 0.0`. Under IEEE 754 floating-point
139//! rules, `-0.0 < 0.0` evaluates to `false`. Consequently, both `Complex::new(-x, 0.0)` and `Complex::new(-x, -0.0)`
140//! evaluate consistently on the **upper edge** of the cut ($\arg(z) = +\pi$).
141//!
142//! If values along the lower edge ($\arg(z) \to -\pi$) are required, the standard DLMF cross-cut
143//! continuation relations (DLMF 10.11 and 10.34) should be applied:
144//! - $Y_\nu(z e^{-i\pi}) = e^{i\nu\pi} Y_\nu(z) - 2i\cos(\nu\pi) J_\nu(z)$
145//! - $K_\nu(z e^{-i\pi}) = e^{i\nu\pi} K_\nu(z) + i\pi I_\nu(z)$
146//! - $H_\nu^{(1)}(z e^{-i\pi}) = 2\cos(\nu\pi) H_\nu^{(1)}(z) + e^{-i\nu\pi} H_\nu^{(2)}(z)$
147//!
148#![cfg_attr(not(feature = "std"), no_std)]
149
150#[cfg(feature = "alloc")]
151#[macro_use]
152extern crate alloc;
153
154use num::Complex;
155
156/// Container for the complex_\[func\] version of the Bessel and Airy functions
157/// for finer control of the calculation and results
158pub mod amos;
159
160/// Functions for computing derivatives of Bessel functions with respect to the argument $z$.
161pub mod derivatives;
162pub(crate) mod reflections;
163mod types;
164
165pub use amos::{HankelKind, Scaling};
166use amos::{
167 complex_airy, complex_airy_b, complex_bessel_i_into, complex_bessel_j_into,
168 complex_bessel_k_into, complex_bessel_y_into, complex_hankel1_into, complex_hankel2_into,
169};
170use types::simple_bessel_wrapper;
171pub use types::{BesselError, BesselFloat, BesselInput, SequenceInfo};
172
173// TODO Overflow to positive or negative infinity, or zero?
174
175/// Computes the Bessel function of the first kind Jv(z).
176///
177/// # Arguments
178/// * `order` - The order of the Bessel function (can be non-integer).
179/// * `z` - The complex or real argument.
180///
181/// # Errors
182/// Returns [`BesselError`] if the calculation cannot be completed:
183/// * [`BesselError::ComplexOutputForRealInput`] if `z` is a real float but the result has a
184/// non-negligible imaginary part.
185/// * Numerical failure due to overflow ([`BesselError::Overflow`]), non-convergence
186/// ([`BesselError::DidNotConverge`]), or complete loss of significance ([`BesselError::LossOfSignificance`]).
187///
188/// See [`BesselError`] for descriptions of all variants.
189pub fn bessel_j<FT: BesselFloat, ZT: BesselInput<FT>, OT: Into<FT>>(
190 order: OT,
191 z: ZT,
192) -> Result<ZT, BesselError<FT>> {
193 bessel_j_single(order.into(), z.into()).and_then(ZT::back_from)
194}
195
196/// Computes the modified Bessel function of the first kind Iv(z).
197///
198/// # Arguments
199/// * `order` - The order of the Bessel function.
200/// * `z` - The complex or real argument.
201///
202/// # Errors
203/// Returns [`BesselError`] if the calculation cannot be completed:
204/// * [`BesselError::ComplexOutputForRealInput`] if `z` is a real float but the result has a
205/// non-negligible imaginary part.
206/// * Numerical failure due to overflow ([`BesselError::Overflow`]), non-convergence
207/// ([`BesselError::DidNotConverge`]), or complete loss of significance ([`BesselError::LossOfSignificance`]).
208///
209/// See [`BesselError`] for descriptions of all variants.
210pub fn bessel_i<FT: BesselFloat, ZT: BesselInput<FT>, OT: Into<FT>>(
211 order: OT,
212 z: ZT,
213) -> Result<ZT, BesselError<FT>> {
214 bessel_i_single(order.into(), z.into()).and_then(ZT::back_from)
215}
216
217/// Computes the modified Bessel function of the second kind Kv(z).
218///
219/// # Arguments
220/// * `order` - The order of the Bessel function.
221/// * `z` - The complex or real argument.
222///
223/// # Errors
224/// Returns [`BesselError`] if the calculation cannot be completed:
225/// * [`BesselError::ComplexOutputForRealInput`] if `z` is a real float but the result has a
226/// non-negligible imaginary part.
227/// * Numerical failure due to overflow ([`BesselError::Overflow`]), non-convergence
228/// ([`BesselError::DidNotConverge`]), or complete loss of significance ([`BesselError::LossOfSignificance`]).
229///
230/// See [`BesselError`] for descriptions of all variants.
231pub fn bessel_k<FT: BesselFloat, ZT: BesselInput<FT>, OT: Into<FT>>(
232 order: OT,
233 z: ZT,
234) -> Result<ZT, BesselError<FT>> {
235 bessel_k_single(order.into(), z.into()).and_then(ZT::back_from)
236}
237
238/// Computes the Bessel function of the second kind Yv(z).
239///
240/// # Arguments
241/// * `order` - The order of the Bessel function.
242/// * `z` - The complex or real argument.
243///
244/// # Errors
245/// Returns [`BesselError`] if the calculation cannot be completed:
246/// * [`BesselError::ComplexOutputForRealInput`] if `z` is a real float but the result has a
247/// non-negligible imaginary part (such as for negative real arguments).
248/// * Numerical failure due to overflow ([`BesselError::Overflow`]), non-convergence
249/// ([`BesselError::DidNotConverge`]), or complete loss of significance ([`BesselError::LossOfSignificance`]).
250///
251/// See [`BesselError`] for descriptions of all variants.
252pub fn bessel_y<FT: BesselFloat, ZT: BesselInput<FT>, OT: Into<FT>>(
253 order: OT,
254 z: ZT,
255) -> Result<ZT, BesselError<FT>> {
256 bessel_y_single(order.into(), z.into()).and_then(ZT::back_from)
257}
258
259/// Computes the Hankel function Hv(z) of the first or second kind.
260///
261/// # Arguments
262/// * `order` - The order of the Hankel function.
263/// * `z` - The complex or real argument.
264/// * `kind` - The kind of Hankel function (First or Second).
265///
266/// # Errors
267/// Returns [`BesselError`] if the calculation cannot be completed:
268/// * [`BesselError::ComplexOutputForRealInput`] if `z` is a real float but the result has a
269/// non-negligible imaginary part.
270/// * Numerical failure due to overflow ([`BesselError::Overflow`]), non-convergence
271/// ([`BesselError::DidNotConverge`]), or complete loss of significance ([`BesselError::LossOfSignificance`]).
272///
273/// See [`BesselError`] for descriptions of all variants.
274pub fn hankel<FT: BesselFloat, ZT: BesselInput<FT>, OT: Into<FT>>(
275 order: OT,
276 z: ZT,
277 kind: HankelKind,
278) -> Result<ZT, BesselError<FT>> {
279 match kind {
280 HankelKind::First => hankel1_single(order.into(), z.into()),
281 HankelKind::Second => hankel2_single(order.into(), z.into()),
282 }
283 .and_then(ZT::back_from)
284}
285
286/// Computes the Airy function Ai(z).
287///
288/// # Errors
289/// Returns [`BesselError`] if the calculation cannot be completed:
290/// * [`BesselError::ComplexOutputForRealInput`] if `z` is a real float but the result has a
291/// non-negligible imaginary part.
292/// * Numerical failure due to overflow ([`BesselError::Overflow`]), non-convergence
293/// ([`BesselError::DidNotConverge`]), or complete loss of significance ([`BesselError::LossOfSignificance`]).
294///
295/// See [`BesselError`] for descriptions of all variants.
296pub fn airy<FT: BesselFloat, ZT: BesselInput<FT>>(z: ZT) -> Result<ZT, BesselError<FT>> {
297 complex_airy(z.into(), false, Scaling::Unscaled)
298 .map(|x| x.0)
299 .and_then(ZT::back_from)
300}
301
302/// Computes the derivative of the Airy function Ai'(z).
303///
304/// # Errors
305/// Returns [`BesselError`] if the calculation cannot be completed:
306/// * [`BesselError::ComplexOutputForRealInput`] if `z` is a real float but the result has a
307/// non-negligible imaginary part.
308/// * Numerical failure due to overflow ([`BesselError::Overflow`]), non-convergence
309/// ([`BesselError::DidNotConverge`]), or complete loss of significance ([`BesselError::LossOfSignificance`]).
310///
311/// See [`BesselError`] for descriptions of all variants.
312pub fn airyp<FT: BesselFloat, ZT: BesselInput<FT>>(z: ZT) -> Result<ZT, BesselError<FT>> {
313 complex_airy(z.into(), true, Scaling::Unscaled)
314 .map(|x| x.0)
315 .and_then(ZT::back_from)
316}
317
318/// Computes the Airy function of the second kind Bi(z).
319///
320/// # Errors
321/// Returns [`BesselError`] if the calculation cannot be completed:
322/// * [`BesselError::ComplexOutputForRealInput`] if `z` is a real float but the result has a
323/// non-negligible imaginary part.
324/// * Numerical failure due to overflow ([`BesselError::Overflow`]), non-convergence
325/// ([`BesselError::DidNotConverge`]), or complete loss of significance ([`BesselError::LossOfSignificance`]).
326///
327/// See [`BesselError`] for descriptions of all variants.
328pub fn airy_b<FT: BesselFloat, ZT: BesselInput<FT>>(z: ZT) -> Result<ZT, BesselError<FT>> {
329 complex_airy_b(z.into(), false, Scaling::Unscaled)
330 .map(|x| x.0)
331 .and_then(ZT::back_from)
332}
333
334/// Computes the derivative of the Airy function of the second kind Bi'(z).
335///
336/// # Errors
337/// Returns [`BesselError`] if the calculation cannot be completed:
338/// * [`BesselError::ComplexOutputForRealInput`] if `z` is a real float but the result has a
339/// non-negligible imaginary part.
340/// * Numerical failure due to overflow ([`BesselError::Overflow`]), non-convergence
341/// ([`BesselError::DidNotConverge`]), or complete loss of significance ([`BesselError::LossOfSignificance`]).
342///
343/// See [`BesselError`] for descriptions of all variants.
344pub fn airy_bp<FT: BesselFloat, ZT: BesselInput<FT>>(z: ZT) -> Result<ZT, BesselError<FT>> {
345 complex_airy_b(z.into(), true, Scaling::Unscaled)
346 .map(|x| x.0)
347 .and_then(ZT::back_from)
348}
349
350simple_bessel_wrapper!(bessel_j_single, complex_bessel_j_into);
351simple_bessel_wrapper!(bessel_y_single, complex_bessel_y_into);
352simple_bessel_wrapper!(bessel_i_single, complex_bessel_i_into);
353simple_bessel_wrapper!(bessel_k_single, complex_bessel_k_into);
354simple_bessel_wrapper!(hankel1_single, complex_hankel1_into);
355simple_bessel_wrapper!(hankel2_single, complex_hankel2_into);
356
357#[cfg(all(test, feature = "std"))]
358mod tests;