]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/dec2flt/algorithm.rs
Rollup merge of #76758 - adamlesinski:clone_clock, r=tmandry
[rust.git] / library / core / src / num / dec2flt / algorithm.rs
1 //! The various algorithms from the paper.
2
3 use crate::cmp::min;
4 use crate::cmp::Ordering::{Equal, Greater, Less};
5 use crate::num::dec2flt::num::{self, Big};
6 use crate::num::dec2flt::rawfp::{self, fp_to_float, next_float, prev_float, RawFloat, Unpacked};
7 use crate::num::dec2flt::table;
8 use crate::num::diy_float::Fp;
9
10 /// Number of significand bits in Fp
11 const P: u32 = 64;
12
13 // We simply store the best approximation for *all* exponents, so the variable "h" and the
14 // associated conditions can be omitted. This trades performance for a couple kilobytes of space.
15
16 fn power_of_ten(e: i16) -> Fp {
17     assert!(e >= table::MIN_E);
18     let i = e - table::MIN_E;
19     let sig = table::POWERS.0[i as usize];
20     let exp = table::POWERS.1[i as usize];
21     Fp { f: sig, e: exp }
22 }
23
24 // In most architectures, floating point operations have an explicit bit size, therefore the
25 // precision of the computation is determined on a per-operation basis.
26 #[cfg(any(not(target_arch = "x86"), target_feature = "sse2"))]
27 mod fpu_precision {
28     pub fn set_precision<T>() {}
29 }
30
31 // On x86, the x87 FPU is used for float operations if the SSE/SSE2 extensions are not available.
32 // The x87 FPU operates with 80 bits of precision by default, which means that operations will
33 // round to 80 bits causing double rounding to happen when values are eventually represented as
34 // 32/64 bit float values. To overcome this, the FPU control word can be set so that the
35 // computations are performed in the desired precision.
36 #[cfg(all(target_arch = "x86", not(target_feature = "sse2")))]
37 mod fpu_precision {
38     use crate::mem::size_of;
39
40     /// A structure used to preserve the original value of the FPU control word, so that it can be
41     /// restored when the structure is dropped.
42     ///
43     /// The x87 FPU is a 16-bits register whose fields are as follows:
44     ///
45     /// | 12-15 | 10-11 | 8-9 | 6-7 |  5 |  4 |  3 |  2 |  1 |  0 |
46     /// |------:|------:|----:|----:|---:|---:|---:|---:|---:|---:|
47     /// |       | RC    | PC  |     | PM | UM | OM | ZM | DM | IM |
48     ///
49     /// The documentation for all of the fields is available in the IA-32 Architectures Software
50     /// Developer's Manual (Volume 1).
51     ///
52     /// The only field which is relevant for the following code is PC, Precision Control. This
53     /// field determines the precision of the operations performed by the  FPU. It can be set to:
54     ///  - 0b00, single precision i.e., 32-bits
55     ///  - 0b10, double precision i.e., 64-bits
56     ///  - 0b11, double extended precision i.e., 80-bits (default state)
57     /// The 0b01 value is reserved and should not be used.
58     pub struct FPUControlWord(u16);
59
60     fn set_cw(cw: u16) {
61         // SAFETY: the `fldcw` instruction has been audited to be able to work correctly with
62         // any `u16`
63         unsafe {
64             asm!(
65                 "fldcw ({})",
66                 in(reg) &cw,
67                 // FIXME: We are using ATT syntax to support LLVM 8 and LLVM 9.
68                 options(att_syntax, nostack),
69             )
70         }
71     }
72
73     /// Sets the precision field of the FPU to `T` and returns a `FPUControlWord`.
74     pub fn set_precision<T>() -> FPUControlWord {
75         let mut cw = 0_u16;
76
77         // Compute the value for the Precision Control field that is appropriate for `T`.
78         let cw_precision = match size_of::<T>() {
79             4 => 0x0000, // 32 bits
80             8 => 0x0200, // 64 bits
81             _ => 0x0300, // default, 80 bits
82         };
83
84         // Get the original value of the control word to restore it later, when the
85         // `FPUControlWord` structure is dropped
86         // SAFETY: the `fnstcw` instruction has been audited to be able to work correctly with
87         // any `u16`
88         unsafe {
89             asm!(
90                 "fnstcw ({})",
91                 in(reg) &mut cw,
92                 // FIXME: We are using ATT syntax to support LLVM 8 and LLVM 9.
93                 options(att_syntax, nostack),
94             )
95         }
96
97         // Set the control word to the desired precision. This is achieved by masking away the old
98         // precision (bits 8 and 9, 0x300) and replacing it with the precision flag computed above.
99         set_cw((cw & 0xFCFF) | cw_precision);
100
101         FPUControlWord(cw)
102     }
103
104     impl Drop for FPUControlWord {
105         fn drop(&mut self) {
106             set_cw(self.0)
107         }
108     }
109 }
110
111 /// The fast path of Bellerophon using machine-sized integers and floats.
112 ///
113 /// This is extracted into a separate function so that it can be attempted before constructing
114 /// a bignum.
115 pub fn fast_path<T: RawFloat>(integral: &[u8], fractional: &[u8], e: i64) -> Option<T> {
116     let num_digits = integral.len() + fractional.len();
117     // log_10(f64::MAX_SIG) ~ 15.95. We compare the exact value to MAX_SIG near the end,
118     // this is just a quick, cheap rejection (and also frees the rest of the code from
119     // worrying about underflow).
120     if num_digits > 16 {
121         return None;
122     }
123     if e.abs() >= T::CEIL_LOG5_OF_MAX_SIG as i64 {
124         return None;
125     }
126     let f = num::from_str_unchecked(integral.iter().chain(fractional.iter()));
127     if f > T::MAX_SIG {
128         return None;
129     }
130
131     // The fast path crucially depends on arithmetic being rounded to the correct number of bits
132     // without any intermediate rounding. On x86 (without SSE or SSE2) this requires the precision
133     // of the x87 FPU stack to be changed so that it directly rounds to 64/32 bit.
134     // The `set_precision` function takes care of setting the precision on architectures which
135     // require setting it by changing the global state (like the control word of the x87 FPU).
136     let _cw = fpu_precision::set_precision::<T>();
137
138     // The case e < 0 cannot be folded into the other branch. Negative powers result in
139     // a repeating fractional part in binary, which are rounded, which causes real
140     // (and occasionally quite significant!) errors in the final result.
141     if e >= 0 {
142         Some(T::from_int(f) * T::short_fast_pow10(e as usize))
143     } else {
144         Some(T::from_int(f) / T::short_fast_pow10(e.abs() as usize))
145     }
146 }
147
148 /// Algorithm Bellerophon is trivial code justified by non-trivial numeric analysis.
149 ///
150 /// It rounds ``f`` to a float with 64 bit significand and multiplies it by the best approximation
151 /// of `10^e` (in the same floating point format). This is often enough to get the correct result.
152 /// However, when the result is close to halfway between two adjacent (ordinary) floats, the
153 /// compound rounding error from multiplying two approximation means the result may be off by a
154 /// few bits. When this happens, the iterative Algorithm R fixes things up.
155 ///
156 /// The hand-wavy "close to halfway" is made precise by the numeric analysis in the paper.
157 /// In the words of Clinger:
158 ///
159 /// > Slop, expressed in units of the least significant bit, is an inclusive bound for the error
160 /// > accumulated during the floating point calculation of the approximation to f * 10^e. (Slop is
161 /// > not a bound for the true error, but bounds the difference between the approximation z and
162 /// > the best possible approximation that uses p bits of significand.)
163 pub fn bellerophon<T: RawFloat>(f: &Big, e: i16) -> T {
164     let slop = if f <= &Big::from_u64(T::MAX_SIG) {
165         // The cases abs(e) < log5(2^N) are in fast_path()
166         if e >= 0 { 0 } else { 3 }
167     } else {
168         if e >= 0 { 1 } else { 4 }
169     };
170     let z = rawfp::big_to_fp(f).mul(&power_of_ten(e)).normalize();
171     let exp_p_n = 1 << (P - T::SIG_BITS as u32);
172     let lowbits: i64 = (z.f % exp_p_n) as i64;
173     // Is the slop large enough to make a difference when
174     // rounding to n bits?
175     if (lowbits - exp_p_n as i64 / 2).abs() <= slop {
176         algorithm_r(f, e, fp_to_float(z))
177     } else {
178         fp_to_float(z)
179     }
180 }
181
182 /// An iterative algorithm that improves a floating point approximation of `f * 10^e`.
183 ///
184 /// Each iteration gets one unit in the last place closer, which of course takes terribly long to
185 /// converge if `z0` is even mildly off. Luckily, when used as fallback for Bellerophon, the
186 /// starting approximation is off by at most one ULP.
187 fn algorithm_r<T: RawFloat>(f: &Big, e: i16, z0: T) -> T {
188     let mut z = z0;
189     loop {
190         let raw = z.unpack();
191         let (m, k) = (raw.sig, raw.k);
192         let mut x = f.clone();
193         let mut y = Big::from_u64(m);
194
195         // Find positive integers `x`, `y` such that `x / y` is exactly `(f * 10^e) / (m * 2^k)`.
196         // This not only avoids dealing with the signs of `e` and `k`, we also eliminate the
197         // power of two common to `10^e` and `2^k` to make the numbers smaller.
198         make_ratio(&mut x, &mut y, e, k);
199
200         let m_digits = [(m & 0xFF_FF_FF_FF) as u32, (m >> 32) as u32];
201         // This is written a bit awkwardly because our bignums don't support
202         // negative numbers, so we use the absolute value + sign information.
203         // The multiplication with m_digits can't overflow. If `x` or `y` are large enough that
204         // we need to worry about overflow, then they are also large enough that `make_ratio` has
205         // reduced the fraction by a factor of 2^64 or more.
206         let (d2, d_negative) = if x >= y {
207             // Don't need x any more, save a clone().
208             x.sub(&y).mul_pow2(1).mul_digits(&m_digits);
209             (x, false)
210         } else {
211             // Still need y - make a copy.
212             let mut y = y.clone();
213             y.sub(&x).mul_pow2(1).mul_digits(&m_digits);
214             (y, true)
215         };
216
217         if d2 < y {
218             let mut d2_double = d2;
219             d2_double.mul_pow2(1);
220             if m == T::MIN_SIG && d_negative && d2_double > y {
221                 z = prev_float(z);
222             } else {
223                 return z;
224             }
225         } else if d2 == y {
226             if m % 2 == 0 {
227                 if m == T::MIN_SIG && d_negative {
228                     z = prev_float(z);
229                 } else {
230                     return z;
231                 }
232             } else if d_negative {
233                 z = prev_float(z);
234             } else {
235                 z = next_float(z);
236             }
237         } else if d_negative {
238             z = prev_float(z);
239         } else {
240             z = next_float(z);
241         }
242     }
243 }
244
245 /// Given `x = f` and `y = m` where `f` represent input decimal digits as usual and `m` is the
246 /// significand of a floating point approximation, make the ratio `x / y` equal to
247 /// `(f * 10^e) / (m * 2^k)`, possibly reduced by a power of two both have in common.
248 fn make_ratio(x: &mut Big, y: &mut Big, e: i16, k: i16) {
249     let (e_abs, k_abs) = (e.abs() as usize, k.abs() as usize);
250     if e >= 0 {
251         if k >= 0 {
252             // x = f * 10^e, y = m * 2^k, except that we reduce the fraction by some power of two.
253             let common = min(e_abs, k_abs);
254             x.mul_pow5(e_abs).mul_pow2(e_abs - common);
255             y.mul_pow2(k_abs - common);
256         } else {
257             // x = f * 10^e * 2^abs(k), y = m
258             // This can't overflow because it requires positive `e` and negative `k`, which can
259             // only happen for values extremely close to 1, which means that `e` and `k` will be
260             // comparatively tiny.
261             x.mul_pow5(e_abs).mul_pow2(e_abs + k_abs);
262         }
263     } else {
264         if k >= 0 {
265             // x = f, y = m * 10^abs(e) * 2^k
266             // This can't overflow either, see above.
267             y.mul_pow5(e_abs).mul_pow2(k_abs + e_abs);
268         } else {
269             // x = f * 2^abs(k), y = m * 10^abs(e), again reducing by a common power of two.
270             let common = min(e_abs, k_abs);
271             x.mul_pow2(k_abs - common);
272             y.mul_pow5(e_abs).mul_pow2(e_abs - common);
273         }
274     }
275 }
276
277 /// Conceptually, Algorithm M is the simplest way to convert a decimal to a float.
278 ///
279 /// We form a ratio that is equal to `f * 10^e`, then throwing in powers of two until it gives
280 /// a valid float significand. The binary exponent `k` is the number of times we multiplied
281 /// numerator or denominator by two, i.e., at all times `f * 10^e` equals `(u / v) * 2^k`.
282 /// When we have found out significand, we only need to round by inspecting the remainder of the
283 /// division, which is done in helper functions further below.
284 ///
285 /// This algorithm is super slow, even with the optimization described in `quick_start()`.
286 /// However, it's the simplest of the algorithms to adapt for overflow, underflow, and subnormal
287 /// results. This implementation takes over when Bellerophon and Algorithm R are overwhelmed.
288 /// Detecting underflow and overflow is easy: The ratio still isn't an in-range significand,
289 /// yet the minimum/maximum exponent has been reached. In the case of overflow, we simply return
290 /// infinity.
291 ///
292 /// Handling underflow and subnormals is trickier. One big problem is that, with the minimum
293 /// exponent, the ratio might still be too large for a significand. See underflow() for details.
294 pub fn algorithm_m<T: RawFloat>(f: &Big, e: i16) -> T {
295     let mut u;
296     let mut v;
297     let e_abs = e.abs() as usize;
298     let mut k = 0;
299     if e < 0 {
300         u = f.clone();
301         v = Big::from_small(1);
302         v.mul_pow5(e_abs).mul_pow2(e_abs);
303     } else {
304         // FIXME possible optimization: generalize big_to_fp so that we can do the equivalent of
305         // fp_to_float(big_to_fp(u)) here, only without the double rounding.
306         u = f.clone();
307         u.mul_pow5(e_abs).mul_pow2(e_abs);
308         v = Big::from_small(1);
309     }
310     quick_start::<T>(&mut u, &mut v, &mut k);
311     let mut rem = Big::from_small(0);
312     let mut x = Big::from_small(0);
313     let min_sig = Big::from_u64(T::MIN_SIG);
314     let max_sig = Big::from_u64(T::MAX_SIG);
315     loop {
316         u.div_rem(&v, &mut x, &mut rem);
317         if k == T::MIN_EXP_INT {
318             // We have to stop at the minimum exponent, if we wait until `k < T::MIN_EXP_INT`,
319             // then we'd be off by a factor of two. Unfortunately this means we have to special-
320             // case normal numbers with the minimum exponent.
321             // FIXME find a more elegant formulation, but run the `tiny-pow10` test to make sure
322             // that it's actually correct!
323             if x >= min_sig && x <= max_sig {
324                 break;
325             }
326             return underflow(x, v, rem);
327         }
328         if k > T::MAX_EXP_INT {
329             return T::INFINITY;
330         }
331         if x < min_sig {
332             u.mul_pow2(1);
333             k -= 1;
334         } else if x > max_sig {
335             v.mul_pow2(1);
336             k += 1;
337         } else {
338             break;
339         }
340     }
341     let q = num::to_u64(&x);
342     let z = rawfp::encode_normal(Unpacked::new(q, k));
343     round_by_remainder(v, rem, q, z)
344 }
345
346 /// Skips over most Algorithm M iterations by checking the bit length.
347 fn quick_start<T: RawFloat>(u: &mut Big, v: &mut Big, k: &mut i16) {
348     // The bit length is an estimate of the base two logarithm, and log(u / v) = log(u) - log(v).
349     // The estimate is off by at most 1, but always an under-estimate, so the error on log(u)
350     // and log(v) are of the same sign and cancel out (if both are large). Therefore the error
351     // for log(u / v) is at most one as well.
352     // The target ratio is one where u/v is in an in-range significand. Thus our termination
353     // condition is log2(u / v) being the significand bits, plus/minus one.
354     // FIXME Looking at the second bit could improve the estimate and avoid some more divisions.
355     let target_ratio = T::SIG_BITS as i16;
356     let log2_u = u.bit_length() as i16;
357     let log2_v = v.bit_length() as i16;
358     let mut u_shift: i16 = 0;
359     let mut v_shift: i16 = 0;
360     assert!(*k == 0);
361     loop {
362         if *k == T::MIN_EXP_INT {
363             // Underflow or subnormal. Leave it to the main function.
364             break;
365         }
366         if *k == T::MAX_EXP_INT {
367             // Overflow. Leave it to the main function.
368             break;
369         }
370         let log2_ratio = (log2_u + u_shift) - (log2_v + v_shift);
371         if log2_ratio < target_ratio - 1 {
372             u_shift += 1;
373             *k -= 1;
374         } else if log2_ratio > target_ratio + 1 {
375             v_shift += 1;
376             *k += 1;
377         } else {
378             break;
379         }
380     }
381     u.mul_pow2(u_shift as usize);
382     v.mul_pow2(v_shift as usize);
383 }
384
385 fn underflow<T: RawFloat>(x: Big, v: Big, rem: Big) -> T {
386     if x < Big::from_u64(T::MIN_SIG) {
387         let q = num::to_u64(&x);
388         let z = rawfp::encode_subnormal(q);
389         return round_by_remainder(v, rem, q, z);
390     }
391     // Ratio isn't an in-range significand with the minimum exponent, so we need to round off
392     // excess bits and adjust the exponent accordingly. The real value now looks like this:
393     //
394     //        x        lsb
395     // /--------------\/
396     // 1010101010101010.10101010101010 * 2^k
397     // \-----/\-------/ \------------/
398     //    q     trunc.    (represented by rem)
399     //
400     // Therefore, when the rounded-off bits are != 0.5 ULP, they decide the rounding
401     // on their own. When they are equal and the remainder is non-zero, the value still
402     // needs to be rounded up. Only when the rounded off bits are 1/2 and the remainder
403     // is zero, we have a half-to-even situation.
404     let bits = x.bit_length();
405     let lsb = bits - T::SIG_BITS as usize;
406     let q = num::get_bits(&x, lsb, bits);
407     let k = T::MIN_EXP_INT + lsb as i16;
408     let z = rawfp::encode_normal(Unpacked::new(q, k));
409     let q_even = q % 2 == 0;
410     match num::compare_with_half_ulp(&x, lsb) {
411         Greater => next_float(z),
412         Less => z,
413         Equal if rem.is_zero() && q_even => z,
414         Equal => next_float(z),
415     }
416 }
417
418 /// Ordinary round-to-even, obfuscated by having to round based on the remainder of a division.
419 fn round_by_remainder<T: RawFloat>(v: Big, r: Big, q: u64, z: T) -> T {
420     let mut v_minus_r = v;
421     v_minus_r.sub(&r);
422     if r < v_minus_r {
423         z
424     } else if r > v_minus_r {
425         next_float(z)
426     } else if q % 2 == 0 {
427         z
428     } else {
429         next_float(z)
430     }
431 }