multidouble 5.1.0

Double-double, quad-double and octo-double arithmetic, scalar and 8-lane SIMD (AVX-512, AVX2, SSE2, NEON, portable) with bitwise identical results, dual numbers and LU solves
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
//! Scalar double-double against exact dyadic arithmetic (`multidouble::exact`, no shared code with the algorithms):
//! the error-free transformations must be exact, and the operations must stay inside their error bounds, measured
//! relative to the exact result in units of u^2 = 2^-106. Also the slice conversions of double-double and quad-double
//! arrays (`dd::split`, `dd::join`, `qd::to_parts`, `qd::from_parts`), bit for bit.
#![allow(clippy::needless_range_loop)]
mod common;
use common::{Rng, U2};
use multidouble::dd::{is_pwr2, join, pow2_near, quick_two_sum, split, two_prod, two_sum, DD};
use multidouble::exact::Dy;
use multidouble::native::QV;
use multidouble::qd::{from_parts, to_parts, QD};

const N: usize = 20_000;

fn exact(x: DD) -> Dy {
    Dy::from_f64(x.hi).add(&Dy::from_f64(x.lo))
}

/// |got - want| / |want| in units of u^2
fn rel_err(got: DD, want: &Dy) -> f64 {
    if want.is_zero() {
        return if got.hi == 0.0 && got.lo == 0.0 {
            0.0
        } else {
            f64::INFINITY
        };
    }
    exact(got).sub(want).ratio(want).abs() / U2
}

fn normalized(x: DD) -> bool {
    x.hi + x.lo == x.hi
}

#[test]
fn error_free_transformations_are_exact() {
    let mut r = Rng(1);
    for _ in 0..N {
        let (a, b) = (r.dd(30).hi, r.dd(30).hi);
        let (s, e) = two_sum(a, b);
        assert!(
            Dy::sum(&[s, e]).sub(&Dy::sum(&[a, b])).is_zero(),
            "two_sum({a:e}, {b:e})"
        );
        let (p, e) = two_prod(a, b);
        assert!(
            Dy::sum(&[p, e]).sub(&Dy::from_f64(a).mul(&Dy::from_f64(b))).is_zero(),
            "two_prod({a:e}, {b:e})"
        );
        // quick_two_sum needs |a| >= |b|
        let (x, y) = if a.abs() >= b.abs() { (a, b) } else { (b, a) };
        let (s, e) = quick_two_sum(x, y);
        assert!(
            Dy::sum(&[s, e]).sub(&Dy::sum(&[x, y])).is_zero(),
            "quick_two_sum({x:e}, {y:e})"
        );
    }
}

#[test]
fn add_and_sub_within_bounds() {
    let mut r = Rng(2);
    let mut worst: f64 = 0.0;
    for i in 0..N {
        let a = r.dd(20);
        // every fourth pair nearly cancels, the hard case for the relative bound
        let b = if i % 4 == 0 {
            DD::new(-a.hi, r.sym() * a.hi.abs() * 2f64.powi(-60))
        } else {
            r.dd(20)
        };
        for (got, want) in [(a + b, exact(a).add(&exact(b))), (a - b, exact(a).sub(&exact(b)))] {
            assert!(normalized(got));
            let e = rel_err(got, &want);
            worst = worst.max(e);
            assert!(e <= 3.0, "{a:?} +- {b:?}: {e} u^2");
        }
    }
    println!("add/sub: worst {worst:.3} u^2 (bound 3 u^2, Joldes, Muller and Popescu 2017)");
}

#[test]
fn mul_within_bound() {
    let mut r = Rng(3);
    let mut worst: f64 = 0.0;
    for _ in 0..N {
        let (a, b) = (r.dd(20), r.dd(20));
        let got = a * b;
        assert!(normalized(got));
        let e = rel_err(got, &exact(a).mul(&exact(b)));
        worst = worst.max(e);
        assert!(e <= 5.0, "{a:?} * {b:?}: {e} u^2");
        let got = a.mul_f(b.hi);
        let e = rel_err(got, &exact(a).mul(&Dy::from_f64(b.hi)));
        assert!(e <= 3.0, "{a:?} * {:e}: {e} u^2", b.hi);
    }
    println!("mul: worst {worst:.3} u^2");
}

