multidouble 6.2.1

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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
//! Scalar octo-double: an unevaluated sum x0 + x1 + ... + x7 of eight f64, renormalized so that the parts do not
//! overlap, about 126 significant digits (2^-418 relative, `OD::EPS`). A product, a quotient or a square root has
//! |x_{i+1}| <= ulp(x_i)/2; a sum (od + od, od + f64) |x_{i+1}| <= ulp(x_i), since after cancelling operands its
//! renormalization can leave a part past half the ulp of the one above, up to 0.74 ulp in the tests
//! (`od_tests::od_results_do_not_overlap`; ulp-nonoverlapping in the sense of Joldes, Marty, Muller and Popescu,
//! below). The 8-lane `ov::OV` runs the same algorithms with bitwise the same results.
//!
//! The algorithms are written once over `Limb`, a part position of one value (`f64`) or of eight (`V8`), so the
//! scalar type and the lanes perform the same IEEE operations in the same order. They generalize the quad-double
//! algorithms of the QD library (Y. Hida, X. S. Li, D. H. Bailey, "Algorithms for quad-double precision floating
//! point arithmetic", ARITH-15, 2001, 155-162, doi:10.1109/ARITH.2001.930115) from four parts to eight, with the
//! error-free transformations two-sum and the FMA two-product (`dd`):
//!
//! * Renormalization (`renorm`): QD's two passes. The first runs from the smallest part up with two-sums, so it is
//!   error-free whatever the order of the parts (VecSum: Ogita, Rump, Oishi, "Accurate sum and dot product", SIAM J.
//!   Sci. Comput. 26(6), 2005, 1955-1988, doi:10.1137/030601818; Joldes, Marty, Muller, Popescu, "Arithmetic
//!   algorithms for extended precision using floating-point expansions", IEEE Trans. Comput. 65(4), 2016,
//!   1197-1210, doi:10.1109/TC.2015.2441714). The second runs from the top with two-sums and skips zero errors, so
//!   that an exact partial sum does not leave a gap, and adds what is left into the eighth part. Its two-sums are
//!   exact whatever the order of the first pass's output: a quick-two-sum is exact only when |acc| >= |c_i|, and a
//!   product of a value with a part far below the one above it (x0 + x1 with |x1| far below ulp(x0), or zero parts
//!   between nonzero ones) gives the first pass levels out of magnitude order, where a quick-two-sum dropped terms of
//!   about 2^-325 (`od_tests`, category gap). The renormalization keeps the sum exact but does not sort, so parts out
//!   of magnitude order can leave it out of order. `OD::new` sorts its parts first and checks its result
//!   (`any_order`). The arithmetic's results are checked to stay on the ladder for operands on it
//!   (`od_tests::od_results_do_not_overlap`), not for the gap category's operands (`gapped`), among them values with
//!   zero parts between nonzero ones, which only a value built from raw parts can have.
//! * Addition: the parts pairwise by two-sums, then each error carried down the levels below it, every level but
//!   the last by two-sums (`dep`), and the nine levels renormalized: QD's sloppy add with its error terms kept to
//!   the eighth level. Its error is relative to |a| + |b| (Cray-style), as QD's `+`.
//! * Multiplication: every partial product a_i b_j of order i + j <= 7 by two-product, the products of order 8 by
//!   fused multiply-adds, all deposited by order into nine levels whose first eight sum with two-sums, then
//!   renormalized: QD's accurate multiply, extended to eight parts. The levels carry the product's terms to order 8,
//!   below the eighth part, so its error is that of the renormalization's rounding to eight parts.
//! * The sloppy multiply (`OD::sloppy_mul`, opt-in): QD's sloppy multiply extended to eight parts. Levels 0..6 sum
//!   with two-sums, each carry taken down to level 6 only, and level 7 sums in plain f64 the products of orders 7
//!   and 8 (by fused multiply-adds), the errors of order 6 and the carries out of level 6. There is no level 8, so
//!   the 168 two-sums of the default's carries become 112, and the renormalization of the eight levels is exact. Its
//!   error is the 64 roundings at level 7 and the dropped products of order above 8: at most 2^31.93 u^8 |a_0 b_0|
//!   (u = 2^-53) for operands on the ladder |a_i| <= (2u)^i |a_0|, Theorem 30 of the error-bounds paper (constant from
//!   `paper/sloppy_consts.py`). The bound is a triangle inequality over the 64 roundings: random operands give at most
//!   98 u^8 |a_0 b_0| and a hill climb 582 (`od_tests`, `od_sloppy_mul`, `od_sloppy_worst_case`), where `*` errs by at
//!   most u^8. Its bits differ from `*`'s.
//! * Division: long division, nine quotient terms q_k = r_0 / b_0 with the remainder r - b q_k updated in one pass
//!   (QD's accurate divide); the square root by Newton's iteration on 1/sqrt(a), two steps from the reciprocal of
//!   the double-double square root, after scaling by a power of four.
//! * `OdAcc`: sums of products, each product's nine levels added into nine running levels with two-sums (the scalar
//!   twin of `ov::ODotAcc`); `finish` adds the levels with octo-double + f64.
//!
//! The error bounds the tests check are stated per operation where it is defined (`od_tests`), measured against
//! exact arithmetic (`exact`). paper/expansion-error-bounds.pdf proves the bounds of the sum, product, quotient,
//! square root and sums of products for operands on the ladder; the tests check them. Full precision
//! needs every part to be a normal f64, |x| above about 2^-600 (424 bits above 2^-1022); below that the lower parts
//! lose bits to underflow, as QD's do below about 2^-800.
//!
//! With the cargo feature `mutate`, `mutate::set(id)` breaks one algorithm on purpose in the current thread, for
//! the controls of the accuracy tests; without it the hooks are compile-time `false`.
use crate::dd::DD;
use crate::exact::Dy;
use crate::qd::QD;
use std::cmp::Ordering;
use std::ops::{Add, Div, Mul, Neg, Sub};

