elem-simd-math 0.1.3

Vectorized elementwise math kernels for f32/f64 over stable-Rust SIMD (port of SLEEF via sleef-rs, on fearless_simd).
Documentation
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! Accuracy, special-case and bit-identity tests for `i0e`, `i1e` and `xlogy`.
//!
//! Provenance of the kernels: SciPy xsf commit `39019a470a208221d55a587f0baa329c3d1054c5`; see
//! `src/bessel.rs`. Oracles:
//!
//! * `i0e`, `i1e`: the committed mpmath tables in `tests/data/` (generator
//!   `tests/data/gen_bessel_reference.py`, mpmath 1.4.1); MPFR has no Bessel `I`.
//! * `xlogy`: exact `x * ln(y)` in MPFR.
//!
//! Bit-identity claims asserted here, per function:
//!
//! | | across SIMD levels | vs scalar reference `elem_simd_math::bessel` |
//! |---|---|---|
//! | `i0e`, `i1e` (f64, f32) | bit-identical | bit-identical |
//! | `xlogy` (f64, f32) | bit-identical | tolerance only (platform `ln` vs SLEEF `log`) |

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;

/// Bounds asserted against the oracles; see the kernel docs in `src/f64x/special.rs`.
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]"
    }
}

/// Worst ULP error per region, asserting `bound` everywhere.
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));
}

/// The scalar reference is bit-identical to the slice entry points, for every table argument.
#[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());
    // Scaled form: no overflow where I0/I1 themselves overflow.
    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]);
    // Where plain I0(x) = exp(x) / sqrt(2 pi x) would overflow (x > ~713.99) the scaled value is
    // the tail asymptote 1/sqrt(2 pi x) (1 + 1/(8x) + 9/(128 x^2) + 225/(3072 x^3) + 11025/(98304 x^4) + ...),
    // whose truncation error is below 1e-15 for x >= 1e3. The table checks this to the ULP; this
    // is the independent spot check.
    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), // log(y) near 0: relative accuracy of log
            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;
    // (x, y, expected); None means NaN. These are SciPy's `scipy.special.xlogy` results,
    // checked with scipy 1.18.1 when this test was written.
    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() {
        // 5e-324 is not a nonzero f32: the f32 lane of that case would test `xlogy(0, y)`.
        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})");
                }
            }
        }
    }
    // The scalar reference agrees on every special case.
    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),
        }
    }
}

/// Every lane length, so every tail path is exercised for each new function.
#[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};

    /// Every SIMD level the host supports, not only the one the slice API would pick.
    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);
        // Special values in every lane position.
        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()
    }

    /// `i0e`/`i1e`: every level is bit-identical to the scalar reference. `xlogy`: every level is
    /// bit-identical to every other.
    #[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}"),
            }
        }
    }

    /// Where `xlogy` is not bit-identical to the scalar reference, it is within the tolerance.
    #[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}");
    }
}