multidouble 6.2.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
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! The number trait `real::Real` over f64, DD, QD and OD, checked against the inherent methods it delegates to, the
//! lanes' accumulators, exact arithmetic (`exact`, which shares no code with the algorithms) and planted values.
//!
//! Pass, fixed before the first run:
//! * the constants: every `ROUNDOFF`, `UNIT` and `EPSILON` equals its pinned bit pattern (the values multishoot's and
//!   multisolver's traits and negative-mass's `Num` carry, `QD::EPS`, `OD::EPS`); `UNIT` is 2^(-52 PARTS) exactly,
//!   `EPSILON` is `f64::EPSILON`, `DD::EPS`, `QD::EPS`, `OD::EPS`, `ROUNDOFF` of f64 and DD is 2^-53 and 2^-106;
//!   `PARTS` is that of `Precision`; `ZERO` and `ONE` read 0 and 1 in every part but the first;
//! * delegation: on 400 random values per type, every method (`from_f64`, `from_dd`, `to_dd`, `to_f64`, `mul_f`,
//!   `recip`, `sqrt`, `exp`, `ln`, `recip_int`, `from_ratio`, the four operators) gives the inherent method's parts bit
//!   for bit; f64's `from_ratio` is the IEEE quotient for p and q below 2^53;
//! * the Cauchy sum: `cauchy` equals the lane accumulator's lane 0 (`Lane::acc` and `fin` of `DV`, `QV`, `OV`) bit for
//!   bit on 300 random sums of 1 to 40 terms, on the default and the `portable` backends; f64's equals the plain sum
//!   `a[0] b[k] + a[1] b[k-1] + ...` bit for bit, negative zeros included; its error against the exact sum is at most
//!   the accumulators' stated bound (|Z| + W) u^n (n = 2, 4, 8, u = 2^-53) on 300 random sums with W = sum |a_j b_(k-j)|;
//! * decimals: `parse` of the 200 digits of pi, printed with `to_sci(15, 30, 60, 120)` digits, equals pi rounded to
//!   those digits; `parse` reads "0.125", "-2.5e3" and " 7 " exactly and rejects "x" and ""; DD's `parse` equals the
//!   double-double rounded from the exact decimal (hi = RN(v), lo = RN(v - hi)) on 300 random 40-digit decimals;
//!   `to_sci` of 1.5e-5 with 5 digits is "1.5000e-05", of a negative zero "-0.0000e+00".
//!
//! Controls, each of which must fail the check it names (those marked *mutate* need the feature `mutate`):
//! * each pinned constant one ulp off fails the constants check;
//! * *mutate* `from_f64` one unit up fails the delegation check;
//! * a start of +0 instead of -0 for f64's sum fails the check on negative zeros;
//! * *mutate* the plain sum of products in place of the accumulator fails the lane equality of every multi-double,
//!   and `DdAcc` without the products' error terms fails it for DD;
//! * the sum's result moved by twice the bound fails the bound check;
//! * pi with one digit changed fails the print check, the decimals shifted by 10^9 units of their 40th digit fail DD's
//!   parse check.
mod common;
use common::Rng;
use multidouble::dd::{DdAcc, DD};
use multidouble::dual::Lane;
use multidouble::exact::{round_to_f64, BigU, Dy};
use multidouble::native::{DV, OV, QV};
use multidouble::od::OD;
use multidouble::precision::{Double, Octo, Precision, Quad};
use multidouble::qd::QD;
use multidouble::real::Real;
use multidouble::simd::Native;

/// the parts of a value, as bits
trait Bits: Real {
    fn bits(self) -> Vec<u64>;
    /// the exact value
    fn exact(self) -> Dy;
}
impl Bits for f64 {
    fn bits(self) -> Vec<u64> {
        vec![self.to_bits()]
    }
    fn exact(self) -> Dy {
        Dy::from_f64(self)
    }
}
impl Bits for DD {
    fn bits(self) -> Vec<u64> {
        vec![self.hi.to_bits(), self.lo.to_bits()]
    }
    fn exact(self) -> Dy {
        Dy::sum(&[self.hi, self.lo])
    }
}
impl Bits for QD {
    fn bits(self) -> Vec<u64> {
        self.x.iter().map(|v| v.to_bits()).collect()
    }
    fn exact(self) -> Dy {
        QD::exact(self)
    }
}
impl Bits for OD {
    fn bits(self) -> Vec<u64> {
        self.x.iter().map(|v| v.to_bits()).collect()
    }
    fn exact(self) -> Dy {
        OD::exact(self)
    }
}