/// Deliberate breakage for the controls (feature `mutate`; ids below, 0 = none).
pub mod mutate {
    /// renormalization: the eighth part dropped
    pub const RENORM_DROP: u32 = 1;
    /// two-sum: its error's second term subtracted instead of added (a wrong sign in an error-free transformation)
    pub const TWO_SUM_SIGN: u32 = 2;
    /// add: the error of a1 + b1 dropped
    pub const ADD_T1: u32 = 3;
    /// mul: the error of a2 b3 (an order-6 term) dropped
    pub const MUL_E23: u32 = 4;
    /// od x f64: the error of a3 b dropped
    pub const MUL_F_E3: u32 = 5;
    /// divide: the remainder update before the sixth quotient term skipped
    pub const DIV_REM: u32 = 6;
    /// sqrt: the second Newton step skipped
    pub const SQRT_ITER: u32 = 7;
    /// dot accumulator: the error of the running sum at level 3 dropped
    pub const ACC_L3: u32 = 8;
    /// parse: the last part truncated instead of rounded to nearest
    pub const PARSE_TRUNC: u32 = 9;
    /// 8-lane only: the renormalization's zero test ignored (every error emitted)
    pub const OV_RENORM_MASK: u32 = 10;
    /// 8-lane only, on the backend `simd::Native`: two-product's fused multiply-subtract replaced by a plain product
    /// and a subtraction
    pub const OV_FMA_PLAIN: u32 = 11;
    /// renormalization: the second pass by quick-two-sums, exact only when |acc| >= |c_i|
    pub const RENORM_FAST: u32 = 12;
    /// mul: the products of order 8 dropped, an error of a few u^8 |ab| (u = 2^-53), inside the 1-unit thresholds
    pub const MUL_L8: u32 = 13;
    /// od x dd and od + dd (`alg::expand_dd`, `alg::add_dd`): the second level one ulp up
    pub const DD_ULP: u32 = 14;
    /// sloppy mul: the carries out of level 6 dropped instead of added to level 7 (the truncation one level too
    /// high), an error of about u^7 |ab| whenever one is nonzero, past the sloppy multiply's proven bound
    pub const SLOPPY_C6: u32 = 15;
    /// number of ids
    pub const N: u32 = 15;
    /// the mutations' descriptions, by id
    pub const NAMES: [&str; 16] = [
        "none",
        "renorm: eighth part dropped",
        "two-sum: error with a wrong sign",
        "add: error of a1 + b1 dropped",
        "mul: error of a2 b3 dropped",
        "od x f64: error of a3 b dropped",
        "divide: sixth remainder update skipped",
        "sqrt: second Newton step skipped",
        "dot accumulator: level-3 running error dropped",
        "parse: last part truncated",
        "8-lane renorm: zero test ignored",
        "8-lane two-product: FMA as a plain product (native)",
        "renorm: second pass by quick-two-sums",
        "mul: products of order 8 dropped",
        "od x dd, od + dd: second level one ulp up",
        "sloppy mul: carries out of level 6 dropped",
    ];

    #[cfg(feature = "mutate")]
    thread_local!(static ID: std::cell::Cell<u32> = const { std::cell::Cell::new(0) });

    /// select the mutation for the current thread (0 = none)
    #[cfg(feature = "mutate")]
    pub fn set(id: u32) {
        ID.with(|m| m.set(id));
    }

    /// whether mutation id is selected in the current thread
    #[cfg(feature = "mutate")]
    #[inline(always)]
    pub fn on(id: u32) -> bool {
        ID.with(|m| m.get() == id)
    }

    /// whether mutation id is selected: never, without the feature `mutate`
    #[cfg(not(feature = "mutate"))]
    #[inline(always)]
    pub fn on(_id: u32) -> bool {
        false
    }
}

// ---------------------------------------------------------------------------------------------------------------
// the arithmetic, once for f64 and for the lanes
// ---------------------------------------------------------------------------------------------------------------

/// One part position of octo-doubles: `f64` for the scalar `OD`, `V8<S>` for the lanes of `ov::OV<S>`. The
/// operations are IEEE round-to-nearest with `fma` and `fms` fused, so each is bitwise the same on both.
pub(crate) trait Limb: Copy {
    /// a per-lane condition: bool for f64, `M8<S>` for the lanes
    type M: Copy;
    fn zero() -> Self;
    fn splat(x: f64) -> Self;
    fn add(self, o: Self) -> Self;
    fn sub(self, o: Self) -> Self;
    fn mul(self, o: Self) -> Self;
    fn div(self, o: Self) -> Self;
    /// self b + c with one rounding
    fn fma(self, b: Self, c: Self) -> Self;
    /// self b - c with one rounding
    fn fms(self, b: Self, c: Self) -> Self;
    /// the sign bit flipped
    fn neg(self) -> Self;
    fn sqrt(self) -> Self;
    /// 2^floor(log2 |x|) for normal x
    fn pow2_floor(self) -> Self;
    /// self == 0
    fn is_zero(self) -> Self::M;
    /// per lane: t where m, f elsewhere
    fn sel(m: Self::M, t: Self, f: Self) -> Self;
    /// the renormalization of N >= 8 parts to eight (the scalar one branches on zero errors, the lanes' masks them)
    fn renorm<const N: usize>(c: [Self; N]) -> [Self; 8];
    /// f, an `#[inline(always)]` closure, run as a function of its own on the lane backends that need no target
    /// features (`Simd::outline`) and inlined elsewhere: the steps of the operations below
    fn outline<T>(f: impl FnOnce() -> T) -> T;
}

impl Limb for f64 {
    type M = bool;
    #[inline(always)]
    fn zero() -> f64 {
        0.0
    }
    #[inline(always)]
    fn splat(x: f64) -> f64 {
        x
    }
    #[inline(always)]
    fn add(self, o: f64) -> f64 {
        self + o
    }
    #[inline(always)]
    fn sub(self, o: f64) -> f64 {
        self - o
    }
    #[inline(always)]
    fn mul(self, o: f64) -> f64 {
        self * o
    }
    #[inline(always)]
    fn div(self, o: f64) -> f64 {
        self / o
    }
    #[inline(always)]
    fn fma(self, b: f64, c: f64) -> f64 {
        self.mul_add(b, c)
    }
    #[inline(always)]
    fn fms(self, b: f64, c: f64) -> f64 {
        self.mul_add(b, -c)
    }
    #[inline(always)]
    fn neg(self) -> f64 {
        -self
    }
    #[inline(always)]
    fn sqrt(self) -> f64 {
        f64::sqrt(self)
    }
    #[inline(always)]
    fn pow2_floor(self) -> f64 {
        f64::from_bits(self.to_bits() & 0x7ff0_0000_0000_0000)
    }
    #[inline(always)]
    fn is_zero(self) -> bool {
        self == 0.0
    }
    #[inline(always)]
    fn sel(m: bool, t: f64, f: f64) -> f64 {
        if m {
            t
        } else {
            f
        }
    }
    #[inline(always)]
    fn renorm<const N: usize>(c: [f64; N]) -> [f64; 8] {
        renorm_scalar(c)
    }
    #[inline(always)]
    fn outline<T>(f: impl FnOnce() -> T) -> T {
        f()
    }
}

