fast_math/exp.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
use core::f32;
use core::f32::consts as f;
use float;
use ieee754::Ieee754;
#[derive(Clone, Copy)]
enum Base {
E,
Two,
}
impl Base {
#[inline(always)]
fn log2(self) -> f32 {
match self {
Base::E => f::LOG2_E,
Base::Two => 1.0,
}
}
#[inline(always)]
fn upper_limit(self) -> f32 {
128.0 / self.log2()
}
#[inline(always)]
fn lower_limit(self) -> f32 {
-127.0 / self.log2()
}
}
#[inline(always)]
fn exp_raw_impl(x: f32, base: Base) -> f32 {
const A: f32 = (1 << float::SIGNIF) as f32;
const MASK: i32 = 0xff800000u32 as i32;
const EXP2_23: f32 = 1.1920929e-7;
const C0: f32 = 0.3371894346 * EXP2_23 * EXP2_23;
const C1: f32 = 0.657636276 * EXP2_23;
const C2: f32 = 1.00172476;
let a = A * base.log2();
let mul = (a * x) as i32;
let floor = mul & MASK;
let frac = (mul - floor) as f32;
let approx = (C0 * frac + C1) * frac + C2;
f32::from_bits(approx.bits().wrapping_add(floor as u32))
}
#[inline(always)]
fn exp_impl(x: f32, base: Base) -> f32 {
if x <= base.lower_limit() {
0.0
} else if x < base.upper_limit() {
exp_raw_impl(x, base)
} else {
// too big, or NaN, so lets overflow to infinity with some
// arithmetic to propagate the NaN.
x + f32::INFINITY
}
}
/// Compute a fast approximation to 2<sup><code>x</code></sup> for
/// -151 ≤ `x` ≤ 151.
///
/// This will return unspecified nonsense if `x` does not satisfy
/// those requirements. Use `exp2` if correct handling is required (at
/// the expense of some speed).
///
/// The maximum relative error for inputs for which the result is
/// normal (`x` ≥ -128) is less than 0.011. For `x` < -128, the
/// relative error in the (subnormal) result can be as large as 1.
#[inline]
pub fn exp2_raw(x: f32) -> f32 {
exp_raw_impl(x, Base::Two)
}
/// Compute a fast approximation to 2<sup><code>x</code></sup>.
///
/// The maximum relative error for inputs for which the result is
/// normal (`x` ≥ -128) is less than 0.011. For `x` < -128, the
/// relative error in the (subnormal) result can be as large as 1.
///
/// If `x` is NaN, `exp2` returns NaN.
///
/// See also `exp2_raw` which only works on -151 ≤ `x` ≤ 151,
/// but is % faster.
#[inline]
pub fn exp2(x: f32) -> f32 {
exp_impl(x, Base::Two)
}
/// Compute a fast approximation to *e*<sup><code>x</code></sup> for
/// -104 ≤ `x` ≤ 104.
///
/// This will return unspecified nonsense if `x` does not satisfy
/// those requirements. Use `exp` if correct handling is required (at
/// the expense of some speed).
///
/// The maximum relative error for inputs for which the result is
/// normal (`x` ≥ -128 ln(2) ≈ -88.7) is less than
/// 0.011. For `x` < -128 ln(2), the relative error in the (subnormal)
/// result can be as large as 1.
#[inline]
pub fn exp_raw(x: f32) -> f32 {
exp_raw_impl(x, Base::E)
}
/// Compute a fast approximation to *e*<sup><code>x</code></sup>.
///
/// The maximum relative error for inputs for which the result is
/// normal (`x` ≥ -128 ln 2 ≈ -88.7) is less than
/// 0.011. For `x` < -128 ln 2, the relative error in the (subnormal)
/// result can be as large as 1.
///
/// If `x` is NaN, `exp` returns NaN.
///
/// See also `exp_raw` which only works on -104 ≤ `x` ≤ 104,
/// but is % faster.
#[inline]
pub fn exp(x: f32) -> f32 {
exp_impl(x, Base::E)
}
#[cfg(test)]
mod tests {
use super::*;
use std::{f32, num};
const PREC: u32 = 1 << 19;
#[test]
fn exp_rel_err_exhaustive() {
let mut max = 0.0;
for i in 0..PREC + 1 {
for j in -5..6 {
for &sign in &[-1.0, 1.0] {
let x = sign * (1.0 + i as f32 / PREC as f32) * 2f32.powi(j * 2);
let e = exp(x);
let t = x.exp();
let rel = e.rel_error(t).abs();
if t.classify() == num::FpCategory::Subnormal {
// subnormal should be approximately right
assert!(rel <= 1.0,
"{:.8}: e = {:.8e}, t = {:.8e}. {:.4}", x, e, t, rel); } else {
if rel > max { max = rel }
// e == t handles the infinity case
assert!(rel <= 0.002,
"{:.8}: e = {:.8e}, t = {:.8e}. {:.4}", x, e, t, rel);
}
}
}
}
println!("maximum {}", max);
}
#[test]
fn exp2_rel_err_exhaustive() {
let mut max = 0.0;
for i in 0..PREC + 1 {
for j in -5..6 {
for &sign in &[-1.0, 1.0] {
let x = sign * (1.0 + i as f32 / PREC as f32) * 2f32.powi(j * 2);
let e = exp2(x);
let t = x.exp2();
let rel = e.rel_error(t).abs();
if t.classify() == num::FpCategory::Subnormal {
// subnormal should be approximately right
assert!(rel <= 1.0,
"{:.8}: e = {:.8e}, t = {:.8e}. {:.4}", x, e, t, rel); } else {
if rel > max { max = rel }
// e == t handles the infinity case
assert!(rel <= 0.002,
"{:.8}: e = {:.8e}, t = {:.8e}. {:.4}", x, e, t, rel);
}
}
}
}
println!("maximum {}", max);
}
#[test]
fn exp_edge_cases() {
assert!(exp(f32::NAN).is_nan());
assert_eq!(exp(f32::NEG_INFINITY), 0.0);
assert!((exp(0.0) - 1.0).abs() < 0.002);
assert_eq!(exp(f32::INFINITY), f32::INFINITY);
}
#[test]
fn exp2_edge_cases() {
assert!(exp2(f32::NAN).is_nan());
assert_eq!(exp2(f32::NEG_INFINITY), 0.0);
assert!((exp2(0.0) - 1.0).abs() < 0.002);
assert_eq!(exp2(f32::INFINITY), f32::INFINITY);
}
}