/// a random value of the type with every part populated: a leading part in (-1, 1) times a power of two within 2^+-e,
/// each next part 2^-53 smaller
fn random<T: Real>(rng: &mut Rng, e: i32) -> T {
    let scale = 2f64.powi((rng.next_u64() % (2 * e as u64 + 1)) as i32 - e);
    let mut x = T::from_f64(rng.sym() * scale);
    let mut s = scale;
    for _ in 1..T::PARTS {
        s *= 2f64.powi(-53);
        x = x + T::from_f64(rng.sym() * s);
    }
    x
}

// ---- constants ----

/// every constant of the four types: (name, value bits)
fn constants() -> Vec<(String, u64)> {
    fn of<T: Real>() -> Vec<(String, u64)> {
        vec![
            (format!("{}::ROUNDOFF", T::NAME), T::ROUNDOFF.to_bits()),
            (format!("{}::UNIT", T::NAME), T::UNIT.to_bits()),
            (format!("{}::EPSILON", T::NAME), T::EPSILON.to_bits()),
        ]
    }
    let mut v = of::<f64>();
    v.extend(of::<DD>());
    v.extend(of::<QD>());
    v.extend(of::<OD>());
    v
}

/// the values the crates carry, as the decimal literals of their sources and the powers of two they are
fn pinned() -> Vec<(String, u64)> {
    let pow2 = |e: i32| 2f64.powi(e).to_bits();
    let lit = |x: f64| x.to_bits();
    let rows: Vec<(&str, u64)> = vec![
        ("f64::ROUNDOFF", lit(1.1102230246251565e-16)),
        ("f64::UNIT", lit(2.220446049250313e-16)),
        ("f64::EPSILON", lit(f64::EPSILON)),
        ("dd::ROUNDOFF", lit(1.232595164407831e-32)),
        ("dd::UNIT", lit(4.930380657631324e-32)),
        ("dd::EPSILON", pow2(-104)),
        ("qd::ROUNDOFF", lit(1.504632769052528e-64)),
        ("qd::UNIT", lit(2.4308653429145085e-63)),
        ("qd::EPSILON", pow2(-209)),
        ("od::ROUNDOFF", lit(2.3e-128)),
        ("od::UNIT", lit(5.909106315382871e-126)),
        ("od::EPSILON", pow2(-418)),
    ];
    rows.into_iter().map(|(n, b)| (n.to_string(), b)).collect()
}

/// the names whose value differs from the pin
fn constant_mismatches(got: &[(String, u64)], want: &[(String, u64)]) -> Vec<String> {
    assert_eq!(got.len(), want.len());
    got.iter()
        .zip(want)
        .filter(|(g, w)| g.0 != w.0 || g.1 != w.1)
        .map(|(g, _)| g.0.clone())
        .collect()
}

#[test]
fn constants_keep_their_values() {
    assert_eq!(constant_mismatches(&constants(), &pinned()), Vec::<String>::new());
    // the relations the values stand in
    fn rel<T: Bits>(parts: usize) {
        assert_eq!(T::PARTS, parts, "{}", T::NAME);
        assert_eq!(T::UNIT, 2f64.powi(-52 * parts as i32), "{} UNIT", T::NAME);
        let (z, o) = (T::ZERO.bits_f64(), T::ONE.bits_f64());
        assert!(z.iter().all(|&v| v == 0.0) && z.len() == parts, "{} ZERO", T::NAME);
        assert!(o[0] == 1.0 && o[1..].iter().all(|&v| v == 0.0), "{} ONE", T::NAME);
    }
    rel::<f64>(1);
    rel::<DD>(2);
    rel::<QD>(4);
    rel::<OD>(8);
    assert_eq!(<f64 as Real>::EPSILON, f64::EPSILON);
    assert_eq!(<DD as Real>::EPSILON, DD::EPS);
    assert_eq!(<QD as Real>::EPSILON, QD::EPS);
    assert_eq!(<OD as Real>::EPSILON, OD::EPS);
    assert_eq!(<f64 as Real>::ROUNDOFF, 2f64.powi(-53));
    assert_eq!(<DD as Real>::ROUNDOFF, 2f64.powi(-106));
    assert_eq!(<Double as Precision<Native>>::PARTS, <DD as Real>::PARTS);
    assert_eq!(<Quad as Precision<Native>>::PARTS, <QD as Real>::PARTS);
    assert_eq!(<Octo as Precision<Native>>::PARTS, <OD as Real>::PARTS);
    assert_eq!(
        [
            <f64 as Real>::NAME,
            <DD as Real>::NAME,
            <QD as Real>::NAME,
            <OD as Real>::NAME
        ],
        ["f64", "dd", "qd", "od"]
    );
}

