Skip to main content

embedded_maths/embedded-maths-functions/
exp.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Exponential function `e^x` for `f32` on `no_std` embedded targets,
3//! powered by `embedded-exp-f32`.
4//!
5//! Uses Cody-Waite range reduction, a `(2, 2)` Padé approximation over the
6//! reduced interval, and IEEE 754 exponent reconstruction without `libm`,
7//! heap allocation, or loops over `k`.
8//!
9//! # Behavior & Notes
10//!
11//! | Input / Condition | Behavior |
12//! |-------------------|----------|
13//! | `x = 0.0` | Returns `1.0` |
14//! | `x = 1.0` | Returns `~e` (`core::f32::consts::E`) |
15//! | `x <= -87.33654` | Underflows to `0.0` |
16//! | `x >= 88.72284` | Overflows to `f32::INFINITY` |
17//! | `fast-path` feature | Skips explicit bounds/NaN checks when `x` is already validated |
18
19pub use embedded_exp_f32::exp_f32;
20
21/// Computes `e^x` in `f32` without `libm` or `std`.
22pub fn exp(x: f32) -> f32 {
23    exp_f32(x)
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn basic_and_known_values() {
32        assert_eq!(exp(0.0), 1.0);
33        assert!((exp(1.0) - core::f32::consts::E).abs() < 1e-4);
34        assert!((exp(-1.0) - 1.0 / core::f32::consts::E).abs() < 1e-4);
35    }
36
37    #[test]
38    fn bounds_and_overflow_underflow() {
39        assert_eq!(exp(-100.0), 0.0);
40        assert_eq!(exp(100.0), f32::INFINITY);
41        assert!(exp(f32::NAN).is_nan());
42    }
43}