/// (a + b) as (s, e) with s = RN(a + b), error-free (Knuth's two-sum, as `dd::two_sum`)
#[inline(always)]
pub(crate) fn two_sum<L: Limb>(a: L, b: L) -> (L, L) {
    let s = a.add(b);
    let bb = s.sub(a);
    let x = a.sub(s.sub(bb));
    let y = b.sub(bb);
    if mutate::on(mutate::TWO_SUM_SIGN) {
        (s, x.sub(y))
    } else {
        (s, x.add(y))
    }
}

/// (a + b) as (s, e), error-free when |a| >= |b| (Dekker's fast two-sum, as `dd::quick_two_sum`)
#[inline(always)]
pub(crate) fn quick_two_sum<L: Limb>(a: L, b: L) -> (L, L) {
    let s = a.add(b);
    (s, b.sub(s.sub(a)))
}

/// a b as (p, e), error-free barring underflow (the FMA two-product, as `dd::two_prod`)
#[inline(always)]
pub(crate) fn two_prod<L: Limb>(a: L, b: L) -> (L, L) {
    let p = a.mul(b);
    (p, a.fms(b, p))
}

/// t added into level l of the levels s: two-sums at levels l..K-2, each error carried to the next level, and a
/// plain add at the last level K-1. All levels but the last stay error-free.
#[inline(always)]
fn dep<L: Limb, const K: usize>(s: &mut [L; K], l: usize, t: L) {
    let mut e = t;
    for m in l..K - 1 {
        let (x, y) = two_sum(s[m], e);
        s[m] = x;
        e = y;
    }
    s[K - 1] = s[K - 1].add(e);
}

/// The first pass of the renormalization, from the smallest part up: s = c[N-1], then (s, c[i+1]) = two-sum(c[i],
/// s) for i = N-2 down to 0, and c[0] = s. Error-free (VecSum), whatever the order of the parts' magnitudes.
#[inline(always)]
pub(crate) fn vecsum<L: Limb, const N: usize>(c: [L; N]) -> [L; N] {
    let mut c = c;
    let mut s = c[N - 1];
    for i in (0..N - 1).rev() {
        let (t, e) = two_sum(c[i], s);
        s = t;
        c[i + 1] = e;
    }
    c[0] = s;
    c
}

/// The renormalization of N parts to eight, branching on zero errors (`ov` has the masked twin): the two-sum pass from
/// the smallest part up (`vecsum`), then a two-sum pass from the top (a quick-two-sum where |acc| >= |c_i|, which is
/// exact and gives the same bits) that emits a part only where the error is nonzero, and once seven parts are out adds
/// the rest into the eighth. An infinite first part returns the first eight parts as they are.
#[inline(always)]
pub(crate) fn renorm_scalar<const N: usize>(c: [f64; N]) -> [f64; 8] {
    if c[0].is_infinite() {
        return std::array::from_fn(|i| if i < N { c[i] } else { 0.0 });
    }
    let c = vecsum(c);
    let mut out = [0.0f64; 8];
    let mut k = 0;
    let mut acc = c[0];
    for &ci in &c[1..] {
        // exact in any order: VecSum's output can be out of magnitude order (a product of a value with a part far
        // below the one above it). A quick-two-sum is exact when |acc| >= |c_i| and then gives the two-sum's bits; the
        // scalar type branches to it (an od + od about 1.2x faster), the lanes take the two-sum throughout
        let (t, e) = if mutate::on(mutate::RENORM_FAST) || acc.abs() >= ci.abs() {
            quick_two_sum(acc, ci)
        } else {
            two_sum(acc, ci)
        };
        if k < 7 && e != 0.0 {
            out[k] = t;
            k += 1;
            acc = e;
        } else {
            acc = t;
        }
    }
    out[k] = acc;
    if mutate::on(mutate::RENORM_DROP) {
        out[7] = 0.0;
    }
    out
}

/// the eight-part arithmetic on part arrays, for `OD` and `ov::OV`
pub(crate) mod alg {
    use super::{dep, mutate, quick_two_sum, two_prod, two_sum, Limb};

    /// a + b (the default `+`): the parts pairwise by two-sums, the errors carried down nine levels, renormalized
    #[inline(always)]
    pub fn add<L: Limb>(a: &[L; 8], b: &[L; 8]) -> [L; 8] {
        L::outline(
            #[inline(always)]
            || {
                let mut s = [L::zero(); 9];
                let mut t = [L::zero(); 8];
                for i in 0..8 {
                    (s[i], t[i]) = two_sum(a[i], b[i]);
                }
                if mutate::on(mutate::ADD_T1) {
                    t[1] = L::zero();
                }
                s[8] = t[7];
                dep(&mut s, 1, t[0]);
                dep(&mut s, 2, t[1]);
                dep(&mut s, 3, t[2]);
                dep(&mut s, 4, t[3]);
                dep(&mut s, 5, t[4]);
                dep(&mut s, 6, t[5]);
                dep(&mut s, 7, t[6]);
                L::renorm(s)
            },
        )
    }

    /// a + b for an exact f64 b: b down the parts by two-sums, renormalized from nine parts
    #[inline(always)]
    pub fn add_f<L: Limb>(a: &[L; 8], b: L) -> [L; 8] {
        L::outline(
            #[inline(always)]
            || {
                let mut s = [L::zero(); 9];
                let mut e = b;
                for i in 0..8 {
                    (s[i], e) = two_sum(a[i], e);
                }
                s[8] = e;
                L::renorm(s)
            },
        )
    }