/// the parts of a value as f64, through its bits helper
trait PartsF64: Bits {
    fn bits_f64(self) -> Vec<f64> {
        self.bits().into_iter().map(f64::from_bits).collect()
    }
}
impl<T: Bits> PartsF64 for T {}

/// Control: each pinned value one ulp off is a mismatch, and only that one
#[test]
fn constants_control_sees_each_pin() {
    let want = pinned();
    for i in 0..want.len() {
        let mut off = want.clone();
        off[i].1 += 1;
        assert_eq!(
            constant_mismatches(&constants(), &off),
            vec![want[i].0.clone()],
            "pin {i}"
        );
    }
}

// ---- delegation ----

/// the arguments of one round of the delegation check: two values, an f64, an integer k and a ratio p / q
#[derive(Clone, Copy)]
struct Case<T> {
    x: T,
    y: T,
    f: f64,
    k: u64,
    p: i64,
    q: u64,
}

/// the first method whose result differs bit for bit from the inherent one, over 400 random values; None when none
fn delegation_mismatch<T: Bits>(
    seed: u64,
    inherent: &dyn Fn(&str, &Case<T>) -> Vec<u64>,
    traitm: &dyn Fn(&str, &Case<T>) -> Vec<u64>,
) -> Option<String> {
    let mut rng = Rng(seed);
    for _ in 0..400 {
        let x: T = random(&mut rng, 20);
        let y: T = random(&mut rng, 20);
        let f = rng.sym() * 2f64.powi((rng.next_u64() % 40) as i32 - 20);
        let k = 1 + rng.next_u64() % (1 << 59);
        let p = rng.next_u64() as i64;
        let q = 1 + rng.next_u64() % (1 << 59);
        let case = Case { x, y, f, k, p, q };
        for m in [
            "from_f64",
            "from_dd",
            "to_dd",
            "to_f64",
            "mul_f",
            "recip",
            "sqrt",
            "exp",
            "ln",
            "recip_int",
            "from_ratio",
            "add",
            "sub",
            "mul",
            "div",
            "neg",
        ] {
            let (a, b) = (inherent(m, &case), traitm(m, &case));
            if a != b {
                return Some(format!("{} {m}: {a:x?} against {b:x?}", T::NAME));
            }
        }
    }
    None
}

macro_rules! delegation {
    ($name:ident, $t:ty, $seed:expr, $from_dd:expr, $to_dd:expr) => {
        fn $name() -> Option<String> {
            let inherent = |m: &str, c: &Case<$t>| -> Vec<u64> {
                let Case { x, y, f, k, p, q } = *c;
                let d = DD::new(f, f * 2f64.powi(-60));
                match m {
                    "from_f64" => <$t>::from_f64(f).bits(),
                    "from_dd" => ($from_dd)(d).bits(),
                    "to_dd" => ($to_dd)(x).bits(),
                    "to_f64" => vec![<$t>::to_f64(x).to_bits()],
                    "mul_f" => <$t>::mul_f(x, f).bits(),
                    "recip" => <$t>::recip(x).bits(),
                    "sqrt" => <$t>::sqrt(x.abs_part()).bits(),
                    "exp" => <$t>::exp(x.small()).bits(),
                    "ln" => <$t>::ln(x.abs_part()).bits(),
                    "recip_int" => <$t>::recip_int(k).bits(),
                    "from_ratio" => <$t>::from_ratio(p, q).bits(),
                    "add" => (x + y).bits(),
                    "sub" => (x - y).bits(),
                    "mul" => (x * y).bits(),
                    "div" => (x / y).bits(),
                    "neg" => (-x).bits(),
                    _ => unreachable!(),
                }
            };
            let traitm = |m: &str, c: &Case<$t>| -> Vec<u64> {
                let Case { x, y, f, k, p, q } = *c;
                let d = DD::new(f, f * 2f64.powi(-60));
                match m {
                    "from_f64" => <$t as Real>::from_f64(f).bits(),
                    "from_dd" => <$t as Real>::from_dd(d).bits(),
                    "to_dd" => Real::to_dd(x).bits(),
                    "to_f64" => vec![Real::to_f64(x).to_bits()],
                    "mul_f" => Real::mul_f(x, f).bits(),
                    "recip" => Real::recip(x).bits(),
                    "sqrt" => Real::sqrt(x.abs_part()).bits(),
                    "exp" => Real::exp(x.small()).bits(),
                    "ln" => Real::ln(x.abs_part()).bits(),
                    "recip_int" => <$t as Real>::recip_int(k).bits(),
                    "from_ratio" => <$t as Real>::from_ratio(p, q).bits(),
                    "add" => (x + y).bits(),
                    "sub" => (x - y).bits(),
                    "mul" => (x * y).bits(),
                    "div" => (x / y).bits(),
                    "neg" => (-x).bits(),
                    _ => unreachable!(),
                }
            };
            delegation_mismatch::<$t>($seed, &inherent, &traitm)
        }
    };
}

