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