    /// a b for an exact f64 b: eight two-products, their errors carried down nine levels, renormalized
    #[inline(always)]
    pub fn mul_f<L: Limb>(a: &[L; 8], b: L) -> [L; 8] {
        L::outline(
            #[inline(always)]
            || {
                let mut s = [L::zero(); 9];
                let mut e = [L::zero(); 8];
                for i in 0..8 {
                    (s[i], e[i]) = two_prod(a[i], b);
                }
                if mutate::on(mutate::MUL_F_E3) {
                    e[3] = L::zero();
                }
                s[8] = e[7];
                dep(&mut s, 1, e[0]);
                dep(&mut s, 2, e[1]);
                dep(&mut s, 3, e[2]);
                dep(&mut s, 4, e[3]);
                dep(&mut s, 5, e[4]);
                dep(&mut s, 6, e[5]);
                dep(&mut s, 7, e[6]);
                L::renorm(s)
            },
        )
    }

    /// a b by order: levels 0..7 hold the partial products of their order and the errors carried into them, all
    /// summed with two-sums, and level 8 the products of order 8 (by FMA) and everything below, in plain f64
    #[inline(always)]
    pub fn expand<L: Limb>(a: &[L; 8], b: &[L; 8]) -> [L; 9] {
        L::outline(
            #[inline(always)]
            || {
                let mut s = [L::zero(); 9];
                let mut e = [L::zero(); 8];
                for j in 0..8 {
                    (s[j], e[j]) = two_prod(a[0], b[j]);
                }
                s[8] = a[7].fma(
                    b[1],
                    a[6].fma(
                        b[2],
                        a[5].fma(b[3], a[4].fma(b[4], a[3].fma(b[5], a[2].fma(b[6], a[1].mul(b[7]))))),
                    ),
                );
                if mutate::on(mutate::MUL_L8) {
                    s[8] = L::zero();
                }
                dep(&mut s, 1, e[0]);
                dep(&mut s, 2, e[1]);
                dep(&mut s, 3, e[2]);
                dep(&mut s, 4, e[3]);
                dep(&mut s, 5, e[4]);
                dep(&mut s, 6, e[5]);
                dep(&mut s, 7, e[6]);
                dep(&mut s, 8, e[7]);
                // rows 1..7: a_i b_j into level i + j, its error into level i + j + 1
                macro_rules! pp {
                ($(($i:literal, $j:literal)),*) => {
                    $({
                        let (p, e) = two_prod(a[$i], b[$j]);
                        let e = if $i == 2 && $j == 3 && mutate::on(mutate::MUL_E23) { L::zero() } else { e };
                        dep(&mut s, $i + $j, p);
                        dep(&mut s, $i + $j + 1, e);
                    })*
                };
            }
                pp!((1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6));
                pp!((2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5));
                pp!((3, 0), (3, 1), (3, 2), (3, 3), (3, 4));
                pp!((4, 0), (4, 1), (4, 2), (4, 3));
                pp!((5, 0), (5, 1), (5, 2));
                pp!((6, 0), (6, 1));
                pp!((7, 0));
                s
            },
        )
    }

    /// a b (the default `*`): the nine levels of `expand`, renormalized
    #[inline(always)]
    pub fn mul<L: Limb>(a: &[L; 8], b: &[L; 8]) -> [L; 8] {
        L::renorm(expand(a, b))
    }

    /// `expand(a, b)` for a double-double b = (b0, b1, 0, ..., 0), bitwise up to NaNs' signs and payloads, without
    /// the partial products of b's six zero parts: 15 two-products of the 36, and one product of the order-8 sum's
    /// seven. For finite parts of a those products deposit zeros at levels 3..8. The carry of a0 b0's error (`dep`
    /// from level 1) leaves no -0 at levels 2..8, as a two-sum's error is never -0, so the zero deposits after it
    /// change nothing. Before it, `expand`'s levels 2..8 differ from these at most in the sign of a zero, which that
    /// carry erases. An infinite or NaN part makes some skipped products NaN. A non-finite a0 makes e0 NaN, whose
    /// carry fills levels 1..8. A non-finite a_i, i >= 1, makes the kept a_i b0's error NaN, whose carry fills
    /// levels i + 1..8, where every skipped NaN lands.
    #[inline(always)]
    pub fn expand_dd<L: Limb>(a: &[L; 8], b0: L, b1: L) -> [L; 9] {
        L::outline(
            #[inline(always)]
            || {
                let mut s = [L::zero(); 9];
                let (p0, e0) = two_prod(a[0], b0);
                let (p1, e1) = two_prod(a[0], b1);
                s[0] = p0;
                s[1] = p1;
                if mutate::on(mutate::DD_ULP) {
                    // one ulp up, for a normal p1
                    s[1] = p1.add(p1.pow2_floor().mul(L::splat(f64::EPSILON)));
                }
                // the order-8 sum of `expand` without its zero products
                s[8] = a[7].mul(b1);
                if mutate::on(mutate::MUL_L8) {
                    s[8] = L::zero();
                }
                dep(&mut s, 1, e0);
                dep(&mut s, 2, e1);
                // rows 1..7 of `expand`, columns 0 and 1
                macro_rules! pp {
                ($(($i:literal, $j:literal)),*) => {
                    $({
                        let (p, e) = two_prod(a[$i], if $j == 0 { b0 } else { b1 });
                        dep(&mut s, $i + $j, p);
                        dep(&mut s, $i + $j + 1, e);
                    })*
                };
            }
                pp!((1, 0), (1, 1));
                pp!((2, 0), (2, 1));
                pp!((3, 0), (3, 1));
                pp!((4, 0), (4, 1));
                pp!((5, 0), (5, 1));
                pp!((6, 0), (6, 1));
                pp!((7, 0));
                s
            },
        )
    }

    /// `dep` on the sloppy product's eight levels: two-sums at levels l..6, a plain add at level 7 (with
    /// `mutate::SLOPPY_C6`, the carry out of level 6 dropped)
    #[inline(always)]
    fn dep_sloppy<L: Limb>(s: &mut [L; 8], l: usize, t: L) {
        if l <= 6 && mutate::on(mutate::SLOPPY_C6) {
            let mut e = t;
            for m in l..7 {
                (s[m], e) = two_sum(s[m], e);
            }
        } else {
            dep(s, l, t);
        }
    }

