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
//! One number trait, [`Real`], over `f64`, double-double ([`DD`]), quad-double ([`QD`]) and octo-double ([`OD`]), for
//! code written once over the scalar of a series, a plane or a solver.
//!
//! [`Precision`](crate::precision::Precision) names the types of one multi-double precision, with a scalar that has
//! only `+`, `-`, `*` and `-x`, and no `f64`. `Real` is the other axis: the arithmetic of one number, with division,
//! `recip`, `sqrt`, `exp` and `ln`, correctly rounded constants (`recip_int`, `from_ratio`), the sum of products in the
//! type's accumulator, decimal parsing and printing, and the type's unit roundoff. It is a trait of its own, so that
//! an implementation of `Precision` outside the crate needs nothing new.
//!
//! Every method delegates to the type's own method and returns its result bit for bit; `f64` uses std's (`exp` and
//! `ln` are the platform's libm, as `f64::exp` and `f64::ln` are).
//!
//! # Roundoff constants
//!
//! The crates that use these types carry the unit roundoff under three conventions, none of which agrees with the
//! others. The trait keeps each under a name of its own, with the values the crates use:
//!
//! | constant | f64 | [`DD`] | [`QD`] | [`OD`] | used as |
//! |---|---|---|---|---|---|
//! | [`Real::ROUNDOFF`] | 2^-53 | 2^-106 | 1.504632769052528e-64 | 2.3e-128 | multishoot's `EPS`, negative-mass's `Num::EPS` |
//! | [`Real::UNIT`] | 2^-52 | 2^-104 | 2^-208 | 2^-416 | multisolver's `UNIT`, 2^(-52 n) for n parts |
//! | [`Real::EPSILON`] | 2^-52 | 2^-104 | 2^-209 | 2^-418 | [`QD::EPS`], [`OD::EPS`], [`DD::EPS`], `f64::EPSILON` |
//!
//! The values of `ROUNDOFF` for [`QD`] and [`OD`] are decimal literals that are not powers of two: 2^-212 is
//! 1.5193e-64 and 2^-424 is 2.3082e-128. They are kept as the crates carry them, so that nothing computed from them
//! changes.
//!
//! # The sum of products
//!
//! [`Real::cauchy`] forms a Cauchy product's coefficient `sum_(j = 0..=k) a[j] b[k - j]` through [`Real::Acc`]: `DdAcc`,
//! `QdAcc` and `OdAcc` for the multi-doubles, the scalar twins of the lanes' dot accumulators (bitwise the same per
//! lane), which keep the error terms of every product and every addition, and for `f64` the plain sum of products,
//! started at -0 so that a sum of negative zeros keeps its sign. The result is bit for bit what a lane's accumulator
//! gives (`Lane::acc` and `fin`), and not the sum of products rounded one by one, which differs in the last bits.
//!
//! ```
//! use multidouble::qd::QD;
//! use multidouble::real::Real;
//!
//! // one code over the four types
//! fn third<T: Real>() -> T {
//!     T::ONE / T::from_f64(3.0)
//! }
//! assert_eq!(third::<f64>(), 1.0 / 3.0);
//! assert!((third::<QD>() * QD::from_f64(3.0) - QD::ONE).to_f64().abs() < <QD as Real>::UNIT);
//! ```
use crate::dd::{DdAcc, DD};
use crate::od::{OdAcc, OD};
use crate::qd::{QdAcc, QD};
use crate::recip::{ratio_parts, recip_parts};
use std::fmt::Debug;
use std::ops::{Add, Div, Mul, Neg, Sub};

/// Deliberate breakage of the trait's methods for the controls of the tests (feature `mutate`).
pub mod mutate {
    /// every `from_f64` one relative unit of f64 off: the value times 1 + 2^-52
    pub const FROM_F64: u32 = 1;
    /// `Real::cauchy` as the plain sum of products in the type's own operations, not through its accumulator
    pub const PLAIN_CAUCHY: u32 = 2;
    /// `DdAcc::add_prod` without the products' error terms
    pub const DD_ACC_NO_ERRORS: u32 = 3;
    /// number of ids
    pub const N: u32 = 3;
    /// the mutations' descriptions, by id
    pub const NAMES: [&str; 4] = [
        "none",
        "real: from_f64 one unit up",
        "real: cauchy by the plain sum of products",
        "real: DdAcc without the products' error terms",
    ];