#[test]
fn div_within_bound() {
    let mut r = Rng(4);
    let mut worst: f64 = 0.0;
    for _ in 0..N {
        let (a, b) = (r.dd(20), r.dd(20));
        let q = a / b;
        assert!(normalized(q));
        // q b - a, exactly, relative to a: the quotient's relative error to first order
        let res = exact(q).mul(&exact(b)).sub(&exact(a));
        let e = res.ratio(&exact(a)).abs() / U2;
        worst = worst.max(e);
        assert!(e <= 8.0, "{a:?} / {b:?}: {e} u^2");
    }
    println!("div: worst {worst:.3} u^2");
}

/// q b - a relative to a, in units of u^2: exactly the relative error of q as a / b
fn quotient_err(q: DD, a: DD, b: DD) -> f64 {
    exact(q).mul(&exact(b)).sub(&exact(a)).ratio(&exact(a)).abs() / U2
}

/// `fast_div` within Theorem 7.1 of Joldes, Muller and Popescu (2017), 15 u^2 + 56 u^3, on random quotients and
/// on divisors just above and below a power of two, where the first quotient's error is largest
#[test]
fn fast_div_within_bound() {
    let mut r = Rng(13);
    let bound = 15.0 + 56.0 * 2f64.powi(-53);
    let mut worst: f64 = 0.0;
    for i in 0..N {
        let a = r.dd(20);
        let b = if i % 2 == 0 {
            r.dd(20)
        } else {
            // b near 2^k (1 +- 2^-j)
            let k = r.dd(20).hi.abs().log2().floor() as i32;
            let j = 1 + (r.dd(0).hi.abs() * 50.0) as i32 % 52;
            let s = if r.dd(0).hi > 0.0 { 1.0 } else { -1.0 };
            DD::new(p2(k) * (1.0 + s * p2(-j)), r.dd(0).lo * p2(k))
        };
        let q = a.fast_div(b);
        assert!(normalized(q));
        let e = quotient_err(q, a, b);
        worst = worst.max(e);
        assert!(e <= bound, "{a:?} / {b:?}: {e} u^2");
    }
    println!("fast_div: worst {worst:.3} u^2");
}

/// The checks can fail: a quotient that ignores the dividend's low part breaks the bound, and so does one whose low
/// part is moved by 32 u^2 of the quotient, which by the bound errs by at least 17 u^2.
#[test]
fn control_fires_for_fast_div() {
    let mut r = Rng(14);
    let caught = (0..1000).any(|_| {
        let (a, b) = (r.dd(20), r.dd(20));
        quotient_err(DD::from_f64(a.hi).fast_div(b), a, b) > 15.0
    });
    assert!(caught);
    let shift = 32.0 * 2f64.powi(-106);
    let moved = (0..1000).all(|_| {
        let (a, b) = (r.dd(20), r.dd(20));
        let q = a.fast_div(b);
        let q = DD::new(q.hi, q.lo + shift * q.hi);
        quotient_err(q, a, b) > 15.0 + 56.0 * 2f64.powi(-53)
    });
    assert!(moved);
}

/// a^n exactly, for n >= 0
fn exact_pow(a: DD, n: u32) -> Dy {
    let x = exact(a);
    (0..n).fold(Dy::from_f64(1.0), |p, _| p.mul(&x))
}

/// `sqr` within the multiply's 5 u^2, and `powi` within 5 (|n| - 1) u^2, the first-order sum of its |n| - 1
/// multiplications' bounds (each squaring doubles the error of what it squares), plus the divide's 8 u^2 for n < 0,
/// measured there as the residual a^|n| x - 1. Thresholds fixed before the first run.
#[test]
fn sqr_and_powi_within_bounds() {
    let mut r = Rng(6);
    let (mut worst_sqr, mut worst_pow): (f64, f64) = (0.0, 0.0);
    for i in 0..N {
        let a = r.dd(20);
        let s = a.sqr();
        assert!(normalized(s));
        let e = rel_err(s, &exact(a).mul(&exact(a)));
        worst_sqr = worst_sqr.max(e);
        assert!(e <= 5.0, "{a:?}.sqr(): {e} u^2");
        let a = r.dd(4);
        let n = (i % 25) as i32 - 12;
        let p = a.powi(n);
        let k = n.unsigned_abs();
        let (e, thr) = if n >= 0 {
            (rel_err(p, &exact_pow(a, k)), 5.0 * k.saturating_sub(1) as f64)
        } else {
            let res = exact(p).mul(&exact_pow(a, k)).sub(&Dy::from_f64(1.0));
            (res.ratio(&Dy::from_f64(1.0)).abs() / U2, 5.0 * (k - 1) as f64 + 8.0)
        };
        worst_pow = worst_pow.max(if thr > 0.0 { e / thr } else { e });
        assert!(e <= thr, "{a:?}.powi({n}): {e} u^2 > {thr}");
    }
    assert_eq!(DD::from_f64(3.0).powi(0), DD::ONE);
    assert_eq!(DD::from_f64(-2.0).powi(5), DD::from_f64(-32.0));
    assert_eq!(DD::from_f64(2.0).powi(-3), DD::from_f64(0.125));
    // a negative power whose positive power overflows: 2^1024 is not representable, 2^-1024 is (subnormal)
    assert_eq!(DD::from_f64(p2(512)).powi(-2), DD::from_f64(p2(-1024)));
    assert_eq!(DD::from_f64(p2(100)).powi(-10), DD::from_f64(p2(-1000)));
    // 2^1200 overflows; DD's division by the underflowed 2^-1200 = 0 gives NaN, as `DD::ONE / DD::ZERO` does
    assert!(!DD::from_f64(p2(-600)).powi(-2).hi.is_finite());
    assert!(DD::from_f64(f64::NAN).powi(-3).hi.is_nan());
    println!("sqr: worst {worst_sqr:.3} u^2; powi: worst {worst_pow:.3} of its bound");
}

