Skip to content

Commit f5c9330

Browse files
authored
perf(rust): toFixed in machine arithmetic (#91)
It formatted every number to 1,100 decimal places and cut the text. The scaled product's rounding error comes from a fused multiply-add, which says which way the true value rounds; the exact path stays for what that cannot decide. A test holds the two equal on over 500,000 cases.
1 parent d857b24 commit f5c9330

1 file changed

Lines changed: 100 additions & 0 deletions

File tree

‎rust/crates/psychoscript/src/value.rs‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,59 @@ pub fn num_to_fixed(x: f64, digits: usize) -> String {
201201
if !x.is_finite() {
202202
return num_to_string(x);
203203
}
204+
match fixed_fast(x, digits) {
205+
Some(out) => out,
206+
None => fixed_exact(x, digits),
207+
}
208+
}
209+
210+
/// `num_to_fixed` in machine arithmetic, for a number whose digits fit in 52 bits once scaled, which is nearly every
211+
/// one a program formats. `x * 10^digits` rounds, so the part the product lost comes from a fused multiply-add, which
212+
/// gives it exactly: together they say which way the true value rounds. `None` when they are too close to tell, or
213+
/// the number is out of range, for `fixed_exact`.
214+
fn fixed_fast(x: f64, digits: usize) -> Option<String> {
215+
const POW10: [f64; 16] = [
216+
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
217+
];
218+
let a = x.abs();
219+
let scale = *POW10.get(digits)?;
220+
let p = a * scale;
221+
// Below 2^52 the product's fraction is exact; a product near the smallest numbers loses more than one rounding.
222+
if p >= 4503599627370496.0 || (a != 0.0 && a < 1e-250) {
223+
return None;
224+
}
225+
let lost = a.mul_add(scale, -p);
226+
let floor = p.floor();
227+
// The true value is `floor + 0.5 + past + lost`: it rounds up from a half on.
228+
let past = (p - floor) - 0.5;
229+
let up = if past == 0.0 {
230+
lost >= 0.0
231+
} else if past.abs() > lost.abs() {
232+
past > 0.0
233+
} else {
234+
return None;
235+
};
236+
let n = floor as u64 + up as u64;
237+
let unit = 10u64.pow(digits as u32);
238+
let mut out = String::with_capacity(24);
239+
if x < 0.0 && n != 0 {
240+
out.push('-');
241+
}
242+
write_int(&mut out, (n / unit) as i64);
243+
if digits > 0 {
244+
out.push('.');
245+
let frac = n % unit;
246+
let mut width = 10u64.pow(digits as u32 - 1);
247+
while width > 0 {
248+
out.push((b'0' + (frac / width % 10) as u8) as char);
249+
width /= 10;
250+
}
251+
}
252+
Some(out)
253+
}
254+
255+
/// `num_to_fixed` from the number's exact decimal expansion.
256+
fn fixed_exact(x: f64, digits: usize) -> String {
204257
let exact = format!("{:.1100}", x.abs());
205258
let (int, frac) = exact.split_once('.').unwrap_or((&exact, ""));
206259
let mut buf: Vec<u8> = int.bytes().chain(frac.bytes().take(digits)).collect();
@@ -539,6 +592,53 @@ impl Slot {
539592
}
540593
}
541594

595+
#[cfg(test)]
596+
mod fixed_tests {
597+
use super::*;
598+
599+
/// The fast path gives what the exact one gives, on numbers at and around ties and on a spread of others.
600+
#[test]
601+
fn fast_path_is_exact() {
602+
let mut state = 0x9e3779b97f4a7c15u64;
603+
let mut next = || {
604+
state ^= state << 13;
605+
state ^= state >> 7;
606+
state ^= state << 17;
607+
state
608+
};
609+
let mut checked = 0;
610+
let mut check = |x: f64| {
611+
for digits in 0..=20 {
612+
if let Some(fast) = fixed_fast(x, digits) {
613+
assert_eq!(fast, fixed_exact(x, digits), "{x:e} to {digits} digits");
614+
checked += 1;
615+
}
616+
}
617+
};
618+
for x in [
619+
0.0, -0.0, 0.5, 1.5, 2.5, 1.005, 1.45, 8.345, 0.000001, 1e21, 123.456, -1.5, -0.0001,
620+
1e-7,
621+
] {
622+
check(x);
623+
}
624+
for _ in 0..20_000 {
625+
let r = next();
626+
// A decimal with up to six places, where ties live, scaled across magnitudes; then any double.
627+
let decimal = (r % 2_000_000_000) as f64
628+
/ [1.0, 10.0, 100.0, 1e3, 1e4, 1e5, 1e6][(r >> 40) as usize % 7];
629+
check(decimal);
630+
check(-decimal);
631+
check(decimal + 0.5);
632+
let any = f64::from_bits(next());
633+
if any.is_finite() {
634+
check(any);
635+
}
636+
check((next() % 1_000_000) as f64 / 1e9);
637+
}
638+
assert!(checked > 500_000, "the fast path took {checked} cases");
639+
}
640+
}
641+
542642
#[cfg(test)]
543643
mod slot_tests {
544644
use super::*;

0 commit comments

Comments
 (0)