Skip to main content

unityrs_core/
pyfloat.rs

1//! Python's `repr` of a float, which the dump's `str()` of an index value
2//! and the cutter's JSON (`json.dumps` writes a float as its `repr`) both
3//! give.
4
5use std::fmt::Write as _;
6
7/// `repr(float)`: the shortest digits that round-trip, positional when the
8/// decimal exponent is in -4..16, else `d.ddde+XX` (`PyOS_double_to_string`
9/// with mode `'r'`); `nan`, `inf` and `-inf`.
10///
11/// Of the shortest digits that round-trip, Python's `repr` (David Gay's
12/// `dtoa` in mode 0) gives those nearest the double, and of two equally
13/// near the even one. Rust's shortest `{:e}` breaks that tie upwards
14/// (`1551563132437320.25`: Python `…320.2`, `{:e}` `…320.3`; review round
15/// 8), so its length only is taken: the double rounded to that many digits
16/// (`{:.*e}`: exact, ties to even) is the nearest of that length, and is
17/// Python's when it round-trips. When it does not (a power of two, whose
18/// doubles that round-trip reach half as far below it as above, can have
19/// its nearest digits below them), `{:e}`'s digits are kept: they are then
20/// the nearest that round-trip, as Python's are, with no tie between two
21/// (`crates/unityrs-dump/tests/fixtures/dump/index.json` "str" holds ties
22/// and such powers, which the tests here repeat).
23#[must_use]
24pub fn py_float_repr(x: f64) -> String {
25    if x.is_nan() {
26        return "nan".to_owned();
27    }
28    if x.is_infinite() {
29        return if x > 0.0 { "inf" } else { "-inf" }.to_owned();
30    }
31    // `{:e}` gives the shortest round-trip digits: "-1.2345e-7".
32    let mut sci = format!("{x:e}");
33    let len = sci
34        .split('e')
35        .next()
36        .map_or(0, |m| m.bytes().filter(u8::is_ascii_digit).count());
37    if len > 1 {
38        let nearest = format!("{:.*e}", len - 1, x);
39        if nearest.parse::<f64>() == Ok(x) {
40            sci = nearest;
41        }
42    }
43    let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
44    let exp: i32 = exp.parse().unwrap_or(0);
45    let (neg, mant) = mant.strip_prefix('-').map_or((false, mant), |m| (true, m));
46    let digits: String = mant.chars().filter(char::is_ascii_digit).collect();
47    let mut out = String::new();
48    if neg {
49        out.push('-');
50    }
51    if (-4..16).contains(&exp) {
52        let point = exp + 1; // digits before the decimal point
53        if point <= 0 {
54            out.push_str("0.");
55            for _ in 0..-point {
56                out.push('0');
57            }
58            out.push_str(&digits);
59        } else {
60            let p = usize::try_from(point).unwrap_or(0);
61            if digits.len() <= p {
62                out.push_str(&digits);
63                for _ in digits.len()..p {
64                    out.push('0');
65                }
66                out.push_str(".0");
67            } else {
68                out.push_str(digits.get(..p).unwrap_or_default());
69                out.push('.');
70                out.push_str(digits.get(p..).unwrap_or_default());
71            }
72        }
73    } else {
74        out.push_str(digits.get(..1).unwrap_or_default());
75        if digits.len() > 1 {
76            out.push('.');
77            out.push_str(digits.get(1..).unwrap_or_default());
78        }
79        out.push('e');
80        out.push(if exp < 0 { '-' } else { '+' });
81        let _ = write!(out, "{:02}", exp.unsigned_abs());
82    }
83    out
84}
85
86#[cfg(test)]
87mod tests {
88    use super::py_float_repr;
89
90    #[test]
91    fn floats_repr_as_python() {
92        // CPython 3.11's `repr`; the ties and the powers of two are the dump
93        // fixture's (`index.json` "str").
94        for (x, s) in [
95            (4100.0, "4100.0"),
96            (1e16, "1e+16"),
97            (0.0001, "0.0001"),
98            (0.00001, "1e-05"),
99            (-2.5, "-2.5"),
100            (0.0, "0.0"),
101            (-0.0, "-0.0"),
102            (1.5e300, "1.5e+300"),
103            (f64::NAN, "nan"),
104            (f64::INFINITY, "inf"),
105            (f64::NEG_INFINITY, "-inf"),
106            (5e-324, "5e-324"),
107        ] {
108            assert_eq!(py_float_repr(x), s, "{x:e}");
109        }
110    }
111
112    #[test]
113    fn ties_go_to_the_even_digits_and_powers_of_two_to_the_nearest() {
114        // Doubles written exactly: two shortest digit strings equally near,
115        // where CPython takes the even one (`{:e}` broke the tie upwards),
116        // and powers of two, whose nearest shortest digits can fail to read
117        // back (the dump fixture's `index.json` "str" cases).
118        for (exact, want) in [
119            ("1234567890123456.0", "1234567890123456.0"),
120            ("1551563132437320.25", "1551563132437320.2"),
121            ("-1551563132437320.25", "-1551563132437320.2"),
122            ("79686618578806.625", "79686618578806.62"),
123            ("1125899906842624.25", "1125899906842624.2"),
124            ("22620844907483.3125", "22620844907483.312"),
125            ("2.98023223876953125e-8", "2.9802322387695312e-08"),
126            ("5.9604644775390625e-7", "5.960464477539062e-07"),
127            ("9007199254740992.0", "9007199254740992.0"),
128        ] {
129            let x: f64 = exact.parse().unwrap();
130            assert_eq!(py_float_repr(x), want, "{exact}");
131        }
132    }
133}