Introduction
Welcome to the Bessel-rs Performance & Accuracy Guide.
bessel-rs is an idiomatic, pure-Rust translation of Amos’ renowned complex Bessel function algorithms (originally written in Fortran).
While porting legacy scientific code to memory-safe languages provides obvious security and ecosystem benefits, users of scientific libraries are rightfully concerned with two primary metrics before adopting a new crate:
- Performance: Is it as fast as the legacy C/Fortran code?
- Accuracy: Does it preserve the mathematical precision and edge-case handling of the original algorithms?
This book serves to transparently document how bessel-rs performs across both of these domains.
Quick Start
amos-bessel-rs is designed to be highly ergonomic and safe, abstracting away the complex multi-return arrays of legacy Fortran into native Rust closures and enums.
Basic Usage
The crate exposes top-level entry points for standard Bessel functions, which will automatically return the evaluated result or an explicit error type if the underlying numeric algorithm diverges.
use num::Complex;
use amos_bessel_rs::bessel_j;
fn main() {
let order = 2.5;
let z = Complex::new(1.0, 2.0);
// Compute the Bessel J function
match bessel_j(order, z) {
Ok(result) => println!("J_{}(z) = {}", order, result),
Err(e) => println!("Failed to compute: {}", e),
}
}
f32 vs f64 Generic Precision
All algorithms are generic over the BesselFloat trait. This means you can drop in f32 arguments and inherently gain the f32 speed boost without modifying your API calls:
#![allow(unused)]
fn main() {
use num::Complex;
use amos_bessel_rs::{bessel_y, BesselError};
// By passing f32 values, the `BesselFloat` trait natively switches
// the underlying algorithmic precision to single-precision float execution.
let order: f32 = 2.5;
let z: Complex<f32> = Complex::new(1.0, 2.0);
let result: Result<Complex<f32>, BesselError<f32>> = bessel_y(order, z);
}
For workloads like computer graphics, DSP audio loops, or machine learning tensors where 32-bit floats are standard, simply providing f32 values unlocks substantial performance wins. (See our Performance Analysis for more).
Performance
This section documents the computational efficiency of bessel-rs.
We evaluate performance across two distinct dimensions:
- Rust vs Fortran: A direct 1-to-1 comparison of this pure Rust implementation against the legacy Fortran bindings (via
complex-bessel-rs). - Precision: f32 vs f64: An analysis of the performance benefits gained when evaluating functions in single precision (
f32) instead of double precision (f64).
Rust vs Fortran Performance
A common question when porting legacy scientific code to a modern language is whether the new implementation sacrifices performance for safety and ergonomics.
To answer this, we benchmarked amos-bessel-rs (our pure Rust implementation) directly against complex-bessel-rs (which provides low-level Rust bindings to the original Amos Fortran binaries compiled with gfortran).
Benchmark Results
Note: All benchmarks were executed on an Apple M2 Pro (ARM64) using Rust 1.95.0. While absolute times will vary depending on your hardware, the comparative speedups should remain relatively consistent across modern CPU architectures.
The benchmarks compare both implementations running the identical algorithms on two datasets:
- Scattered: An array of 46 highly extreme edge cases designed to trigger algorithmic branching.
- Grid: A realistic uniform grid of thousands of sequential points, designed to test typical throughput, caching, and branch prediction.
Performance Comparison: Rust vs Fortran
--------------------------------------------------------------------
Function | Dataset | Rust (ns) | Fortran (ns) | Speedup
--------------------------------------------------------------------
J | Scattered | 17246.05 | 19372.35 | 1.12x
J | Grid | 10856966.43| 12409125.32 | 1.14x
Y | Scattered | 35394.00 | 37235.85 | 1.05x
Y | Grid | 21346008.61| 22750567.22 | 1.07x
I | Scattered | 14733.58 | 17271.79 | 1.17x
I | Grid | 10330456.25| 11532561.09 | 1.12x
K | Scattered | 17786.17 | 18692.93 | 1.05x
K | Grid | 15016672.92| 15571820.65 | 1.04x
--------------------------------------------------------------------
Overall Geometric Mean Speedup (Rust over Fortran): 1.09x
Analysis
Not only does amos-bessel-rs match the performance of the highly-optimized Fortran legacy code, it is actually 9% faster on average.
This is an incredible result. It proves that you can gain all the benefits of pure Rust—including f32 generics, memory safety, excellent cargo integration, and idiomatic error handling—while maintaining state-of-the-art computational performance.
Precision: f32 vs f64
Bessel functions involve intensive iterative algorithms, recurrence relations, and transcendental operations. As a result, calculating them in double precision (f64) requires significantly more computational power than single precision (f32).
Many real-world applications in computer graphics, audio processing, or machine learning only require 32 bits of precision. amos-bessel-rs provides generic algorithms bound by the BesselFloat trait, meaning you can drop in f32 natively and gain significant performance benefits.
Benchmark Results
Note: All benchmarks were executed on an Apple M2 Pro (ARM64) using Rust 1.95.0. While absolute times will vary depending on your hardware, the comparative speedups should remain relatively consistent across modern CPU architectures.
Below is a direct comparison of f32 vs f64 evaluation times using the Criterion framework. The benchmarks are split into two datasets:
- Scattered: An array of 46 highly extreme edge cases designed to trigger the slowest algorithmic paths (e.g., asymptotic expansions vs Miller algorithms).
- Grid: A realistic uniform grid of thousands of sequential points, designed to test typical throughput, caching, and branch prediction.
Performance Comparison: f32 vs f64
------------------------------------------------------------
Function | Dataset | f32 (ns) | f64 (ns) | Speedup
------------------------------------------------------------
J | Scattered | 9192.55 | 17313.19 | 1.88x
J | Grid | 4892837.96 | 9198335.20 | 1.88x
Y | Scattered | 15794.43 | 35795.55 | 2.27x
Y | Grid | 9955819.66 | 19215359.98| 1.93x
I | Scattered | 6398.72 | 15119.08 | 2.36x
I | Grid | 4991749.35 | 8964225.62 | 1.80x
K | Scattered | 9390.94 | 18567.97 | 1.98x
K | Grid | 6510330.20 | 14086508.75| 2.16x
H1 | Scattered | 10777.64 | 24668.69 | 2.29x
H1 | Grid | 6664222.40 | 14094536.78| 2.11x
H2 | Scattered | 12647.01 | 24028.28 | 1.90x
H2 | Grid | 6791329.33 | 14324728.55| 2.11x
Ai | Scattered | 2740.28 | 6914.27 | 2.52x
Ai | Grid | 256551.19 | 568103.49 | 2.21x
Bi | Scattered | 2724.28 | 6913.83 | 2.54x
Bi | Grid | 375262.96 | 863576.61 | 2.30x
------------------------------------------------------------
Overall Geometric Mean Speedup (f32 over f64): 2.13x
Analysis
As shown above, f32 is on average over twice as fast (2.13x) as f64 across the entire suite of functions.
For the Airy functions (Ai, Bi), the speedup is particularly pronounced (approaching ~2.5x), reflecting their reliance on computationally heavy cube roots and fractional powers which execute much faster on f32 ALUs.
Recommendation: Unless your scientific workload strictly requires 64-bit IEEE 754 precision, you should default to f32 arguments when evaluating large quantities of Bessel functions.
Accuracy & Technical Details
This section documents the specific mathematical quirks and legacy conventions carried over from the original Amos Fortran code, and how they are exposed in our Rust API.
Loss of Significance
When translating legacy scientific code into modern memory-safe languages, fixing numeric vulnerabilities is just as important as fixing memory leaks.
In the original Amos Fortran library, mathematical issues during runtime (such as underflows, overflows, or diverging iterations) were handled by silently writing integer error flags to an IERR array parameter (e.g., IERR=3 or IERR=4). Because Fortran lacks native sum types, it was incredibly common for users to completely ignore the IERR argument and accidentally consume the garbage data left in the uninitialized result arrays.
Native Rust Error Handling
amos-bessel-rs eliminates this vulnerability. It wraps all outputs in a Result<T, BesselError<T>>, forcing you to explicitly acknowledge when a mathematical algorithm diverges.
For large arguments z or very large orders nu, trigonometric phase reductions and continued fraction expansions begin to experience severe precision loss.
When evaluating these boundary values, amos-bessel-rs catches the numerical decay and returns one of two critical errors:
Partial Loss of Significance & SequenceInfo
This occurs when the calculation succeeded and the algorithm converged, but argument reduction caused internal precision to drop below half of machine accuracy (due to extreme values of $|z|$ or order).
Rather than returning a fatal error or burying loss-of-precision warnings, all sequence functions return computation metadata via [SequenceInfo]:
#![allow(unused)]
fn main() {
// In `types.rs`:
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SequenceInfo {
/// The number of components explicitly set to zero due to underflow.
pub n_zeros: usize,
/// Whether partial loss of significance occurred during calculation.
pub partial_loss_of_significance: bool,
}
}
- Allocating sequence functions (
complex_bessel_j, etc.) returnResult<(Vec<Complex<T>>, SequenceInfo), BesselError<T>>. - Zero-allocation slice functions (
complex_bessel_j_into, etc.) returnResult<SequenceInfo, BesselError<T>>.
When partial_loss_of_significance is true, the computed values are returned safely in Ok, but mathematically the lower bits of the float are essentially noise.
(Note: Simplified single-value entry points like bessel_j() return Result<T, BesselError<T>> directly, returning the computed value as Ok when the algorithm converged).
BesselError::LossOfSignificance
This occurs when argument reduction resulted in a complete loss of accuracy. The output is mathematically meaningless noise.
In Fortran, this returned IERR=4 and left garbage in the array. In amos-bessel-rs, it returns a strict Err(BesselError::LossOfSignificance), preventing you from accessing undefined values and halting pipeline corruption.
Original Amos Notes on Accuracy
In most complex variable computation, one must evaluate elementary functions. When the magnitude of z or (effective) order is large, losses of significance by argument reduction occur.
Consequently, if either one exceeds u1 = (0.5/eps).sqrt(), then losses exceeding half of machine precision are likely, and SequenceInfo::partial_loss_of_significance is set to true, where eps is the machine precision (f64::EPSILON for double precision). If either z or order is larger than u2 = 0.5/eps, then all significance is lost and LossOfSignificance is returned.
In order to use the int function, arguments must be further restricted not to exceed the largest machine integer, u3 = (i32::MAX as f64) * 0.5. Thus, the magnitude of z and (effective) order is restricted by u2.min(u3). With 64-bit precision, u1, u2, and u3 are approximately 1.3e8, 1.8e16, and 2.1e9.
The approximate relative error in the magnitude of a complex bessel function can be expressed by eps * 10.0.pow(s) where eps is the nominal precision and 10.0.pow(s) represents the increase in error due to argument reduction in the elementary functions. Here, s = 1.0.max(z.abs().log10().abs().max(order.log10().abs()) approximately.
However, the phase angle may have only absolute accuracy. This is most likely to occur when one component (in absolute value) is larger than the other by several orders of magnitude. If one component is 10.0.pow(k) larger than the other, then one can expect only p.log10().abs() - k).max(0) significant digits. Stated another way, when k exceeds the exponent of p, no significant digits remain in the smaller component. However, the phase angle retains absolute accuracy because, in complex arithmetic with precision p, the smaller component will not (as a rule) decrease below p times the magnitude of the larger component. In these extreme cases, the principal phase angle is on the order of +p, -p, pi/2-p, or -pi/2+p.
Scaling Options
Some mathematical functions natively exhibit extreme exponential growth or decay.
For example, the Modified Bessel Functions of the First and Second Kind—$I_\nu(z)$ and $K_\nu(z)$—grow and decay exponentially as the absolute value of $z$ increases.
When evaluating these functions at large arguments, the values easily exceed the maximum representable limit of an f64 float ($\approx 10^{308}$), returning Infinity and destroying the calculation.
Scaling::Scaled
To resolve this, the internal Amos algorithms can compute a mathematically scaled version of the function that strips out the dominant exponential factor, keeping the raw floating-point calculations comfortably within machine bounds.
The low-level complex_bessel_* APIs require you to pass a Scaling enum:
#![allow(unused)]
fn main() {
pub enum Scaling {
Unscaled,
Scaled,
}
}
If you select Scaling::Scaled, the algorithm will compute the Bessel function multiplied by a scaling factor to counteract the exponential growth:
| Function | Returned Scaled Value |
|---|---|
| $J_\nu(z)$ | $e^{- |
| $Y_\nu(z)$ | $e^{- |
| $I_\nu(z)$ | $e^{- |
| $K_\nu(z)$ | $e^{z} K_\nu(z)$ |
| $H^{(1)}_\nu(z)$ | $e^{-\text{Im}(z)} H^{(1)}_\nu(z)$ |
| $H^{(2)}_\nu(z)$ | $e^{\text{Im}(z)} H^{(2)}_\nu(z)$ |
By retrieving this scaled value, your application can safely operate on the mantissa, or defer the exponentiation to a log-space domain where f64 overflow is no longer a risk.
(Note: The simplified top-level functions like bessel_i() automatically use Scaling::Unscaled for standard behavior. You must use complex_bessel_i() to request scaled execution).