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;
trait Bits: Real {
fn bits(self) -> Vec<u64>;
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)
}
}
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
}
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
}
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()
}
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());
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"]
);
}
trait PartsF64: Bits {
fn bits_f64(self) -> Vec<f64> {
self.bits().into_iter().map(f64::from_bits).collect()
}
}
impl<T: Bits> PartsF64 for T {}
#[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}"
);
}
}
#[derive(Clone, Copy)]
struct Case<T> {
x: T,
y: T,
f: f64,
k: u64,
p: i64,
q: u64,
}
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)
}
};
}
trait Shape: Bits {
fn abs_part(self) -> Self {
if self.to_f64() < 0.0 {
-self
} else {
self
}
}
fn small(self) -> Self {
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 {}
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);
}
}
#[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}"
);
}
}
#[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}");
}
}
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()
}
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);
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);
}
#[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]));
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}");
}
}
#[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");
}
#[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);
}
}
fn f64_sum_differs(start: f64) -> usize {
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);
}
#[test]
fn control_positive_zero_start_fails() {
assert!(f64_sum_differs(0.0) > 0);
}
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}");
}
}
#[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}");
}
}
const PI: &str = "3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196";
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..])
}
fn pi_digits<T: Real>() -> usize {
match T::PARTS {
1 => 15,
2 => 30,
4 => 60,
_ => 120,
}
}
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));
}
#[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>();
}
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)
}
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)
}
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);
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()]
}
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())
}
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);
}
#[test]
fn control_shifted_decimals_fail_dd_parse() {
assert!(dd_parse_misreads(1_000_000_000) > 0);
}
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));
}
#[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));
}