/// |x| and a value in (-8, 8), in the type
trait Shape: Bits {
    fn abs_part(self) -> Self {
        if self.to_f64() < 0.0 {
            -self
        } else {
            self
        }
    }
    fn small(self) -> Self {
        // exp of the value scaled into (-8, 8): exact scaling by a power of two
        let e = self.to_f64().abs().max(f64::MIN_POSITIVE).log2().ceil() as i32;
        self.mul_f(2f64.powi(3 - e.clamp(-1000, 1000)))
    }
}
impl<T: Bits> Shape for T {}
/// f64 has no inherent methods of these names: std's operations and `ratio_parts`' first part
fn delegation_f64() -> Option<String> {
    let inherent = |m: &str, c: &Case<f64>| -> Vec<u64> {
        let Case { x, y, f, k, p, q } = *c;
        let d = DD::new(f, f * 2f64.powi(-60));
        match m {
            "from_f64" => f.bits(),
            "from_dd" => d.to_f64().bits(),
            "to_dd" => DD::from_f64(x).bits(),
            "to_f64" => x.bits(),
            "mul_f" => (x * f).bits(),
            "recip" => (1.0 / x).bits(),
            "sqrt" => x.abs_part().sqrt().bits(),
            "exp" => x.small().exp().bits(),
            "ln" => x.abs_part().ln().bits(),
            "recip_int" => multidouble::recip::recip_parts(k)[0].bits(),
            "from_ratio" => multidouble::recip::ratio_parts(p, q)[0].bits(),
            "add" => (x + y).bits(),
            "sub" => (x - y).bits(),
            "mul" => (x * y).bits(),
            "div" => (x / y).bits(),
            "neg" => (-x).bits(),
            _ => unreachable!(),
        }
    };
    let traitm = |m: &str, c: &Case<f64>| -> Vec<u64> {
        let Case { x, y, f, k, p, q } = *c;
        let d = DD::new(f, f * 2f64.powi(-60));
        match m {
            "from_f64" => <f64 as Real>::from_f64(f).bits(),
            "from_dd" => <f64 as Real>::from_dd(d).bits(),
            "to_dd" => Real::to_dd(x).bits(),
            "to_f64" => Real::to_f64(x).bits(),
            "mul_f" => Real::mul_f(x, f).bits(),
            "recip" => Real::recip(x).bits(),
            "sqrt" => Real::sqrt(x.abs_part()).bits(),
            "exp" => Real::exp(x.small()).bits(),
            "ln" => Real::ln(x.abs_part()).bits(),
            "recip_int" => <f64 as Real>::recip_int(k).bits(),
            "from_ratio" => <f64 as Real>::from_ratio(p, q).bits(),
            "add" => (x + y).bits(),
            "sub" => (x - y).bits(),
            "mul" => (x * y).bits(),
            "div" => (x / y).bits(),
            "neg" => (-x).bits(),
            _ => unreachable!(),
        }
    };
    delegation_mismatch::<f64>(11, &inherent, &traitm)
}
delegation!(delegation_dd, DD, 12, |d: DD| d, |x: DD| x);
delegation!(delegation_qd, QD, 13, QD::from_dd, QD::to_dd);
delegation!(delegation_od, OD, 14, OD::from_dd, OD::to_dd);

#[test]
fn every_method_is_the_inherent_one() {
    for r in [delegation_f64(), delegation_dd(), delegation_qd(), delegation_od()] {
        assert_eq!(r, None);
    }
}

/// f64's `from_ratio` is the IEEE quotient where p and q are exact in f64, and `recip_int` that of 1 / k
#[test]
fn f64_ratio_is_the_ieee_quotient() {
    let mut rng = Rng(15);
    for _ in 0..2000 {
        let p = (rng.next_u64() >> 11) as i64 * if rng.next_u64() & 1 == 0 { 1 } else { -1 };
        let q = 1 + (rng.next_u64() >> 11);
        assert_eq!(
            <f64 as Real>::from_ratio(p, q).to_bits(),
            (p as f64 / q as f64).to_bits(),
            "{p}/{q}"
        );
        assert_eq!(
            <f64 as Real>::recip_int(q).to_bits(),
            (1.0 / q as f64).to_bits(),
            "1/{q}"
        );
    }
}