    /// The sloppy product's eight levels: levels 0..6 as in `expand`, each deposit carried down with two-sums to
    /// level 6 only, and level 7 in plain f64. Level 7 holds the products of orders 7 and 8 by fused multiply-adds,
    /// the smallest first, the errors of the products of order 6, and the carries out of level 6.
    #[inline(always)]
    pub fn expand_sloppy<L: Limb>(a: &[L; 8], b: &[L; 8]) -> [L; 8] {
        L::outline(
            #[inline(always)]
            || {
                let mut s = [L::zero(); 8];
                let mut e = [L::zero(); 7];
                for j in 0..7 {
                    (s[j], e[j]) = two_prod(a[0], b[j]);
                }
                let o8 = a[7].fma(
                    b[1],
                    a[6].fma(
                        b[2],
                        a[5].fma(b[3], a[4].fma(b[4], a[3].fma(b[5], a[2].fma(b[6], a[1].mul(b[7]))))),
                    ),
                );
                s[7] = a[7].fma(
                    b[0],
                    a[6].fma(
                        b[1],
                        a[5].fma(
                            b[2],
                            a[4].fma(b[3], a[3].fma(b[4], a[2].fma(b[5], a[1].fma(b[6], a[0].fma(b[7], o8))))),
                        ),
                    ),
                );
                dep_sloppy(&mut s, 1, e[0]);
                dep_sloppy(&mut s, 2, e[1]);
                dep_sloppy(&mut s, 3, e[2]);
                dep_sloppy(&mut s, 4, e[3]);
                dep_sloppy(&mut s, 5, e[4]);
                dep_sloppy(&mut s, 6, e[5]);
                dep_sloppy(&mut s, 7, e[6]);
                // rows 1..6: a_i b_j of order i + j <= 6 into level i + j, its error into level i + j + 1
                macro_rules! pp {
                ($(($i:literal, $j:literal)),*) => {
                    $({
                        let (p, e) = two_prod(a[$i], b[$j]);
                        dep_sloppy(&mut s, $i + $j, p);
                        dep_sloppy(&mut s, $i + $j + 1, e);
                    })*
                };
            }
                pp!((1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5));
                pp!((2, 0), (2, 1), (2, 2), (2, 3), (2, 4));
                pp!((3, 0), (3, 1), (3, 2), (3, 3));
                pp!((4, 0), (4, 1), (4, 2));
                pp!((5, 0), (5, 1));
                pp!((6, 0));
                s
            },
        )
    }

    /// a b for a double-double b = (b0, b1): bitwise `mul(a, b)`, the levels of `expand_dd` renormalized
    #[inline(always)]
    pub fn mul_dd<L: Limb>(a: &[L; 8], b0: L, b1: L) -> [L; 8] {
        L::renorm(expand_dd(a, b0, b1))
    }

    /// `add(a, b)` for a double-double b = (b0, b1, 0, ..., 0), bitwise up to NaNs' signs and payloads, without the
    /// two-sums of a's parts 2..7 with zero and the carries of their errors. For a finite part such a two-sum returns
    /// the part, a -0 as +0, with a zero error, and the carry of a0 + b0's error erases that difference as in
    /// `expand_dd`. For an infinite or NaN part its error is NaN, and that carry, passing the part's level, makes
    /// every level below it NaN.
    #[inline(always)]
    pub fn add_dd<L: Limb>(a: &[L; 8], b0: L, b1: L) -> [L; 8] {
        L::outline(
            #[inline(always)]
            || {
                let mut s = [L::zero(); 9];
                let (s0, t0) = two_sum(a[0], b0);
                let (s1, t1) = two_sum(a[1], b1);
                s[0] = s0;
                s[1] = s1;
                if mutate::on(mutate::DD_ULP) {
                    // one ulp up, for a normal s1
                    s[1] = s1.add(s1.pow2_floor().mul(L::splat(f64::EPSILON)));
                }
                s[2..8].copy_from_slice(&a[2..8]);
                let t1 = if mutate::on(mutate::ADD_T1) { L::zero() } else { t1 };
                dep(&mut s, 1, t0);
                dep(&mut s, 2, t1);
                L::renorm(s)
            },
        )
    }

    /// a b by the sloppy multiply: the eight levels of `expand_sloppy`, renormalized (exactly, as eight terms)
    #[inline(always)]
    pub fn sloppy_mul<L: Limb>(a: &[L; 8], b: &[L; 8]) -> [L; 8] {
        L::renorm(expand_sloppy(a, b))
    }

    /// r - b q for an f64 q in one pass: r_i - RN(b_i q) by two-sums, those errors and the errors of the products
    /// carried down nine levels, renormalized (the remainder of long division)
    #[inline(always)]
    pub fn sub_mul_f<L: Limb>(r: &[L; 8], b: &[L; 8], q: L) -> [L; 8] {
        L::outline(
            #[inline(always)]
            || {
                let mut s = [L::zero(); 9];
                let mut t = [L::zero(); 8];
                let mut e = [L::zero(); 8];
                for i in 0..8 {
                    let (p, pe) = two_prod(b[i], q);
                    (s[i], t[i]) = two_sum(r[i], p.neg());
                    e[i] = pe.neg();
                }
                s[8] = t[7].add(e[7]);
                macro_rules! carry {
                ($($l:literal),*) => {
                    $(
                        dep(&mut s, $l + 1, t[$l]);
                        dep(&mut s, $l + 1, e[$l]);
                    )*
                };
            }
                carry!(0, 1, 2, 3, 4, 5, 6);
                L::renorm(s)
            },
        )
    }

    /// a / b by long division (QD's accurate divide with nine quotient terms), each quotient term q(r_0) = r_0 / b_0
    /// (so that `ov::OV::div_by` can pass a shared divisor)
    #[inline(always)]
    pub fn div<L: Limb>(a: &[L; 8], b: &[L; 8], q: impl Fn(L) -> L) -> [L; 8] {
        let mut qs = [L::zero(); 9];
        let mut r = *a;
        qs[0] = q(r[0]);
        for k in 1..9 {
            if !(k == 5 && mutate::on(mutate::DIV_REM)) {
                r = sub_mul_f(&r, b, qs[k - 1]);
            }
            qs[k] = q(r[0]);
        }
        L::renorm(qs)
    }

    /// times a power of two, every part
    #[inline(always)]
    pub fn mul_pwr2<L: Limb>(a: &[L; 8], s: L) -> [L; 8] {
        let mut r = *a;
        for k in 0..8 {
            r[k] = a[k].mul(s);
        }
        r
    }