/// 2^e for any exponent of a nonzero f64, subnormal included (`2f64.powi(e)` underflows to 0 below about 2^-1023)
fn p2(e: i32) -> f64 {
    if e >= -1022 {
        f64::from_bits(((e + 1023) as u64) << 52)
    } else {
        f64::from_bits(1u64 << (e + 1074))
    }
}

/// |sqrt(x) - z| / sqrt(x) in units of u^2, from the exact residual: z = sqrt(x)(1 + d) gives (z^2 - x)/(2x) = d + d^2/2
fn sqrt_err(z: DD, x: &Dy) -> f64 {
    exact(z).mul(&exact(z)).sub(x).ratio(x).abs() / 2.0 / U2
}

/// `sqrt` within the proven 25/8 u^2 (Lefèvre, Louvet, Muller, Picot, Rideau 2023, Theorem 3.5), over random
/// magnitudes, near the scaling threshold 2^-968, at the extremes of the range, and on exact squares, where it is exact.
/// The d^2/2 of the residual is below 2^-200 u^2, so the bound is checked as stated.
#[test]
fn sqrt_within_bound() {
    let mut r = Rng(8);
    let mut worst: f64 = 0.0;
    let mut check = |x: DD| {
        let z = x.sqrt();
        assert!(normalized(z), "{x:?}");
        let e = sqrt_err(z, &exact(x));
        worst = worst.max(e);
        assert!(e <= 25.0 / 8.0, "{x:?}.sqrt(): {e} u^2");
    };
    for _ in 0..N {
        check(r.dd(300).abs());
    }
    let mut subnormal = 0;
    for e in [-1074, -1060, -1022, -1000, -969, -968, -967, -900, 1000, 1022] {
        for _ in 0..50 {
            // |hi| in [2^e, 2^(e+1)); below 2^-1022 a single subnormal f64 (mul_pwr2 takes normal powers only), as a
            // renormalized value that small has a zero lo
            let x = if e >= -1022 {
                r.dd(0).abs().mul_pwr2(p2(e))
            } else {
                DD::from_f64((1.0 + r.unit()) * p2(e))
            };
            assert!(x.hi > 0.0, "2^{e}");
            subnormal += !x.hi.is_normal() as usize;
            check(x);
        }
    }
    assert_eq!(subnormal, 100, "the inputs at 2^-1074 and 2^-1060 are subnormal");
    for _ in 0..1000 {
        let s = r.dd(200).abs();
        let x = DD::from_f64(s.hi * s.hi);
        if x.hi.is_normal() && exact(x).sub(&Dy::from_f64(s.hi).mul(&Dy::from_f64(s.hi))).is_zero() {
            assert_eq!(x.sqrt().hi, s.hi.abs());
        }
    }
    assert_eq!(DD::from_f64(4.0).sqrt(), DD::from_f64(2.0));
    assert_eq!(DD::ZERO.sqrt(), DD::ZERO);
    assert!(DD::from_f64(-1.0).sqrt().hi.is_nan());
    assert_eq!(DD::from_f64(f64::INFINITY).sqrt().hi, f64::INFINITY);
    println!("sqrt: worst {worst:.3} u^2");
}

