mod common;
use core::mem::MaybeUninit;
use common::{read, BinaryOp, Rng, UlpScalar, UnaryOp, PREC};
use elem_simd_math::{bessel, f32 as ops32, f64 as ops64};
use rug::Float;
const I0E_F64_ULP: f64 = 6.0;
const I1E_F64_ULP: f64 = 8.0;
const BESSEL_F32_ULP: f64 = 0.5001;
const XLOGY_ULP: f64 = 1.5;
const TABLE_F64: &str = include_str!("data/bessel_ref_f64.csv");
const TABLE_F32: &str = include_str!("data/bessel_ref_f32.csv");
struct Row {
func: &'static str,
x: f64,
value: Float,
}
fn parse_table(text: &'static str) -> Vec<Row> {
text.lines()
.skip(1)
.map(|line| {
let mut it = line.split(',');
let func = match it.next().unwrap() {
"i0e" => "i0e",
"i1e" => "i1e",
other => panic!("unknown function {other}"),
};
let x = f64::from_bits(u64::from_str_radix(it.next().unwrap(), 16).unwrap());
let value = Float::with_val(192, Float::parse(it.next().unwrap()).unwrap());
Row { func, x, value }
})
.collect()
}
fn run1<T: Copy>(op: UnaryOp<T>, xs: &[T]) -> Vec<T> {
let mut out = vec![MaybeUninit::uninit(); xs.len()];
op(xs, &mut out).unwrap();
read(out)
}
fn run2<T: Copy>(op: BinaryOp<T>, xs: &[T], ys: &[T]) -> Vec<T> {
let mut out = vec![MaybeUninit::uninit(); xs.len()];
op(xs, ys, &mut out).unwrap();
read(out)
}
fn region(ax: f64) -> &'static str {
if ax <= 1.0 {
"[0,1]"
} else if ax <= 8.0 {
"(1,8]"
} else if ax <= 64.0 {
"(8,64]"
} else if ax <= 1e8 {
"(64,1e8]"
} else {
"(1e8,max]"
}
}
fn check_table<T: UlpScalar + Copy + PartialEq + std::fmt::Debug>(
rows: &[Row],
func: &str,
bound: f64,
run: impl Fn(&[T]) -> Vec<T>,
) {
let sel: Vec<&Row> = rows.iter().filter(|r| r.func == func).collect();
let xs: Vec<T> = sel.iter().map(|r| T::from_f64(r.x)).collect();
let got = run(&xs);
let mut worst: std::collections::BTreeMap<&str, (f64, f64)> = Default::default();
for ((row, &g), &x) in sel.iter().zip(got.iter()).zip(xs.iter()) {
let ulp = T::ulp(g, &row.value);
let e = worst.entry(region(row.x.abs())).or_insert((0.0, 0.0));
if ulp > e.0 {
*e = (ulp, x.widen());
}
assert!(
ulp <= bound,
"{func}: x={:e}, got {:e}, want {}, {ulp} ULP > {bound}",
x.widen(),
g.widen(),
row.value
);
}
for (r, (u, x)) in worst {
println!(
"{func} {} region {r}: max {u:.3} ULP (at x={x:e})",
std::any::type_name::<T>()
);
}
}
#[test]
fn i0e_i1e_f64_match_mpmath() {
let rows = parse_table(TABLE_F64);
check_table::<f64>(&rows, "i0e", I0E_F64_ULP, |x| run1(ops64::i0e, x));
check_table::<f64>(&rows, "i1e", I1E_F64_ULP, |x| run1(ops64::i1e, x));
}
#[test]
fn i0e_i1e_f32_match_mpmath() {
let rows = parse_table(TABLE_F32);
check_table::<f32>(&rows, "i0e", BESSEL_F32_ULP, |x| run1(ops32::i0e, x));
check_table::<f32>(&rows, "i1e", BESSEL_F32_ULP, |x| run1(ops32::i1e, x));
}
#[test]
fn i0e_i1e_bit_identical_to_scalar_reference() {
for (text, is32) in [(TABLE_F64, false), (TABLE_F32, true)] {
let xs: Vec<f64> = parse_table(text)
.iter()
.filter(|r| r.func == "i0e")
.map(|r| r.x)
.collect();
if is32 {
let xs32: Vec<f32> = xs.iter().map(|&x| x as f32).collect();
for (&x, (a, b)) in xs32.iter().zip(
run1(ops32::i0e, &xs32)
.into_iter()
.zip(run1(ops32::i1e, &xs32)),
) {
assert_eq!(
a.to_bits(),
(bessel::i0e(x as f64) as f32).to_bits(),
"i0e f32 {x:e}"
);
assert_eq!(
b.to_bits(),
(bessel::i1e(x as f64) as f32).to_bits(),
"i1e f32 {x:e}"
);
}
} else {
for (&x, (a, b)) in xs
.iter()
.zip(run1(ops64::i0e, &xs).into_iter().zip(run1(ops64::i1e, &xs)))
{
assert_eq!(a.to_bits(), bessel::i0e(x).to_bits(), "i0e f64 {x:e}");
assert_eq!(b.to_bits(), bessel::i1e(x).to_bits(), "i1e f64 {x:e}");
}
}
}
}
#[test]
fn i0e_i1e_special_values() {
let inf = f64::INFINITY;
let xs = [
0.0,
-0.0,
inf,
-inf,
f64::NAN,
f64::MAX,
-f64::MAX,
5e-324,
8.0,
-8.0,
];
let a = run1(ops64::i0e, &xs);
let b = run1(ops64::i1e, &xs);
assert_eq!(a[0], 1.0);
assert_eq!(a[1], 1.0);
assert_eq!(a[2], 0.0);
assert_eq!(a[3], 0.0);
assert!(a[4].is_nan() && b[4].is_nan());
assert!(a[5] > 0.0 && a[5].is_finite() && a[5] < 1e-150);
assert_eq!(a[5], a[6]);
assert_eq!(a[7], 1.0);
assert_eq!(a[8], a[9]);
assert_eq!(b[0].to_bits(), 0.0f64.to_bits());
assert_eq!(
b[1].to_bits(),
(-0.0f64).to_bits(),
"i1e is odd, including the sign of zero"
);
assert_eq!(b[2].to_bits(), 0.0f64.to_bits());
assert_eq!(b[3].to_bits(), (-0.0f64).to_bits());
assert!(b[5] > 0.0 && b[5].is_finite());
assert_eq!(b[5], -b[6]);
assert_eq!(b[8], -b[9]);
for x in [1e3, 1e5, 1e10, 1e100, 1e300] {
let r = run1(ops64::i0e, &[x])[0];
let series = 1.0
+ 1.0 / (8.0 * x)
+ 9.0 / (128.0 * x * x)
+ 225.0 / (3072.0 * x * x * x)
+ 11025.0 / (98304.0 * x * x * x * x);
let asym = 1.0 / (2.0 * std::f64::consts::PI * x).sqrt() * series;
assert!((r / asym - 1.0).abs() < 2e-15, "x={x:e}: {r:e} vs {asym:e}");
}
let f = [f32::MAX, f32::INFINITY, 1e-45f32, f32::NAN];
let a32 = run1(ops32::i0e, &f);
assert!(a32[0] > 0.0 && a32[0].is_finite());
assert_eq!(a32[1], 0.0);
assert_eq!(a32[2], 1.0);
assert!(a32[3].is_nan());
}
fn xlogy_oracle(x: &Float, y: &Float) -> Float {
let mut l = Float::with_val(PREC, y);
l.ln_mut();
l * x
}
fn xlogy_inputs(rng: &mut Rng, n: usize, limit: f64) -> (Vec<f64>, Vec<f64>) {
let mut xs = Vec::new();
let mut ys = Vec::new();
let lim = limit.log10();
for i in 0..n {
let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
let x = sign * 10f64.powf(rng.range(-lim * 0.4, lim * 0.4, 1e300));
let y = match i % 4 {
0 => 10f64.powf(rng.range(-lim * 0.9, lim * 0.9, 1e300)),
1 => 1.0 + rng.range(-1e-3, 1e-3, 1.0), 2 => 1.0 + rng.range(-1e-10, 1e-10, 1.0),
_ => rng.range(0.0, 50.0, 1e300),
};
xs.push(x);
ys.push(y);
}
(xs, ys)
}
fn check_xlogy<T: UlpScalar + Copy>(
xs: &[f64],
ys: &[f64],
run: impl Fn(&[T], &[T]) -> Vec<T>,
) -> f64 {
let xt: Vec<T> = xs.iter().map(|&v| T::from_f64(v)).collect();
let yt: Vec<T> = ys.iter().map(|&v| T::from_f64(v)).collect();
let got = run(&xt, &yt);
let mut worst = 0.0f64;
for i in 0..xt.len() {
let want = xlogy_oracle(&xt[i].to_float(), &yt[i].to_float());
if want.is_zero() || !want.is_finite() {
continue;
}
let ulp = T::ulp(got[i], &want);
worst = worst.max(ulp);
assert!(
ulp <= XLOGY_ULP,
"xlogy({:e}, {:e}) = {:e}, want {want}, {ulp} ULP",
xt[i].widen(),
yt[i].widen(),
got[i].widen()
);
}
worst
}
#[test]
fn xlogy_matches_mpfr() {
let mut rng = Rng::new(0x51ed_270b_1234_5678);
let (xs, ys) = xlogy_inputs(&mut rng, 20000, 1e300);
println!(
"xlogy f64 max {:.3} ULP",
check_xlogy::<f64>(&xs, &ys, |a, b| run2(ops64::xlogy, a, b))
);
let (xs, ys) = xlogy_inputs(&mut rng, 20000, 1e38);
println!(
"xlogy f32 max {:.3} ULP",
check_xlogy::<f32>(&xs, &ys, |a, b| run2(ops32::xlogy, a, b))
);
}
#[test]
fn xlogy_special_cases_follow_scipy() {
let inf = f64::INFINITY;
let nan = f64::NAN;
let cases: &[(f64, f64, Option<f64>)] = &[
(0.0, 0.0, Some(0.0)),
(0.0, inf, Some(0.0)),
(0.0, nan, None),
(0.0, -1.0, Some(0.0)),
(0.0, -inf, Some(0.0)),
(-0.0, 0.0, Some(0.0)),
(0.0, 5e-324, Some(0.0)),
(1.0, 0.0, Some(-inf)),
(2.5, 0.0, Some(-inf)),
(5e-324, 0.0, Some(-inf)),
(-2.5, 0.0, Some(inf)),
(1.0, -1.0, None),
(1.0, nan, None),
(nan, 1.0, None),
(nan, 0.0, None),
(inf, 1.0, None),
(inf, 2.0, Some(inf)),
(-inf, 2.0, Some(-inf)),
(1.0, inf, Some(inf)),
(-1.0, inf, Some(-inf)),
(3.0, 1.0, Some(0.0)),
];
let xs: Vec<f64> = cases.iter().map(|c| c.0).collect();
let ys: Vec<f64> = cases.iter().map(|c| c.1).collect();
let got = run2(ops64::xlogy, &xs, &ys);
let got32 = run2(
ops32::xlogy,
&xs.iter().map(|&v| v as f32).collect::<Vec<_>>(),
&ys.iter().map(|&v| v as f32).collect::<Vec<_>>(),
);
for (i, &(x, y, want)) in cases.iter().enumerate() {
let f32_valid = x == 0.0 || (x as f32) != 0.0;
match want {
None => {
assert!(got[i].is_nan(), "f64 xlogy({x}, {y}) should be NaN");
assert!(
!f32_valid || got32[i].is_nan(),
"f32 xlogy({x}, {y}) should be NaN"
);
}
Some(w) => {
assert_eq!(got[i], w, "f64 xlogy({x}, {y})");
if f32_valid {
assert_eq!(got32[i] as f64, w, "f32 xlogy({x}, {y})");
}
}
}
}
for &(x, y, want) in cases {
let r = bessel::xlogy(x, y);
match want {
None => assert!(r.is_nan()),
Some(w) => assert_eq!(r, w),
}
}
}
#[test]
fn tails_match_whole_buffer() {
let mut rng = Rng::new(7);
let xs: Vec<f64> = (0..300).map(|_| rng.range(-40.0, 40.0, 1e300)).collect();
let ys: Vec<f64> = (0..300).map(|_| rng.range(0.0, 40.0, 1e300)).collect();
let (wi0, wi1, wx) = (
run1(ops64::i0e, &xs),
run1(ops64::i1e, &xs),
run2(ops64::xlogy, &xs, &ys),
);
for n in [1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 33, 257] {
let a: Vec<u64> = run1(ops64::i0e, &xs[..n])
.iter()
.map(|v| v.to_bits())
.collect();
let b: Vec<u64> = run1(ops64::i1e, &xs[..n])
.iter()
.map(|v| v.to_bits())
.collect();
let c: Vec<u64> = run2(ops64::xlogy, &xs[..n], &ys[..n])
.iter()
.map(|v| v.to_bits())
.collect();
for i in 0..n {
assert_eq!(a[i], wi0[i].to_bits());
assert_eq!(b[i], wi1[i].to_bits());
assert_eq!(c[i], wx[i].to_bits());
}
}
}
#[test]
fn length_mismatch_is_reported() {
let mut out = vec![MaybeUninit::<f64>::uninit(); 3];
assert!(ops64::i0e(&[1.0, 2.0], &mut out).is_err());
assert!(ops64::xlogy(&[1.0, 2.0, 3.0], &[1.0, 2.0], &mut out).is_err());
}
#[cfg(feature = "simd")]
mod levels {
use super::*;
use elem_simd_math::common::{F32s, F64s};
use elem_simd_math::{f32x, f64x};
use fearless_simd::prelude::*;
use fearless_simd::{dispatch, Level, Simd};
fn levels() -> Vec<(&'static str, Level)> {
let best = Level::new();
let mut v: Vec<(&'static str, Level)> = Vec::new();
#[cfg(target_arch = "x86_64")]
{
if let Some(t) = best.as_sse2() {
v.push(("sse2", Level::Sse2(t)));
}
if let Some(t) = best.as_sse4_2() {
v.push(("sse4.2", Level::Sse4_2(t)));
}
if let Some(t) = best.as_avx2() {
v.push(("avx2", Level::Avx2(t)));
}
if let Some(t) = best.as_avx512() {
v.push(("avx512", Level::Avx512(t)));
}
}
if v.is_empty() {
v.push(("native", best));
}
v
}
#[inline(always)]
fn apply64<S: Simd>(simd: S, k: fn(S, F64s<S>) -> F64s<S>, xs: &[f64]) -> Vec<f64> {
let n = F64s::<S>::LEN;
xs.chunks(n)
.flat_map(|c| {
let mut p = vec![1.0; n];
p[..c.len()].copy_from_slice(c);
let r = k(simd, F64s::<S>::from_slice(simd, &p)).to_array();
r.as_ref()[..c.len()].to_vec()
})
.collect()
}
#[inline(always)]
fn apply64_2<S: Simd>(
simd: S,
k: fn(S, F64s<S>, F64s<S>) -> F64s<S>,
xs: &[f64],
ys: &[f64],
) -> Vec<f64> {
let n = F64s::<S>::LEN;
xs.chunks(n)
.zip(ys.chunks(n))
.flat_map(|(c, d)| {
let (mut p, mut q) = (vec![1.0; n], vec![1.0; n]);
p[..c.len()].copy_from_slice(c);
q[..d.len()].copy_from_slice(d);
let r = k(
simd,
F64s::<S>::from_slice(simd, &p),
F64s::<S>::from_slice(simd, &q),
)
.to_array();
r.as_ref()[..c.len()].to_vec()
})
.collect()
}
#[inline(always)]
fn apply32<S: Simd>(simd: S, k: fn(S, F32s<S>) -> F32s<S>, xs: &[f32]) -> Vec<f32> {
let n = F32s::<S>::LEN;
xs.chunks(n)
.flat_map(|c| {
let mut p = vec![1.0; n];
p[..c.len()].copy_from_slice(c);
let r = k(simd, F32s::<S>::from_slice(simd, &p)).to_array();
r.as_ref()[..c.len()].to_vec()
})
.collect()
}
#[inline(always)]
fn apply32_2<S: Simd>(
simd: S,
k: fn(S, F32s<S>, F32s<S>) -> F32s<S>,
xs: &[f32],
ys: &[f32],
) -> Vec<f32> {
let n = F32s::<S>::LEN;
xs.chunks(n)
.zip(ys.chunks(n))
.flat_map(|(c, d)| {
let (mut p, mut q) = (vec![1.0; n], vec![1.0; n]);
p[..c.len()].copy_from_slice(c);
q[..d.len()].copy_from_slice(d);
let r = k(
simd,
F32s::<S>::from_slice(simd, &p),
F32s::<S>::from_slice(simd, &q),
)
.to_array();
r.as_ref()[..c.len()].to_vec()
})
.collect()
}
fn samples() -> (Vec<f64>, Vec<f64>) {
let mut rng = Rng::new(0xabcdef);
let mut xs: Vec<f64> = parse_table(TABLE_F64).iter().map(|r| r.x).collect();
let (a, b) = xlogy_inputs(&mut rng, 4000, 1e300);
xs.extend(a);
let mut ys: Vec<f64> = xs.iter().map(|x| x.abs() + 0.001).collect();
let n = ys.len();
ys[n - 4000..].copy_from_slice(&b);
for (i, v) in [
0.0,
-0.0,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NAN,
5e-324,
1.0,
8.0,
]
.iter()
.enumerate()
{
xs[i] = *v;
ys[(i * 3) % 8] = *v;
}
(xs, ys)
}
fn bits(v: &[f64]) -> Vec<u64> {
v.iter().map(|x| x.to_bits()).collect()
}
#[test]
fn f64_levels_bit_identical() {
let (xs, ys) = samples();
let ref0: Vec<u64> = xs.iter().map(|&x| bessel::i0e(x).to_bits()).collect();
let ref1: Vec<u64> = xs.iter().map(|&x| bessel::i1e(x).to_bits()).collect();
let mut xlogy_ref: Option<Vec<u64>> = None;
for (name, level) in levels() {
let a = dispatch!(level, simd => apply64(simd, f64x::special::i0e, &xs));
let b = dispatch!(level, simd => apply64(simd, f64x::special::i1e, &xs));
let c = dispatch!(level, simd => apply64_2(simd, f64x::special::xlogy, &xs, &ys));
assert_eq!(bits(&a), ref0, "i0e f64 at {name}");
assert_eq!(bits(&b), ref1, "i1e f64 at {name}");
match &xlogy_ref {
None => xlogy_ref = Some(bits(&c)),
Some(r) => assert_eq!(&bits(&c), r, "xlogy f64 at {name}"),
}
println!(
"f64 level {name}: i0e/i1e == scalar reference, xlogy == first level, bitwise"
);
}
}
#[test]
fn f32_levels_bit_identical() {
let (xs64, ys64) = samples();
let xs: Vec<f32> = xs64.iter().map(|&x| x as f32).collect();
let ys: Vec<f32> = ys64.iter().map(|&x| x as f32).collect();
let ref0: Vec<u32> = xs
.iter()
.map(|&x| (bessel::i0e(x as f64) as f32).to_bits())
.collect();
let ref1: Vec<u32> = xs
.iter()
.map(|&x| (bessel::i1e(x as f64) as f32).to_bits())
.collect();
let b32 = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
let mut xlogy_ref: Option<Vec<u32>> = None;
for (name, level) in levels() {
let a = dispatch!(level, simd => apply32(simd, f32x::special::i0e, &xs));
let b = dispatch!(level, simd => apply32(simd, f32x::special::i1e, &xs));
let c = dispatch!(level, simd => apply32_2(simd, f32x::special::xlogy, &xs, &ys));
assert_eq!(b32(&a), ref0, "i0e f32 at {name}");
assert_eq!(b32(&b), ref1, "i1e f32 at {name}");
match &xlogy_ref {
None => xlogy_ref = Some(b32(&c)),
Some(r) => assert_eq!(&b32(&c), r, "xlogy f32 at {name}"),
}
}
}
#[test]
fn xlogy_vs_scalar_reference_tolerance() {
let mut rng = Rng::new(99);
let (xs, ys) = xlogy_inputs(&mut rng, 20000, 1e300);
let got = run2(ops64::xlogy, &xs, &ys);
let mut differing = 0usize;
let mut worst = 0.0f64;
for i in 0..xs.len() {
let want = bessel::xlogy(xs[i], ys[i]);
if got[i].to_bits() != want.to_bits() {
differing += 1;
if want != 0.0 && want.is_finite() {
let ulp = ((got[i] - want) / (want.abs() * f64::EPSILON / 2.0)).abs() / 2.0;
worst = worst.max(ulp);
}
}
}
println!(
"xlogy f64 vs platform-ln scalar: {differing}/{} bit-different, worst {worst:.2} ULP",
xs.len()
);
assert!(worst <= 2.5, "{worst}");
}
}