    /// -a: the first part's sign bit flipped, the others as -x + 0, so a zero lower part is +0 (as `QD`'s)
    #[inline(always)]
    pub fn neg<L: Limb>(a: &[L; 8]) -> [L; 8] {
        let z = L::zero();
        let mut r = *a;
        r[0] = a[0].neg();
        for k in 1..8 {
            r[k] = a[k].neg().add(z);
        }
        r
    }

    /// The square root: Newton's iteration on 1/sqrt(a), two steps from the reciprocal of the double-double square
    /// root of a's two leading parts, the first with its second-order term, then times a, applied to a scaled by an
    /// exact power of four into [1, 4) and the result scaled back. A zero gives zero. The products and sums are the
    /// caller's (`mul`, `add`, `add_f`: the type's own operations, so that they are not inlined here at every call).
    #[inline(always)]
    pub fn sqrt<L: Limb>(
        x: &[L; 8],
        mul: impl Fn(&[L; 8], &[L; 8]) -> [L; 8],
        add: impl Fn(&[L; 8], &[L; 8]) -> [L; 8],
        add_f: impl Fn(&[L; 8], L) -> [L; 8],
    ) -> [L; 8] {
        let z = L::zero();
        let zero = x[0].is_zero();
        let s = x[0].sqrt().pow2_floor();
        let inv = L::splat(1.0).div(s);
        let mut a = *x;
        for k in 0..8 {
            a[k] = x[k].mul(inv).mul(inv);
        }
        let one = L::splat(1.0);
        // r_0 = 1 / y for y the double-double square root of a_0 + a_1, renormalized to a double-word number by a
        // quick two-sum: y by Algorithm 8 of Lefevre, Louvet, Muller, Picot and Rideau (`DD::sqrt`, within 25/8 u^2;
        // a_0 is in [1, 4)) and 1 / y by DWDivDW2 of Joldes, Muller and Popescu (`DD::fast_div`, within
        // 15 u^2 + 56 u^3)
        let (a0, a1) = quick_two_sum(a[0], a[1]);
        let sh = a0.sqrt();
        let (yh, yl) = quick_two_sum(sh, a1.add(sh.neg().fma(sh, a0)).div(sh.add(sh)));
        let th = one.div(yh);
        let (ch, cl1) = two_prod(yh, th);
        let (g, tl1) = quick_two_sum(ch, yl.mul(th));
        let (rh, rl) = quick_two_sum(g, tl1.add(cl1));
        let (r0, r1) = quick_two_sum(th, one.sub(rh).sub(rl).div(yh));
        let mut r = [z; 8];
        r[0] = r0;
        r[1] = r1;
        let h = mul_pwr2(&a, L::splat(0.5));
        // first step, with its second-order term: r + (c + 3/2 c^2) r for c = 1/2 - h r^2, an error cubic in r_0's
        let c = add_f(&neg(&mul(&h, &mul(&r, &r))), L::splat(0.5));
        let c2 = mul(&c, &c);
        let w = add(&c, &add(&c2, &mul_pwr2(&c2, L::splat(0.5))));
        r = add(&r, &mul(&w, &r));
        // second step, Newton's: r + (1/2 - h r^2) r
        if !mutate::on(mutate::SQRT_ITER) {
            let c = add_f(&neg(&mul(&h, &mul(&r, &r))), L::splat(0.5));
            r = add(&r, &mul(&c, &r));
        }
        let mut r = mul(&r, &a);
        for k in 0..8 {
            r[k] = L::sel(zero, z, r[k].mul(s));
        }
        r
    }

    /// the levels of `expand` (or a's parts) added into the running levels acc: level l by two-sums into acc[l],
    /// each error carried down to level 8, which sums in plain f64
    #[inline(always)]
    pub fn acc_levels<L: Limb, const K: usize>(acc: &mut [L; 9], t: &[L; K]) {
        L::outline(
            #[inline(always)]
            || {
                for l in 0..K.min(8) {
                    if l == 3 && mutate::on(mutate::ACC_L3) {
                        let (x, _) = two_sum(acc[3], t[3]);
                        acc[3] = x;
                        continue;
                    }
                    dep(acc, l, t[l]);
                }
                if K > 8 {
                    acc[8] = acc[8].add(t[8]);
                }
            },
        )
    }

    /// quick-two-sum of a0 and the sum of the lower parts (a's value to about 2^-106)
    #[inline(always)]
    pub fn to_dd<L: Limb>(a: &[L; 8]) -> (L, L) {
        let t = a[1].add(a[2].add(a[3].add(a[4].add(a[5].add(a[6].add(a[7]))))));
        quick_two_sum(a[0], t)
    }

    /// the four leading parts, the fourth with the sum of the lower four added (renormalized by the caller)
    #[inline(always)]
    pub fn to_qd_parts<L: Limb>(a: &[L; 8]) -> [L; 4] {
        [a[0], a[1], a[2], a[3].add(a[4].add(a[5].add(a[6].add(a[7]))))]
    }

    /// a0 and the sum of the lower parts (a's nearest f64 to within that sum's rounding)
    #[inline(always)]
    pub fn to_f64_parts<L: Limb>(a: &[L; 8]) -> (L, L) {
        (a[0], a[1].add(a[2].add(a[3].add(a[4].add(a[5].add(a[6].add(a[7])))))))
    }
}

// ---------------------------------------------------------------------------------------------------------------
// the scalar type
// ---------------------------------------------------------------------------------------------------------------

/// Octo-double `x[0] + x[1] + ... + x[7]`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct OD {
    /// the parts, largest first. `OD::new` puts parts given in any order so, each at most the ulp of the one before
    /// and zeros only at the end; a value built from its fields must keep that order.
    pub x: [f64; 8],
}

impl OD {
    /// 0
    pub const ZERO: OD = OD { x: [0.0; 8] };
    /// 1
    pub const ONE: OD = OD {
        x: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
    };
    /// 2^-418, the unit of the error bounds (twice the exponent of QD's 2^-209; the parts hold 424 bits)
    pub const EPS: f64 = f64::from_bits((1023 - 418) << 52);