/// Control (feature `mutate`): `from_f64` one unit up is seen by the delegation check, in every type
#[cfg(feature = "mutate")]
#[test]
fn control_from_f64_up_fails_delegation() {
    use multidouble::real::mutate;
    mutate::set(mutate::FROM_F64);
    let seen = [delegation_f64(), delegation_dd(), delegation_qd(), delegation_od()];
    mutate::set(0);
    for r in seen {
        let m = r.expect("the mutation must be seen");
        assert!(m.contains("from_f64"), "{m}");
    }
}

// ---- the Cauchy sum ----

/// 300 random sums of 1 to 40 terms (a, b of length k + 1), exponents within 2^+-e
fn sums<T: Real>(seed: u64, e: i32) -> Vec<(Vec<T>, Vec<T>)> {
    let mut rng = Rng(seed);
    (0..300)
        .map(|_| {
            let k = (rng.next_u64() % 40) as usize;
            let a: Vec<T> = (0..=k).map(|_| random(&mut rng, e)).collect();
            let b: Vec<T> = (0..=k).map(|_| random(&mut rng, e)).collect();
            (a, b)
        })
        .collect()
}

/// lane 0 of the accumulator of the type's lane, as multishoot's `Scalar::cauchy` formed it
trait LaneCauchy: Real {
    fn lane_cauchy(a: &[Self], b: &[Self], k: usize) -> Self;
}
macro_rules! lane_cauchy {
    ($t:ty, $lane:ident) => {
        impl LaneCauchy for $t {
            fn lane_cauchy(a: &[$t], b: &[$t], k: usize) -> $t {
                let mut acc = <$lane>::acc0();
                for j in 0..=k {
                    acc = <$lane>::acc(acc, <$lane>::splat(a[j]), <$lane>::splat(b[k - j]));
                }
                <$lane>::fin(acc).lane(0)
            }
        }
    };
}
lane_cauchy!(DD, DV);
lane_cauchy!(QD, QV);
lane_cauchy!(OD, OV);

/// the sums whose `cauchy` differs from lane 0 of the lane accumulator
fn lane_mismatches<T: LaneCauchy + Bits>(seed: u64, e: i32) -> usize {
    sums::<T>(seed, e)
        .iter()
        .filter(|(a, b)| {
            let k = a.len() - 1;
            T::cauchy(a, b, k).bits() != T::lane_cauchy(a, b, k).bits()
        })
        .count()
}

#[test]
fn cauchy_is_the_lane_accumulator() {
    assert_eq!(lane_mismatches::<DD>(21, 30), 0);
    assert_eq!(lane_mismatches::<QD>(22, 30), 0);
    assert_eq!(lane_mismatches::<OD>(23, 30), 0);
}

/// `DdAcc` against `DDotAcc` through the same sums, on its own
#[test]
fn dd_acc_is_the_lane_accumulator() {
    let mut rng = Rng(24);
    for n in 0..300 {
        let k = n % 40;
        let (a, b): (Vec<DD>, Vec<DD>) = (
            (0..=k).map(|_| random(&mut rng, 30)).collect(),
            (0..=k).map(|_| random(&mut rng, 30)).collect(),
        );
        let mut s = DdAcc::zero();
        let mut l = DV::acc0();
        for j in 0..=k {
            s = s.add_prod(a[j], b[j]);
            l = DV::acc(l, DV::splat(a[j]), DV::splat(b[j]));
            // the sum of a plain value, too
            s = s.add(b[j]);
            l = DV::acc1(l, DV::splat(b[j]));
        }
        assert_eq!(s.finish().bits(), DV::fin(l).lane(0).bits(), "k = {k}");
    }
}

/// Control (feature `mutate`): the plain sum of products is not the accumulator, in every multi-double, and `DdAcc`
/// without the products' error terms is not `DDotAcc`
#[cfg(feature = "mutate")]
#[test]
fn control_plain_sum_fails_the_lane_equality() {
    use multidouble::real::mutate;
    mutate::set(mutate::PLAIN_CAUCHY);
    let n = (
        lane_mismatches::<DD>(21, 30),
        lane_mismatches::<QD>(22, 30),
        lane_mismatches::<OD>(23, 30),
    );
    mutate::set(mutate::DD_ACC_NO_ERRORS);
    let m = lane_mismatches::<DD>(21, 30);
    mutate::set(0);
    assert!(
        n.0 > 0 && n.1 > 0 && n.2 > 0,
        "plain sums equal the accumulator's: {n:?}"
    );
    assert!(m > 0, "DdAcc without error terms equals DDotAcc");
}