    #[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 number types of one lane: `f64`, [`DD`], [`QD`] and [`OD`], with the arithmetic that series, plane and solver
/// code needs. See the module documentation.
pub trait Real:
    Copy
    + Debug
    + Send
    + Sync
    + 'static
    + Add<Output = Self>
    + Sub<Output = Self>
    + Mul<Output = Self>
    + Div<Output = Self>
    + Neg<Output = Self>
{
    /// "f64", "dd", "qd" or "od"
    const NAME: &'static str;
    /// the number of f64 parts: 1, 2, 4 or 8, as `Precision::PARTS` for the multi-doubles
    const PARTS: usize;
    /// 0
    const ZERO: Self;
    /// 1
    const ONE: Self;
    /// the unit roundoff of the plane stepper and the series walks (see the table in the module documentation)
    const ROUNDOFF: f64;
    /// 2^(-52 n) for n parts, the scale of a rounding in this arithmetic
    const UNIT: f64;
    /// the epsilon of the error bounds: `f64::EPSILON`, `DD::EPS`, `QD::EPS`, `OD::EPS`
    const EPSILON: f64;

    /// an f64, exactly
    fn from_f64(x: f64) -> Self;
    /// rounded to f64
    fn to_f64(self) -> f64;
    /// a double-double, exactly (for f64 `DD::to_f64`: `hi + lo` rounded to nearest, a zero keeping its sign)
    fn from_dd(x: DD) -> Self;
    /// rounded to double-double (an f64 is exact)
    fn to_dd(self) -> DD;
    /// self times an f64 (exact for a power of two)
    fn mul_f(self, b: f64) -> Self;
    /// whether the leading part is finite
    fn is_finite(self) -> bool {
        self.to_f64().is_finite()
    }

    /// 1 / self in this arithmetic
    fn recip(self) -> Self;
    /// the square root, for a nonnegative argument
    fn sqrt(self) -> Self;
    /// e^self
    fn exp(self) -> Self;
    /// the natural logarithm, for a positive argument
    fn ln(self) -> Self;

    /// 1/k rounded to this precision from the exact value (`DD::recip_int`, ...); for f64 the nearest f64
    ///
    /// # Panics
    ///
    /// Unless 1 <= k < 2^60.
    fn recip_int(k: u64) -> Self;
    /// p/q rounded to this precision from the exact value (`DD::from_ratio`, ...); for f64 the nearest f64
    ///
    /// # Panics
    ///
    /// Unless 1 <= q < 2^60.
    fn from_ratio(p: i64, q: u64) -> Self;

    /// the accumulator of a sum of products: `DdAcc`, `QdAcc` and `OdAcc`, and for f64 the plain sum
    type Acc: Copy + Debug + Send + Sync;
    /// the empty sum
    fn acc_zero() -> Self::Acc;
    /// acc + a b
    fn acc_add_prod(acc: Self::Acc, a: Self, b: Self) -> Self::Acc;
    /// the sum
    fn acc_finish(acc: Self::Acc) -> Self;
    /// `sum_(j = 0..=k) a[j] b[k - j]`, the Cauchy product's coefficient, through the accumulator
    ///
    /// # Panics
    ///
    /// Unless `a` and `b` have more than k elements.
    fn cauchy(a: &[Self], b: &[Self], k: usize) -> Self {
        if mutate::on(mutate::PLAIN_CAUCHY) {
            let mut s = a[0] * b[k];
            for j in 1..=k {
                s = s + a[j] * b[k - j];
            }
            return s;
        }
        let mut acc = Self::acc_zero();
        for j in 0..=k {
            acc = Self::acc_add_prod(acc, a[j], b[k - j]);
        }
        Self::acc_finish(acc)
    }

    /// a decimal ("-1.234e-5", "3.14159...", "42") rounded to this precision, surrounding whitespace ignored, an
    /// infinity where it is out of range; for a double-double through quad-double (`QD::parse`, then rounded: a value
    /// within 2^-212 of a halfway point of the double-double may round the other way)
    ///
    /// # Errors
    ///
    /// A message when `s` is not a decimal number.
    fn parse(s: &str) -> Result<Self, String>;
    /// scientific notation with `digits` significant digits, at most 17, 33, 64 and 128 for f64, double-double,
    /// quad-double and octo-double (more are taken as those), correctly rounded from the exact value: "-1.2345e-05"
    /// style, at least two exponent digits, for every type
    fn to_sci(self, digits: usize) -> String;
}

impl Real for f64 {
    const NAME: &'static str = "f64";
    const PARTS: usize = 1;
    const ZERO: f64 = 0.0;
    const ONE: f64 = 1.0;
    const ROUNDOFF: f64 = 1.1102230246251565e-16;
    const UNIT: f64 = 2.220446049250313e-16;
    const EPSILON: f64 = f64::EPSILON;

