use crate::dd::two_sum;
use std::cmp::Ordering;
pub mod mutate {
pub const AS_GIVEN: u32 = 1;
pub const NO_FALLBACK: u32 = 2;
pub const NO_BALANCE: u32 = 3;
pub const LANES_KEEP_OVERFLOW: u32 = 4;
pub const N: u32 = 4;
pub const NAMES: [&str; 5] = [
"none",
"constructors: parts renormalized as given",
"constructors: no fallback",
"constructors: no retry after an overflow",
"constructors: lanes keep an overflow",
];
#[cfg(feature = "mutate")]
thread_local!(static ID: std::cell::Cell<u32> = const { std::cell::Cell::new(0) });
#[cfg(feature = "mutate")]
pub fn set(id: u32) {
ID.with(|m| m.set(id));
}
#[cfg(feature = "mutate")]
#[inline(always)]
pub fn on(id: u32) -> bool {
ID.with(|m| m.get() == id)
}
#[cfg(not(feature = "mutate"))]
#[inline(always)]
pub fn on(_id: u32) -> bool {
false
}
}
#[inline(always)]
pub(crate) fn by_magnitude<const N: usize>(mut x: [f64; N]) -> [f64; N] {
if (0..N - 1).all(|k| x[k].abs() >= x[k + 1].abs()) {
return x;
}
for i in 1..N {
let mut j = i;
while j > 0 && x[j - 1].abs().total_cmp(&x[j].abs()) == Ordering::Less {
x.swap(j - 1, j);
j -= 1;
}
}
x
}
#[inline(always)]
pub(crate) fn ulp(a: f64) -> f64 {
f64::from_bits(a.to_bits() & 0x7ff0_0000_0000_0000).max(f64::MIN_POSITIVE) * f64::EPSILON
}
#[inline(always)]
pub(crate) fn on_ladder<const N: usize>(x: &[f64; N]) -> bool {
let quick = (0..N - 1).fold(true, |m, k| m & (x[k + 1].abs() * 2f64.powi(53) <= x[k].abs()));
quick || (0..N - 1).all(|k| x[k + 1] == 0.0 || (x[k] != 0.0 && x[k + 1].abs() <= ulp(x[k])))
}
#[cold]
#[inline(never)]
pub(crate) fn expansion_sum<const N: usize>(x: [f64; N]) -> [f64; N] {
let r = grow_and_compress(x, false);
if r.iter().all(|p| p.is_finite()) || mutate::on(mutate::NO_BALANCE) {
r
} else {
grow_and_compress(x, true)
}
}
#[inline(always)]
fn grow_and_compress<const N: usize>(x: [f64; N], balanced: bool) -> [f64; N] {
let mut e = [0.0f64; N];
let mut used = [false; N];
for m in 0..N {
let next = if balanced {
let s = if m == 0 { 0.0 } else { e[m - 1] };
(0..N)
.find(|&i| !used[i] && ((s > 0.0 && x[i] < 0.0) || (s < 0.0 && x[i] > 0.0)))
.or_else(|| (0..N).find(|&i| !used[i]))
.unwrap_or(m)
} else {
m
};
used[next] = true;
let mut q = x[next];
for c in e.iter_mut().take(m) {
let (s, h) = two_sum(q, *c);
*c = h;
q = s;
}
e[m] = q;
}
let mut out = [0.0f64; N];
let mut k = 0;
let mut acc = e[N - 1];
for i in (0..N - 1).rev() {
let (t, err) = two_sum(acc, e[i]);
if err != 0.0 {
out[k] = t;
k += 1;
acc = err;
} else {
acc = t;
}
}
out[k] = acc;
out
}
#[inline(always)]
pub(crate) fn exact_sum<const N: usize>(
x: [f64; N],
renorm: impl FnOnce([f64; N]) -> [f64; N],
renorm_exact: impl FnOnce([f64; N]) -> [f64; N],
) -> [f64; N] {
if on_ladder(&x) {
return renorm(x);
}
let c = by_magnitude(x);
let r = renorm_exact(c);
let finite = c.iter().all(|p| p.is_finite());
if !finite || (r[0].is_finite() && on_ladder(&r)) || mutate::on(mutate::NO_FALLBACK) {
r
} else {
expansion_sum(c)
}
}
#[cfg(test)]
mod tests {
use crate::dd::{quick_two_sum, DD};
use crate::exact::Dy;
use crate::od::{renorm_scalar, OD};
use crate::qd::{renorm4, QD};
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
fn dd(&mut self, e: i32) -> DD {
let x = 2f64.powi((self.next() % (2 * e as u64 + 1)) as i32 - e)
* (1.0 + (self.next() >> 11) as f64 / 2f64.powi(53));
let s = if self.next() & 1 == 0 { 1.0 } else { -1.0 };
let lo = ((self.next() >> 11) as f64 / 2f64.powi(53) - 0.5) * x * f64::EPSILON;
DD::new(s * x, lo)
}
}
fn bits<const N: usize>(x: [f64; N]) -> [u64; N] {
x.map(f64::to_bits)
}
fn laddered<const N: usize>(r: &mut Rng) -> [f64; N] {
let mut x = [0.0; N];
x[0] = 2f64.powi((r.next() % 2023) as i32 - 1022) * (1.0 + (r.next() >> 11) as f64 / 2f64.powi(53));
for k in 1..N {
let m = if r.next().is_multiple_of(8) {
1.0
} else {
(r.next() >> 11) as f64 / 2f64.powi(53)
};
let s = if r.next() & 1 == 0 { 1.0 } else { -1.0 };
x[k] = if x[k - 1] == 0.0 {
0.0
} else {
s * m * super::ulp(x[k - 1])
};
}
x
}
fn exact_on_ladder(c: &[f64], r: &[f64]) -> bool {
let ulp = |x: f64| {
let e = ((x.to_bits() >> 52) & 0x7ff) as i64;
Dy::from_f64(1.0).ldexp(if e == 0 { -1074 } else { e - 1075 })
};
Dy::sum(c).sub(&Dy::sum(r)).is_zero()
&& (0..r.len() - 1).all(|k| {
if r[k] == 0.0 {
r[k + 1] == 0.0
} else {
Dy::from_f64(r[k + 1]).cmp_abs(&ulp(r[k])) != std::cmp::Ordering::Greater
}
})
}
#[test]
fn ladder_parts_renormalize_exactly_onto_the_ladder() {
let mut r = Rng(2);
let (mut reversed_fail, n) = (0, 20000);
for _ in 0..n {
let q: [f64; 4] = laddered(&mut r);
assert!(super::on_ladder(&q), "{q:?}");
let rq = renorm4(q[0], q[1], q[2], q[3]);
assert!(exact_on_ladder(&q, &rq), "{q:?} gives {rq:?}");
assert_eq!(bits(QD::new(q[0], q[1], q[2], q[3]).x), bits(rq));
let o: [f64; 8] = laddered(&mut r);
assert!(super::on_ladder(&o), "{o:?}");
let ro = renorm_scalar(o);
assert!(exact_on_ladder(&o, &ro), "{o:?} gives {ro:?}");
assert_eq!(bits(OD::new(o).x), bits(ro));
let p = [q[3], q[2], q[1], q[0]];
reversed_fail += !exact_on_ladder(&p, &renorm4(p[0], p[1], p[2], p[3])) as usize;
}
println!("reversed parts: {reversed_fail} of {n} fail");
assert!(reversed_fail > n / 10, "control: {reversed_fail} of {n}");
}
#[test]
fn ordered_parts_keep_their_bits() {
let mut r = Rng(1);
let (mut permuted_differ, n) = (0, 20000);
for i in 0..n {
let (a, b, c) = (r.dd(30), r.dd(30), r.dd(300));
let d = match i % 3 {
0 => a * b + c,
1 => a / b,
_ => DD::new(a.hi, 0.0),
};
let (h, l) = quick_two_sum(d.hi, d.lo);
let e = DD::new(d.hi, d.lo);
assert_eq!(bits([e.hi, e.lo]), bits([h, l + 0.0]), "{d:?}");
let q = match i % 3 {
0 => QD::from_dd(a) * QD::from_dd(b) + QD::from_dd(c),
1 => QD::from_dd(a) / QD::from_dd(b),
_ => QD::from_dd(a) + QD::from_dd(c),
};
let x = q.x;
assert_eq!(
bits(QD::new(x[0], x[1], x[2], x[3]).x),
bits(renorm4(x[0], x[1], x[2], x[3])),
"{x:?}"
);
let o = match i % 3 {
0 => OD::from_qd(q) * OD::from_dd(c) + OD::from_dd(a),
1 => OD::from_qd(q) / OD::from_dd(b),
_ => OD::from_qd(q) - OD::from_dd(a),
};
assert_eq!(bits(OD::new(o.x).x), bits(renorm_scalar(o.x)), "{:?}", o.x);
let p = [o.x[3], o.x[0], o.x[6], o.x[1], o.x[7], o.x[2], o.x[5], o.x[4]];
permuted_differ += (bits(OD::new(p).x) != bits(renorm_scalar(p))) as usize;
}
println!("permuted parts: {permuted_differ} of {n} differ from the renormalization as given");
assert!(permuted_differ > n / 10, "control: {permuted_differ} of {n}");
}
}