    /// The exact sum of eight finite parts in any order, as eight parts largest first: zero parts only after the
    /// nonzero ones, and each part at most the ulp of the one before (`any_order`). Parts already so, as the arithmetic
    /// returns them, are renormalized as given (`renorm_scalar`, exact for eight parts) with its bits. Others are
    /// sorted by decreasing magnitude and renormalized, and a result off the ladder (parts that overlap in one binade)
    /// is replaced by the parts' exact expansion, compressed. With an infinite or NaN part the result is not finite.
    #[inline]
    pub fn new(x: [f64; 8]) -> OD {
        if crate::any_order::mutate::on(crate::any_order::mutate::AS_GIVEN) {
            return OD { x: renorm_scalar(x) };
        }
        OD {
            x: crate::any_order::exact_sum(x, renorm_scalar, renorm_scalar),
        }
    }
    /// exact
    #[inline(always)]
    pub fn from_f64(x: f64) -> OD {
        let mut o = OD::ZERO;
        o.x[0] = x;
        o
    }
    /// exact
    #[inline(always)]
    pub fn from_dd(d: DD) -> OD {
        let mut o = OD::ZERO;
        o.x[0] = d.hi;
        o.x[1] = d.lo;
        o
    }
    /// exact
    #[inline(always)]
    pub fn from_qd(q: QD) -> OD {
        let mut o = OD::ZERO;
        o.x[..4].copy_from_slice(&q.x);
        o
    }
    /// nearest f64 (to within the rounding of the seven lower parts' sum); a zero tail leaves the leading part as it
    /// is, so a zero keeps its sign
    #[inline(always)]
    pub fn to_f64(self) -> f64 {
        let (h, t) = alg::to_f64_parts(&self.x);
        if t == 0.0 {
            h
        } else {
            h + t
        }
    }
    /// double-double, to about 2^-106 relative (as `QD::to_dd`)
    #[inline(always)]
    pub fn to_dd(self) -> DD {
        let (hi, lo) = alg::to_dd(&self.x);
        DD { hi, lo }
    }
    /// quad-double, to about 2^-212 relative: the four leading parts with the lower four's sum added to the fourth,
    /// renormalized (`QD::new`)
    #[inline(always)]
    pub fn to_qd(self) -> QD {
        let [a, b, c, d] = alg::to_qd_parts(&self.x);
        QD::new(a, b, c, d)
    }
    /// the leading part is zero (so, renormalized, every part is)
    #[inline(always)]
    pub fn is_zero(self) -> bool {
        self.x[0] == 0.0
    }
    /// |self|: negated where the leading part is negative
    #[inline(always)]
    pub fn abs(self) -> OD {
        if self.x[0] < 0.0 {
            -self
        } else {
            self
        }
    }
    /// times a power of two b (`dd::is_pwr2`): every part scaled, exact barring overflow and underflow
    #[inline(always)]
    pub fn mul_pwr2(self, b: f64) -> OD {
        debug_assert!(crate::dd::is_pwr2(b), "mul_pwr2: {b} is not a power of two");
        OD {
            x: alg::mul_pwr2(&self.x, b),
        }
    }
    /// od + f64
    #[inline]
    pub fn add_f(self, b: f64) -> OD {
        OD {
            x: alg::add_f(&self.x, b),
        }
    }
    /// a b by the sloppy multiply (see the module doc): levels 0..6 error-free, level 7 in plain f64, about 1.3 times
    /// fewer instructions than `*`, within 2^31.93 u^8 |a_0 b_0| of the exact product for operands on the ladder. Its
    /// bits differ from `*`.
    #[inline]
    pub fn sloppy_mul(self, b: OD) -> OD {
        OD {
            x: alg::sloppy_mul(&self.x, &b.x),
        }
    }
    /// od x f64
    #[inline]
    pub fn mul_f(self, b: f64) -> OD {
        OD {
            x: alg::mul_f(&self.x, b),
        }
    }
    /// od + dd: bitwise `self + OD::from_dd(b)`, without the steps for the zero parts (`alg::add_dd`)
    #[inline]
    pub fn add_dd(self, b: DD) -> OD {
        OD {
            x: alg::add_dd(&self.x, b.hi, b.lo),
        }
    }
    /// od x dd: bitwise `self * OD::from_dd(b)`, without the partial products of the zero parts (`alg::expand_dd`)
    #[inline]
    pub fn mul_dd(self, b: DD) -> OD {
        OD {
            x: alg::mul_dd(&self.x, b.hi, b.lo),
        }
    }
    /// 1 / self
    #[inline]
    pub fn recip(self) -> OD {
        OD::ONE / self
    }
    /// the square root (Newton's iteration on 1/sqrt(a), see the module doc); a negative value gives NaN
    #[inline]
    pub fn sqrt(self) -> OD {
        let w = |x: &[f64; 8]| OD { x: *x };
        OD {
            x: alg::sqrt(
                &self.x,
                |a, b| (w(a) * w(b)).x,
                |a, b| (w(a) + w(b)).x,
                |a, b| w(a).add_f(b).x,
            ),
        }
    }
    /// integer power: binary powering, 1/a^|n| for n < 0 (as `QD::powi`)
    pub fn powi(self, n: i32) -> OD {
        if n == 0 {
            return OD::ONE;
        }
        let mut r = self;
        let mut s = OD::ONE;
        let mut nn = n.unsigned_abs();
        if nn > 1 {
            while nn > 0 {
                if nn % 2 == 1 {
                    s = s * r;
                }
                nn /= 2;
                if nn > 0 {
                    r = r * r;
                }
            }
        } else {
            s = r;
        }
        if n < 0 {
            OD::ONE / s
        } else {
            s
        }
    }

    /// the exact value of the eight-part sum (finite parts)
    pub fn exact(self) -> Dy {
        Dy::sum(&self.x)
    }

    /// Parse a decimal ("-1.234e-5", "3.14159...", "42"): the exact decimal value rounded to eight parts by greedy
    /// round-to-nearest (x0 = RN(v), x1 = RN(v - x0), ...), so |error| <= ulp(x7)/2 <= 2^-424 |v|.
    ///
    /// ```
    /// use multidouble::od::OD;
    /// let x: OD = "1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727"
    ///     .parse()
    ///     .unwrap();
    /// assert!((x * x - OD::from_f64(2.0)).to_f64().abs() < 1e-99);
    /// ```
    pub fn parse(s: &str) -> Result<OD, String> {
        let mut x = crate::qd::parse_parts::<8>(s, mutate::on(mutate::PARSE_TRUNC))?;
        // a lower part that rounded to zero below the subnormals is +0, as everywhere else
        for v in x[1..].iter_mut() {
            *v += 0.0;
        }
        Ok(OD { x })
    }