/// The sqrt check can fail: the root of hi alone, ignoring lo, misses the bound.
#[test]
fn control_fires_for_sqrt() {
    let mut r = Rng(9);
    let caught = (0..1000).any(|_| {
        let x = r.dd(20).abs();
        sqrt_err(DD::from_f64(x.hi).sqrt(), &exact(x)) > 25.0 / 8.0
    });
    assert!(caught);
}

/// The sqr and powi checks can fail: a square without its 2 hi lo term, and a power formed in f64, break their
/// bounds.
#[test]
fn controls_fire_for_sqr_and_powi() {
    let mut r = Rng(7);
    let (mut sqr_caught, mut pow_caught) = (false, false);
    for _ in 0..1000 {
        let a = r.dd(20);
        let (p, e) = two_prod(a.hi, a.hi);
        sqr_caught |= rel_err(DD::new(p, e), &exact(a).mul(&exact(a))) > 5.0;
        let a = r.dd(4);
        let broken = DD::from_f64(a.to_f64().powi(7));
        pow_caught |= rel_err(broken, &exact_pow(a, 7)) > 30.0;
    }
    assert!(sqr_caught && pow_caught);
}

#[test]
fn small_identities() {
    let one = DD::ONE;
    let three = DD::from_f64(3.0);
    let third = one / three;
    assert!(((third * three) - one).to_f64().abs() < 2.0 * U2);
    assert_eq!((DD::from_f64(-2.5)).abs(), DD::from_f64(2.5));
    assert_eq!(DD::from_f64(4.0).recip(), DD::from_f64(0.25));
    assert_eq!(-(-third), third);
    // 2 pi to double-double: hi + lo against the 34-digit decimal value
    let tp: multidouble::qd::QD = "6.283185307179586476925286766559005768394".parse().unwrap();
    assert!((tp - multidouble::qd::QD::from_dd(DD::TWO_PI)).to_f64().abs() < 1e-31);
}

/// The checks above can fail: a double-double add that drops the low parts, and a multiply without the cross terms,
/// both break their bounds on these inputs.
#[test]
fn controls_fire() {
    let mut r = Rng(5);
    let (mut add_caught, mut mul_caught) = (false, false);
    for _ in 0..1000 {
        let (a, b) = (r.dd(20), r.dd(20));
        let (s, e) = two_sum(a.hi, b.hi);
        let broken_add = DD::new(s, e);
        add_caught |= rel_err(broken_add, &exact(a).add(&exact(b))) > 3.0;
        let (p, e) = two_prod(a.hi, b.hi);
        let broken_mul = DD::new(p, e);
        mul_caught |= rel_err(broken_mul, &exact(a).mul(&exact(b))) > 5.0;
    }
    assert!(add_caught && mul_caught);
}

/// `pow2_near` returns a normal power of two within half an octave of x, x itself for a power of two, and the
/// neighbour on the other side when x crosses the geometric midpoint (sqrt 2 times a power of two)
#[test]
fn pow2_near_is_the_nearest_power_of_two() {
    let mut r = Rng(91);
    for _ in 0..N {
        let x = r.dd(300).hi.abs();
        let p = pow2_near(x);
        assert!(is_pwr2(p) && (x / p).log2().abs() <= 0.5, "{x} -> {p}");
    }
    assert_eq!(pow2_near(0.25), 0.25);
    assert_eq!(pow2_near(1e-3), 2f64.powi(-10));
    assert_eq!(pow2_near(3.0), 4.0);
    assert_eq!(pow2_near(2.8), 2.0);
    assert_eq!(pow2_near(1.5 * 2f64.powi(100)), 2f64.powi(101));
    assert!(!is_pwr2(1.5 * pow2_near(2.8)), "control");
    // the ends of the range: the smallest and the largest normal powers of two
    assert_eq!(pow2_near(f64::MIN_POSITIVE), f64::MIN_POSITIVE);
    assert_eq!(pow2_near(1.4 * f64::MIN_POSITIVE), f64::MIN_POSITIVE);
    assert_eq!(pow2_near(2f64.powi(1023)), 2f64.powi(1023));
    assert_eq!(pow2_near(1.4 * 2f64.powi(1023)), 2f64.powi(1023));
}

/// in debug builds, an x whose nearest power of two is subnormal (or infinite) is refused
#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "outside the normal range")]
fn pow2_near_refuses_a_subnormal_result_in_debug() {
    pow2_near(1e-320);
}