/// Control (feature `mutate`): `DdAcc` without the products' error terms is not `DDotAcc`
#[cfg(feature = "mutate")]
#[test]
#[should_panic(expected = "k = ")]
fn control_dd_acc_without_errors_fails() {
    use multidouble::real::mutate;
    mutate::set(mutate::DD_ACC_NO_ERRORS);
    let r = std::panic::catch_unwind(dd_acc_is_the_lane_accumulator);
    mutate::set(0);
    if let Err(e) = r {
        std::panic::resume_unwind(e);
    }
}

/// f64's sum is the plain one, from the first product: `start` is the accumulator's start (-0 is the trait's)
fn f64_sum_differs(start: f64) -> usize {
    // sums with zeros of both signs among the products, whose sum is a zero of either sign
    let mut rng = Rng(25);
    let mut bad = 0;
    for n in 0..400 {
        let k = n % 6;
        let pick = |rng: &mut Rng| match rng.next_u64() % 4 {
            0 => 0.0,
            1 => -0.0,
            2 => 1.0,
            _ => -1.0,
        };
        let a: Vec<f64> = (0..=k).map(|_| pick(&mut rng)).collect();
        let b: Vec<f64> = (0..=k).map(|_| pick(&mut rng)).collect();
        let mut plain = a[0] * b[k];
        for j in 1..=k {
            plain += a[j] * b[k - j];
        }
        let mut acc = start;
        for j in 0..=k {
            acc += a[j] * b[k - j];
        }
        let got = if start.to_bits() == (-0.0f64).to_bits() {
            f64::cauchy(&a, &b, k)
        } else {
            acc
        };
        if got.to_bits() != plain.to_bits() {
            bad += 1;
        }
    }
    bad
}

#[test]
fn f64_cauchy_is_the_plain_sum() {
    assert_eq!(f64_sum_differs(-0.0), 0);
}

/// Control: a start of +0 loses the sign of a sum of negative zeros
#[test]
fn control_positive_zero_start_fails() {
    assert!(f64_sum_differs(0.0) > 0);
}

/// the error of `cauchy` against the exact sum, and the bound (|Z| + W) u^n, as a ratio error / bound, worst over the
/// sums; `wrong` moves each result by that many bounds (the control)
fn worst_error_over_bound<T: Bits>(seed: u64, wrong: f64) -> f64 {
    let un = 2f64.powi(-53 * T::PARTS as i32);
    let mut worst = 0.0f64;
    for (a, b) in sums::<T>(seed, 30) {
        let k = a.len() - 1;
        let mut z = Dy::zero();
        let mut w = Dy::zero();
        for j in 0..=k {
            let t = a[j].exact().mul(&b[k - j].exact());
            z = z.add(&t);
            w = w.add(&t.abs());
        }
        let got = T::cauchy(&a, &b, k).exact();
        let bound = z.abs().add(&w).mul(&Dy::from_f64(un * (k as f64 + 9.0)));
        let moved = if wrong == 0.0 {
            got
        } else {
            let step = bound.mul(&Dy::from_f64(wrong));
            got.add(&step)
        };
        let err = moved.sub(&z).abs();
        if err.is_zero() {
            continue;
        }
        worst = worst.max(err.ratio(&bound));
    }
    worst
}

#[test]
fn cauchy_is_within_the_accumulators_bound() {
    for (name, w) in [
        ("f64", worst_error_over_bound::<f64>(31, 0.0)),
        ("dd", worst_error_over_bound::<DD>(32, 0.0)),
        ("qd", worst_error_over_bound::<QD>(33, 0.0)),
        ("od", worst_error_over_bound::<OD>(34, 0.0)),
    ] {
        println!("cauchy {name}: worst error over (k + 9) u^n (|Z| + W) = {w:.3e}");
        assert!(w <= 1.0, "{name}: {w:e}");
    }
}

/// Control: the same results moved by twice the bound fail it
#[test]
fn control_moved_results_fail_the_bound() {
    for w in [
        worst_error_over_bound::<f64>(31, 2.0),
        worst_error_over_bound::<DD>(32, 2.0),
        worst_error_over_bound::<QD>(33, 2.0),
        worst_error_over_bound::<OD>(34, 2.0),
    ] {
        assert!(w > 1.0, "{w:e}");
    }
}