    /// Scientific notation with `digits` significant digits, correctly rounded (half to even) from the exact value
    /// of the eight-part sum: "-1.2345e-05" style, at least two exponent digits.
    pub fn to_sci(self, digits: usize) -> String {
        crate::qd::sci_parts(&self.x, digits)
    }
}

impl std::fmt::Display for OD {
    /// 128 significant digits (the eight parts carry about 126)
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_sci(f.precision().map(|p| p + 1).unwrap_or(128)))
    }
}

impl std::str::FromStr for OD {
    type Err = String;
    /// parse a decimal (`OD::parse`)
    fn from_str(s: &str) -> Result<OD, String> {
        OD::parse(s)
    }
}

/// Lexicographic on the parts, as the QD library orders quad-doubles; None if a part is NaN. For renormalized values
/// (nonoverlapping parts) this is the order of the values, up to ties at the parts' half-ulp bounds.
impl PartialOrd for OD {
    /// the parts compared in turn, the first that differ deciding
    fn partial_cmp(&self, o: &OD) -> Option<Ordering> {
        for i in 0..8 {
            match self.x[i].partial_cmp(&o.x[i])? {
                Ordering::Equal => continue,
                c => return Some(c),
            }
        }
        Some(Ordering::Equal)
    }
}

impl Neg for OD {
    type Output = OD;
    /// every part negated, the lower seven as -x + 0, so that a zero lower part is +0 (as `QD`'s)
    #[inline(always)]
    fn neg(self) -> OD {
        OD { x: alg::neg(&self.x) }
    }
}

impl Add for OD {
    type Output = OD;
    /// a + b (QD's sloppy add carried to eight parts, see the module doc)
    #[inline]
    fn add(self, b: OD) -> OD {
        OD {
            x: alg::add(&self.x, &b.x),
        }
    }
}

impl Sub for OD {
    type Output = OD;
    /// a + (-b)
    #[inline]
    fn sub(self, b: OD) -> OD {
        self + (-b)
    }
}

impl Mul for OD {
    type Output = OD;
    /// a b (the partial products to order 8, renormalized)
    #[inline]
    fn mul(self, b: OD) -> OD {
        OD {
            x: alg::mul(&self.x, &b.x),
        }
    }
}

impl Div for OD {
    type Output = OD;
    /// a / b by long division, nine quotient terms
    #[inline]
    fn div(self, b: OD) -> OD {
        let b0 = b.x[0];
        OD {
            x: alg::div(&self.x, &b.x, |r: f64| r / b0),
        }
    }
}

/// the eight parts of octo-doubles as eight arrays, part k of value i at index i of array k (the layout of
/// `OV::load`), the inverse of `from_parts`
pub fn to_parts(v: &[OD]) -> [Vec<f64>; 8] {
    std::array::from_fn(|k| v.iter().map(|q| q.x[k]).collect())
}

/// octo-doubles from the arrays of their eight parts, the parts as they are (`OD { x }`, not renormalized as
/// `OD::new`). Arrays of different lengths panic.
pub fn from_parts(c: [&[f64]; 8]) -> Vec<OD> {
    let n = c[0].len();
    assert!(
        c.iter().all(|p| p.len() == n),
        "from_parts: the eight arrays must have one length"
    );
    (0..n)
        .map(|i| OD {
            x: std::array::from_fn(|k| c[k][i]),
        })
        .collect()
}

/// Scalar sum-of-products accumulator, the twin of `ov::ODotAcc` (same algorithm, bitwise the same per lane): nine
/// running levels, the first eight summed with two-sums and the last in plain f64. Each product's levels (`expand`,
/// its terms to order 8) are added into them with their errors carried down. For K products of operands on the ladder
/// the error is at most (|Z| + c_K W) u^8, W = sum |a_i b_i| and u = 2^-53, with c_K below 1 up to K = 50 (`od_tests`,
/// `acc_thr`). c_K grows like K^9 u, and 2048 constructed terms reach 2^23.8 u^8 |Z|, while random sums stay near
/// u^8 W. The proof is the section on sums of products of paper/expansion-error-bounds.pdf.
#[derive(Clone, Copy, Debug, Default)]
pub struct OdAcc {
    /// the running levels, the largest first
    pub s: [f64; 9],
}

impl OdAcc {
    /// the empty sum
    pub fn zero() -> OdAcc {
        OdAcc::default()
    }
    /// self + a b
    #[inline]
    pub fn add_prod(self, a: OD, b: OD) -> OdAcc {
        let t = alg::expand(&a.x, &b.x);
        let mut s = self.s;
        alg::acc_levels(&mut s, &t);
        OdAcc { s }
    }
    /// self + a b for a double-double b: bitwise `add_prod(a, OD::from_dd(b))` (`alg::expand_dd`)
    #[inline]
    pub fn add_prod_dd(self, a: OD, b: DD) -> OdAcc {
        let t = alg::expand_dd(&a.x, b.hi, b.lo);
        let mut s = self.s;
        alg::acc_levels(&mut s, &t);
        OdAcc { s }
    }
    /// self + a b by the sloppy multiply's eight levels (`OD::sloppy_mul`), added into the running levels as `add`
    /// adds a value. Each product adds its own error, at most 2^31.93 u^8 |a_0 b_0|, and the levels' accumulation is
    /// the default's; it can be mixed with `add_prod` and `add` in one sum.
    #[inline]
    pub fn add_prod_sloppy(self, a: OD, b: OD) -> OdAcc {
        let t = alg::expand_sloppy(&a.x, &b.x);
        let mut s = self.s;
        alg::acc_levels(&mut s, &t);
        OdAcc { s }
    }
    /// self + a
    #[inline]
    pub fn add(self, a: OD) -> OdAcc {
        let mut s = self.s;
        alg::acc_levels(&mut s, &a.x);
        OdAcc { s }
    }
    /// the sum as an octo-double: the nine levels added in turn with od + f64
    #[inline]
    pub fn finish(self) -> OD {
        let mut r = OD::from_f64(self.s[0]);
        for l in 1..9 {
            r = r.add_f(self.s[l]);
        }
        r
    }
}