#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "outside the normal range")]
fn pow2_near_refuses_an_infinite_result_in_debug() {
    pow2_near(f64::MAX);
}

// ---------------------------------------------------------------------------------------------------------------
// slice conversions
// ---------------------------------------------------------------------------------------------------------------

fn bits(v: &[f64]) -> Vec<u64> {
    v.iter().map(|x| x.to_bits()).collect()
}

/// `split` and `join` are the loops they replace (the parts collected one array at a time, and `DD { hi, lo }` from
/// the zipped arrays) bit for bit, and each undoes the other, also for parts that overlap (which `join` keeps as
/// they are, where `DD::new` would renormalize them) and for empty arrays. Controls: a join with the lo parts dropped
/// or the parts swapped does not give the double-doubles back.
#[test]
fn split_and_join_are_the_loops_and_inverses() {
    let mut r = Rng(91);
    let v: Vec<DD> = (0..37).map(|_| r.dd(20)).collect();
    let (h, l) = split(&v);
    let (hh, ll): (Vec<f64>, Vec<f64>) = (v.iter().map(|d| d.hi).collect(), v.iter().map(|d| d.lo).collect());
    assert!(bits(&h) == bits(&hh) && bits(&l) == bits(&ll));
    let w = join(&h, &l);
    let hand: Vec<DD> = h.iter().zip(&l).map(|(&a, &c)| DD { hi: a, lo: c }).collect();
    let same = |a: &[DD], b: &[DD]| {
        a.len() == b.len()
            && a.iter()
                .zip(b)
                .all(|(x, y)| x.hi.to_bits() == y.hi.to_bits() && x.lo.to_bits() == y.lo.to_bits())
    };
    assert!(same(&w, &hand) && same(&w, &v));
    // overlapping parts, each about 2^-20 of its hi
    let (oh, ol): (Vec<f64>, Vec<f64>) = (0..37).map(|_| (r.sym(), r.sym() * 2f64.powi(-20))).unzip();
    let (h2, l2) = split(&join(&oh, &ol));
    assert!(bits(&h2) == bits(&oh) && bits(&l2) == bits(&ol));
    assert!(
        oh.iter()
            .zip(&ol)
            .any(|(&a, &b)| DD::new(a, b).hi.to_bits() != a.to_bits()),
        "control: no overlap"
    );
    assert!(split(&[]) == (vec![], vec![]) && join(&[], &[]).is_empty());
    assert!(!same(&join(&h, &vec![0.0; h.len()]), &v), "control: lo dropped");
    assert!(!same(&join(&l, &h), &v), "control: parts swapped");
}

#[test]
#[should_panic(expected = "join: 3 hi parts and 2 lo parts")]
fn join_refuses_arrays_of_different_lengths() {
    join(&[1.0, 2.0, 3.0], &[0.0, 0.0]);
}

/// `to_parts` and `from_parts` are the loops they replace (part k of every value collected into array k, and
/// `QD { x }` from part k of each array at index i) bit for bit, each undoes the other for parts that overlap (not
/// renormalized, as `QD::new` would), and `from_parts` reads the four arrays as `QV::load` does, value i at lane i.
/// Controls: two parts swapped, or the last part dropped, do not give the quad-doubles back.
#[test]
fn to_parts_and_from_parts_are_the_loops_and_inverses() {
    let mut r = Rng(92);
    let n = 40;
    // overlapping parts, each about 2^-20 of the one before
    let c: [Vec<f64>; 4] = std::array::from_fn(|k| (0..n).map(|_| r.sym() * 2f64.powi(-20 * k as i32)).collect());
    let q = from_parts([&c[0], &c[1], &c[2], &c[3]]);
    let hand: Vec<QD> = (0..n)
        .map(|i| QD {
            x: std::array::from_fn(|k| c[k][i]),
        })
        .collect();
    let same = |a: &[QD], b: &[QD]| {
        a.len() == b.len()
            && a.iter()
                .zip(b)
                .all(|(x, y)| x.x.iter().zip(y.x.iter()).all(|(p, s)| p.to_bits() == s.to_bits()))
    };
    assert!(same(&q, &hand));
    let back = to_parts(&q);
    let loops: [Vec<f64>; 4] = std::array::from_fn(|k| q.iter().map(|v| v.x[k]).collect());
    for k in 0..4 {
        assert!(
            bits(&back[k]) == bits(&c[k]) && bits(&loops[k]) == bits(&c[k]),
            "part {k}"
        );
    }
    for b in 0..n / 8 {
        let o = 8 * b;
        let v = QV::load(&c[0][o..o + 8], &c[1][o..o + 8], &c[2][o..o + 8], &c[3][o..o + 8]);
        assert!(same(&v.lanes(), &q[o..o + 8]), "lane vector {b}");
    }
    assert!(
        (0..4).any(|k| QD::new(c[0][0], c[1][0], c[2][0], c[3][0]).x[k].to_bits() != c[k][0].to_bits()),
        "control: no overlap"
    );
    assert!(to_parts(&[]).iter().all(|p| p.is_empty()) && from_parts([&[], &[], &[], &[]]).is_empty());
    assert!(
        !same(&from_parts([&c[1], &c[0], &c[2], &c[3]]), &q),
        "control: parts swapped"
    );
    assert!(
        !same(&from_parts([&c[0], &c[1], &c[2], &vec![0.0; n]]), &q),
        "control: last part dropped"
    );
}