// ---- decimals ----

const PI: &str = "3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196";

/// pi rounded half to even to `digits` significant digits, in `to_sci`'s style, from the decimal text
fn pi_sci(text: &str, digits: usize) -> String {
    let ds: Vec<u8> = text.bytes().filter(|c| c.is_ascii_digit()).collect();
    let mut out: Vec<u8> = ds[..digits].to_vec();
    let next = ds[digits];
    let rest = ds[digits + 1..].iter().any(|&c| c != b'0');
    if next > b'5' || (next == b'5' && (rest || (out[digits - 1] - b'0') % 2 == 1)) {
        let mut i = digits;
        while i > 0 {
            i -= 1;
            if out[i] == b'9' {
                out[i] = b'0';
            } else {
                out[i] += 1;
                break;
            }
        }
    }
    let s = String::from_utf8(out).unwrap();
    format!("{}.{}e+00", &s[..1], &s[1..])
}

/// the digits at which each type prints pi, a few below what it holds
fn pi_digits<T: Real>() -> usize {
    match T::PARTS {
        1 => 15,
        2 => 30,
        4 => 60,
        _ => 120,
    }
}

/// whether the type's parse of `text`, printed at its digits, is pi rounded to them
fn prints_pi<T: Real>(text: &str) -> bool {
    let d = pi_digits::<T>();
    T::parse(PI).map(|x| x.to_sci(d)) == Ok(pi_sci(text, d))
}

#[test]
fn parse_and_print_pi() {
    assert!(prints_pi::<f64>(PI));
    assert!(prints_pi::<DD>(PI));
    assert!(prints_pi::<QD>(PI));
    assert!(prints_pi::<OD>(PI));
}

/// Control: pi with one digit changed (the 14th) is not what the types parse
#[test]
fn control_wrong_pi_fails() {
    let bad = PI.replacen("3.14159265358979", "3.14159265358978", 1);
    assert!(!prints_pi::<f64>(&bad));
    assert!(!prints_pi::<DD>(&bad));
    assert!(!prints_pi::<QD>(&bad));
    assert!(!prints_pi::<OD>(&bad));
}

fn exact_reads<T: Real>() {
    assert_eq!(T::parse("0.125").unwrap().to_f64(), 0.125, "{}", T::NAME);
    assert_eq!(T::parse("-2.5e3").unwrap().to_f64(), -2500.0, "{}", T::NAME);
    assert_eq!(T::parse(" 7 ").unwrap().to_f64(), 7.0, "{}", T::NAME);
    assert!(T::parse("x").is_err(), "{}", T::NAME);
    assert!(T::parse("").is_err(), "{}", T::NAME);
    assert_eq!(T::from_f64(1.5e-5).to_sci(5), "1.5000e-05", "{}", T::NAME);
    assert_eq!(T::from_f64(-0.0).to_sci(5), "-0.0000e+00", "{}", T::NAME);
    assert_eq!(T::from_f64(1234.5).to_sci(3), "1.23e+03", "{}", T::NAME);
}

#[test]
fn parse_reads_and_print_formats() {
    exact_reads::<f64>();
    exact_reads::<DD>();
    exact_reads::<QD>();
    exact_reads::<OD>();
}

/// a random decimal of 40 digits with an exponent: (text, exact value as digits n and power e: n 10^e)
fn random_decimal(rng: &mut Rng) -> (String, BigU, i64) {
    let mut digits = String::new();
    digits.push((b'1' + (rng.next_u64() % 9) as u8) as char);
    for _ in 1..40 {
        digits.push((b'0' + (rng.next_u64() % 10) as u8) as char);
    }
    let e = (rng.next_u64() % 41) as i64 - 20 - 39;
    (format!("{digits}e{e}"), BigU::from_dec(&digits), e)
}

/// the f64 nearest to m 2^e / den (m, den positive integers), by a quotient of at least 79 bits and a sticky remainder
fn round_ratio(m: &BigU, e: i64, den: &BigU) -> f64 {
    let shift = 80 + den.bits();
    let (q, sticky) = div_big(&m.shl(shift), den);
    round_to_f64(&q, e - shift as i64, sticky)
}

