miri/
math.rs

1use rand::Rng as _;
2use rustc_apfloat::Float as _;
3use rustc_apfloat::ieee::IeeeFloat;
4
5/// Disturbes a floating-point result by a relative error in the range (-2^scale, 2^scale).
6///
7/// For a 2^N ULP error, you can use an `err_scale` of `-(F::PRECISION - 1 - N)`.
8/// In other words, a 1 ULP (absolute) error is the same as a `2^-(F::PRECISION-1)` relative error.
9/// (Subtracting 1 compensates for the integer bit.)
10pub(crate) fn apply_random_float_error<F: rustc_apfloat::Float>(
11    ecx: &mut crate::MiriInterpCx<'_>,
12    val: F,
13    err_scale: i32,
14) -> F {
15    let rng = ecx.machine.rng.get_mut();
16    // Generate a random integer in the range [0, 2^PREC).
17    // (When read as binary, the position of the first `1` determines the exponent,
18    // and the remaining bits fill the mantissa. `PREC` is one plus the size of the mantissa,
19    // so this all works out.)
20    let r = F::from_u128(rng.random_range(0..(1 << F::PRECISION))).value;
21    // Multiply this with 2^(scale - PREC). The result is between 0 and
22    // 2^PREC * 2^(scale - PREC) = 2^scale.
23    let err = r.scalbn(err_scale.strict_sub(F::PRECISION.try_into().unwrap()));
24    // give it a random sign
25    let err = if rng.random() { -err } else { err };
26    // multiple the value with (1+err)
27    (val * (F::from_u128(1).value + err).value).value
28}
29
30pub(crate) fn sqrt<S: rustc_apfloat::ieee::Semantics>(x: IeeeFloat<S>) -> IeeeFloat<S> {
31    match x.category() {
32        // preserve zero sign
33        rustc_apfloat::Category::Zero => x,
34        // propagate NaN
35        rustc_apfloat::Category::NaN => x,
36        // sqrt of negative number is NaN
37        _ if x.is_negative() => IeeeFloat::NAN,
38        // sqrt(∞) = ∞
39        rustc_apfloat::Category::Infinity => IeeeFloat::INFINITY,
40        rustc_apfloat::Category::Normal => {
41            // Floating point precision, excluding the integer bit
42            let prec = i32::try_from(S::PRECISION).unwrap() - 1;
43
44            // x = 2^(exp - prec) * mant
45            // where mant is an integer with prec+1 bits
46            // mant is a u128, which should be large enough for the largest prec (112 for f128)
47            let mut exp = x.ilogb();
48            let mut mant = x.scalbn(prec - exp).to_u128(128).value;
49
50            if exp % 2 != 0 {
51                // Make exponent even, so it can be divided by 2
52                exp -= 1;
53                mant <<= 1;
54            }
55
56            // Bit-by-bit (base-2 digit-by-digit) sqrt of mant.
57            // mant is treated here as a fixed point number with prec fractional bits.
58            // mant will be shifted left by one bit to have an extra fractional bit, which
59            // will be used to determine the rounding direction.
60
61            // res is the truncated sqrt of mant, where one bit is added at each iteration.
62            let mut res = 0u128;
63            // rem is the remainder with the current res
64            // rem_i = 2^i * ((mant<<1) - res_i^2)
65            // starting with res = 0, rem = mant<<1
66            let mut rem = mant << 1;
67            // s_i = 2*res_i
68            let mut s = 0u128;
69            // d is used to iterate over bits, from high to low (d_i = 2^(-i))
70            let mut d = 1u128 << (prec + 1);
71
72            // For iteration j=i+1, we need to find largest b_j = 0 or 1 such that
73            //  (res_i + b_j * 2^(-j))^2 <= mant<<1
74            // Expanding (a + b)^2 = a^2 + b^2 + 2*a*b:
75            //  res_i^2 + (b_j * 2^(-j))^2 + 2 * res_i * b_j * 2^(-j) <= mant<<1
76            // And rearranging the terms:
77            //  b_j^2 * 2^(-j) + 2 * res_i * b_j <= 2^j * (mant<<1 - res_i^2)
78            //  b_j^2 * 2^(-j) + 2 * res_i * b_j <= rem_i
79
80            while d != 0 {
81                // Probe b_j^2 * 2^(-j) + 2 * res_i * b_j <= rem_i with b_j = 1:
82                // t = 2*res_i + 2^(-j)
83                let t = s + d;
84                if rem >= t {
85                    // b_j should be 1, so make res_j = res_i + 2^(-j) and adjust rem
86                    res += d;
87                    s += d + d;
88                    rem -= t;
89                }
90                // Adjust rem for next iteration
91                rem <<= 1;
92                // Shift iterator
93                d >>= 1;
94            }
95
96            // Remove extra fractional bit from result, rounding to nearest.
97            // If the last bit is 0, then the nearest neighbor is definitely the lower one.
98            // If the last bit is 1, it sounds like this may either be a tie (if there's
99            // infinitely many 0s after this 1), or the nearest neighbor is the upper one.
100            // However, since square roots are either exact or irrational, and an exact root
101            // would lead to the last "extra" bit being 0, we can exclude a tie in this case.
102            // We therefore always round up if the last bit is 1. When the last bit is 0,
103            // adding 1 will not do anything since the shift will discard it.
104            res = (res + 1) >> 1;
105
106            // Build resulting value with res as mantissa and exp/2 as exponent
107            IeeeFloat::from_u128(res).value.scalbn(exp / 2 - prec)
108        }
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, QuadS, SingleS};
115
116    use super::sqrt;
117
118    #[test]
119    fn test_sqrt() {
120        #[track_caller]
121        fn test<S: rustc_apfloat::ieee::Semantics>(x: &str, expected: &str) {
122            let x: IeeeFloat<S> = x.parse().unwrap();
123            let expected: IeeeFloat<S> = expected.parse().unwrap();
124            let result = sqrt(x);
125            assert_eq!(result, expected);
126        }
127
128        fn exact_tests<S: rustc_apfloat::ieee::Semantics>() {
129            test::<S>("0", "0");
130            test::<S>("1", "1");
131            test::<S>("1.5625", "1.25");
132            test::<S>("2.25", "1.5");
133            test::<S>("4", "2");
134            test::<S>("5.0625", "2.25");
135            test::<S>("9", "3");
136            test::<S>("16", "4");
137            test::<S>("25", "5");
138            test::<S>("36", "6");
139            test::<S>("49", "7");
140            test::<S>("64", "8");
141            test::<S>("81", "9");
142            test::<S>("100", "10");
143
144            test::<S>("0.5625", "0.75");
145            test::<S>("0.25", "0.5");
146            test::<S>("0.0625", "0.25");
147            test::<S>("0.00390625", "0.0625");
148        }
149
150        exact_tests::<HalfS>();
151        exact_tests::<SingleS>();
152        exact_tests::<DoubleS>();
153        exact_tests::<QuadS>();
154
155        test::<SingleS>("2", "1.4142135");
156        test::<DoubleS>("2", "1.4142135623730951");
157
158        test::<SingleS>("1.1", "1.0488088");
159        test::<DoubleS>("1.1", "1.0488088481701516");
160
161        test::<SingleS>("2.2", "1.4832398");
162        test::<DoubleS>("2.2", "1.4832396974191326");
163
164        test::<SingleS>("1.22101e-40", "1.10499205e-20");
165        test::<DoubleS>("1.22101e-310", "1.1049932126488395e-155");
166
167        test::<SingleS>("3.4028235e38", "1.8446743e19");
168        test::<DoubleS>("1.7976931348623157e308", "1.3407807929942596e154");
169    }
170}