    #[inline(always)]
    fn from_f64(x: f64) -> f64 {
        if mutate::on(mutate::FROM_F64) {
            x * (1.0 + f64::EPSILON)
        } else {
            x
        }
    }
    #[inline(always)]
    fn to_f64(self) -> f64 {
        self
    }
    #[inline(always)]
    fn from_dd(x: DD) -> f64 {
        x.to_f64()
    }
    #[inline(always)]
    fn to_dd(self) -> DD {
        DD::from_f64(self)
    }
    #[inline(always)]
    fn mul_f(self, b: f64) -> f64 {
        self * b
    }
    #[inline(always)]
    fn recip(self) -> f64 {
        1.0 / self
    }
    #[inline(always)]
    fn sqrt(self) -> f64 {
        f64::sqrt(self)
    }
    fn exp(self) -> f64 {
        f64::exp(self)
    }
    fn ln(self) -> f64 {
        f64::ln(self)
    }
    fn recip_int(k: u64) -> f64 {
        recip_parts(k)[0]
    }
    fn from_ratio(p: i64, q: u64) -> f64 {
        ratio_parts(p, q)[0]
    }
    type Acc = f64;
    /// -0: adding it to anything gives that thing back, a zero's sign included, as the plain sum starts at its first
    /// product
    #[inline(always)]
    fn acc_zero() -> f64 {
        -0.0
    }
    #[inline(always)]
    fn acc_add_prod(acc: f64, a: f64, b: f64) -> f64 {
        acc + a * b
    }
    #[inline(always)]
    fn acc_finish(acc: f64) -> f64 {
        acc
    }
    fn parse(s: &str) -> Result<f64, String> {
        s.trim().parse::<f64>().map_err(|e| format!("{e}"))
    }
    fn to_sci(self, digits: usize) -> String {
        QD::from_f64(self).to_sci(digits.min(17))
    }
}

macro_rules! real_multidouble {
    ($t:ty, $name:expr, $parts:expr, $roundoff:expr, $unit:expr, $eps:expr, $acc:ty, $from_dd:expr, $to_dd:expr,
     $parse:expr, $sci:expr) => {
        impl Real for $t {
            const NAME: &'static str = $name;
            const PARTS: usize = $parts;
            const ZERO: $t = <$t>::ZERO;
            const ONE: $t = <$t>::ONE;
            const ROUNDOFF: f64 = $roundoff;
            const UNIT: f64 = $unit;
            const EPSILON: f64 = $eps;

            #[inline(always)]
            fn from_f64(x: f64) -> $t {
                let r = <$t>::from_f64(x);
                if mutate::on(mutate::FROM_F64) {
                    r.mul_f(1.0 + f64::EPSILON)
                } else {
                    r
                }
            }
            #[inline(always)]
            fn to_f64(self) -> f64 {
                <$t>::to_f64(self)
            }
            #[inline(always)]
            fn from_dd(x: DD) -> $t {
                ($from_dd)(x)
            }
            #[inline(always)]
            fn to_dd(self) -> DD {
                ($to_dd)(self)
            }
            #[inline(always)]
            fn mul_f(self, b: f64) -> $t {
                <$t>::mul_f(self, b)
            }
            #[inline(always)]
            fn recip(self) -> $t {
                <$t>::recip(self)
            }
            #[inline(always)]
            fn sqrt(self) -> $t {
                <$t>::sqrt(self)
            }
            fn exp(self) -> $t {
                <$t>::exp(self)
            }
            fn ln(self) -> $t {
                <$t>::ln(self)
            }
            fn recip_int(k: u64) -> $t {
                <$t>::recip_int(k)
            }
            fn from_ratio(p: i64, q: u64) -> $t {
                <$t>::from_ratio(p, q)
            }
            type Acc = $acc;
            #[inline(always)]
            fn acc_zero() -> $acc {
                <$acc>::zero()
            }
            #[inline(always)]
            fn acc_add_prod(acc: $acc, a: $t, b: $t) -> $acc {
                acc.add_prod(a, b)
            }
            #[inline(always)]
            fn acc_finish(acc: $acc) -> $t {
                acc.finish()
            }
            fn parse(s: &str) -> Result<$t, String> {
                ($parse)(s)
            }
            fn to_sci(self, digits: usize) -> String {
                ($sci)(self, digits)
            }
        }
    };
}

/// a parsed quad-double as a double-double: rounded, and a value out of range (an infinite leading part, which
/// `QD::to_dd` would give a NaN low part) as the infinity with a zero low part
fn dd_of_qd(q: QD) -> DD {
    if q.x[0].is_finite() {
        q.to_dd()
    } else {
        DD { hi: q.x[0], lo: 0.0 }
    }
}

real_multidouble!(
    DD,
    "dd",
    2,
    1.232595164407831e-32,
    4.930380657631324e-32,
    DD::EPS,
    DdAcc,
    |x: DD| x,
    |x: DD| x,
    |s: &str| QD::parse(s).map(dd_of_qd),
    |x: DD, digits: usize| QD::from_dd(x).to_sci(digits.min(33))
);
real_multidouble!(
    QD,
    "qd",
    4,
    1.504632769052528e-64,
    2.4308653429145085e-63,
    QD::EPS,
    QdAcc,
    QD::from_dd,
    QD::to_dd,
    QD::parse,
    |x: QD, digits: usize| x.to_sci(digits.min(64))
);
real_multidouble!(
    OD,
    "od",
    8,
    2.3e-128,
    5.909106315382871e-126,
    OD::EPS,
    OdAcc,
    OD::from_dd,
    OD::to_dd,
    OD::parse,
    |x: OD, digits: usize| x.to_sci(digits.min(128))
);