#[test]
#[should_panic(expected = "from_parts: the four arrays must have one length")]
fn from_parts_refuses_arrays_of_different_lengths() {
    from_parts([&[1.0, 2.0], &[0.0, 0.0], &[0.0], &[0.0, 0.0]]);
}

// ---------------------------------------------------------------------------------------------------------------
// pinned outputs
// ---------------------------------------------------------------------------------------------------------------

/// the bits of the pinned double-double outputs, by group. nudge flips the last bit of the first
/// x's high part.
fn dd_outputs(nudge: bool) -> Vec<Vec<u64>> {
    use multidouble::native::{DDotAcc, DV, V8};
    let bits = |v: &[DD]| -> Vec<u64> { v.iter().flat_map(|d| [d.hi.to_bits(), d.lo.to_bits()]).collect() };
    let lanes = |v: DV| -> Vec<u64> { bits(&(0..8).map(|j| v.lane(j)).collect::<Vec<_>>()) };
    let dv = |v: &[DD; 8]| DV::load(&v.map(|d| d.hi), &v.map(|d| d.lo));
    let mut r = Rng(73);
    let mut w = vec![Vec::new(); 5];
    for i in 0..16 {
        let mut x: [DD; 8] = std::array::from_fn(|_| r.dd(8));
        if nudge && i == 0 {
            x[0].hi = f64::from_bits(x[0].hi.to_bits() ^ 1);
        }
        let y: [DD; 8] = std::array::from_fn(|_| r.dd(8));
        let f: [f64; 8] = std::array::from_fn(|_| r.dd(4).hi);
        for j in 0..8 {
            let (a, b) = (x[j], y[j]);
            w[0].extend(bits(&[a + b, a - b, -a, a.abs()]));
            w[0].push(a.to_f64().to_bits());
            w[1].extend(bits(&[a * b, a.mul_f(f[j]), a.mul_pwr2(0.25)]));
            w[2].extend(bits(&[a / b, a.recip()]));
        }
        // on the lanes, the operations without a scalar twin, and the dot accumulator
        let (xv, yv, fv) = (dv(&x), dv(&y), V8::from_array(f));
        for v in [xv.mul_v(fv), xv.add_v(fv), xv.div_by(yv, yv.hi.divisor())] {
            w[3].extend(lanes(v));
        }
        w[4].extend(lanes(
            DDotAcc::zero().add_prod(xv, yv).add_prod(yv, yv).add(xv).finish(),
        ));
    }
    w
}

/// The double-double outputs pinned bit for bit on fixed inputs, against hashes recorded with
/// 4.1.1: the scalar operations, and on the lanes those without a scalar twin and the dot
/// accumulator. Every backend gives these bits (tests/lanes.rs checks the lanes against the
/// scalar arithmetic). Control: the first input's last bit flipped changes every group's hash.
#[test]
fn dd_outputs_are_pinned() {
    let names = [
        "add, sub, neg, abs, to_f64",
        "mul, x f64, x 2^k",
        "div, recip",
        "lanes: x V8, + V8, div_by",
        "dot accumulator",
    ];
    let want: [u64; 5] = [
        0x5c8f_9441_3619_2b66,
        0x855a_1020_6b1a_ff1a,
        0xe3b9_1a9f_5250_529f,
        0x0537_7e0c_19a4_3dcf,
        0xd029_233f_9485_1d15,
    ];
    common::assert_pinned(&names, &dd_outputs(false), &dd_outputs(true), &want);
}