/// the double-double rounded from the exact decimal n 10^e: hi = RN(v), lo = RN(v - hi), by exact arithmetic
fn dd_of_decimal(n: &BigU, e: i64) -> [u64; 2] {
    let (num, den) = if e >= 0 {
        (n.mul(&BigU::pow_small(10, e as u64)), BigU::from_u64(1))
    } else {
        (n.clone(), BigU::pow_small(10, (-e) as u64))
    };
    let hi = round_ratio(&num, 0, &den);
    // the remainder v - hi = (num - hi den) / den, exactly
    let den_dy = Dy {
        neg: false,
        m: den.clone(),
        e: 0,
    };
    let num_dy = Dy {
        neg: false,
        m: num,
        e: 0,
    };
    let rem = num_dy.sub(&Dy::from_f64(hi).mul(&den_dy));
    let lo = if rem.is_zero() {
        0.0
    } else {
        let v = round_ratio(&rem.m, rem.e, &den);
        if rem.neg {
            -v
        } else {
            v
        }
    };
    let d = DD::new(hi, lo);
    [d.hi.to_bits(), d.lo.to_bits()]
}

/// big / small as (quotient, sticky = remainder nonzero), by shift and subtract
fn div_big(num: &BigU, den: &BigU) -> (BigU, bool) {
    let mut q = BigU::zero();
    let mut r = BigU::zero();
    for i in (0..num.bits()).rev() {
        r = r.shl(1);
        if num.bit(i) {
            r = r.add(&BigU::from_u64(1));
        }
        q = q.shl(1);
        if r.cmp(den) != std::cmp::Ordering::Less {
            r = r.sub(den);
            q = q.add(&BigU::from_u64(1));
        }
    }
    (q, !r.is_zero())
}

/// how many of 300 random decimals DD's `parse` reads other than the exactly rounded double-double; `shift` moves the
/// reference's decimal by that many units in the last place (the control)
fn dd_parse_misreads(shift: u64) -> usize {
    let mut rng = Rng(41);
    (0..300)
        .filter(|_| {
            let (text, n, e) = random_decimal(&mut rng);
            let n = n.add(&BigU::from_u64(shift));
            <DD as Real>::parse(&text).unwrap().bits() != dd_of_decimal(&n, e)
        })
        .count()
}

#[test]
fn dd_parse_is_the_rounded_decimal() {
    assert_eq!(dd_parse_misreads(0), 0);
}

/// Control: a reference one unit in the last place off disagrees with the parse
#[test]
fn control_shifted_decimals_fail_dd_parse() {
    // 10^9 units of the 40th digit are 10^-31 of the value, above the double-double's 2^-106 of it
    assert!(dd_parse_misreads(1_000_000_000) > 0);
}

// ---- the edges of the conversions ----

/// whether `from_dd` of a double-double -0 reads as -0 in the type, and `parse` of a decimal out of range as the
/// infinity, with no NaN in any part; `from_dd` and `parse` are the closures under test
fn edges_ok<T: Bits>(from_dd: &dyn Fn(DD) -> T, parse: &dyn Fn(&str) -> Result<T, String>) -> bool {
    let neg_zero = from_dd(DD::from_f64(-0.0)).to_f64();
    let (up, down) = (parse("1e309"), parse("-1e309"));
    let inf = |r: Result<T, String>, want: f64| match r {
        Ok(x) => x.bits().iter().all(|&b| !f64::from_bits(b).is_nan()) && x.to_f64() == want,
        Err(_) => false,
    };
    neg_zero == 0.0 && neg_zero.is_sign_negative() && inf(up, f64::INFINITY) && inf(down, f64::NEG_INFINITY)
}

#[test]
fn a_negative_zero_and_an_overflow_survive_the_conversions() {
    assert!(edges_ok::<f64>(&<f64 as Real>::from_dd, &<f64 as Real>::parse));
    assert!(edges_ok::<DD>(&<DD as Real>::from_dd, &<DD as Real>::parse));
    assert!(edges_ok::<QD>(&<QD as Real>::from_dd, &<QD as Real>::parse));
    assert!(edges_ok::<OD>(&<OD as Real>::from_dd, &<OD as Real>::parse));
}

/// Control: `hi + lo` turns a -0 into +0, and `QD::parse` then `QD::to_dd` gives a NaN low part
#[test]
fn control_the_plain_conversions_fail_the_edges() {
    let plain = |d: DD| d.hi + d.lo;
    let parse_f64 = <f64 as Real>::parse;
    assert!(!edges_ok::<f64>(&plain, &parse_f64));
    let naive = |s: &str| QD::parse(s).map(QD::to_dd);
    assert!(!edges_ok::<DD>(&<DD as Real>::from_dd, &naive));
}