1 //! The various algorithms from the paper.
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;
10 /// Number of significand bits in Fp
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.
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];
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"))]
28 pub fn set_precision<T>() {}
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")))]
38 use crate::mem::size_of;
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.
43 /// The x87 FPU is a 16-bits register whose fields are as follows:
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 |
49 /// The documentation for all of the fields is available in the IA-32 Architectures Software
50 /// Developer's Manual (Volume 1).
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);
61 // SAFETY: the `fldcw` instruction has been audited to be able to work correctly with
63 unsafe { llvm_asm!("fldcw $0" :: "m" (cw) :: "volatile") }
66 /// Sets the precision field of the FPU to `T` and returns a `FPUControlWord`.
67 pub fn set_precision<T>() -> FPUControlWord {
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
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
81 unsafe { llvm_asm!("fnstcw $0" : "=*m" (&cw) ::: "volatile") }
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);
90 impl Drop for FPUControlWord {
97 /// The fast path of Bellerophon using machine-sized integers and floats.
99 /// This is extracted into a separate function so that it can be attempted before constructing
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).
109 if e.abs() >= T::CEIL_LOG5_OF_MAX_SIG as i64 {
112 let f = num::from_str_unchecked(integral.iter().chain(fractional.iter()));
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>();
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.
128 Some(T::from_int(f) * T::short_fast_pow10(e as usize))
130 Some(T::from_int(f) / T::short_fast_pow10(e.abs() as usize))
134 /// Algorithm Bellerophon is trivial code justified by non-trivial numeric analysis.
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.
142 /// The hand-wavy "close to halfway" is made precise by the numeric analysis in the paper.
143 /// In the words of Clinger:
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 }
154 if e >= 0 { 1 } else { 4 }
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))
168 /// An iterative algorithm that improves a floating point approximation of `f * 10^e`.
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 {
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);
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);
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);
197 // Still need y - make a copy.
198 let mut y = y.clone();
199 y.sub(&x).mul_pow2(1).mul_digits(&m_digits);
204 let mut d2_double = d2;
205 d2_double.mul_pow2(1);
206 if m == T::MIN_SIG && d_negative && d2_double > y {
213 if m == T::MIN_SIG && d_negative {
218 } else if d_negative {
223 } else if d_negative {
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);
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);
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);
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);
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);
263 /// Conceptually, Algorithm M is the simplest way to convert a decimal to a float.
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.
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
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 {
283 let e_abs = e.abs() as usize;
287 v = Big::from_small(1);
288 v.mul_pow5(e_abs).mul_pow2(e_abs);
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.
293 u.mul_pow5(e_abs).mul_pow2(e_abs);
294 v = Big::from_small(1);
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);
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 {
312 return underflow(x, v, rem);
314 if k > T::MAX_EXP_INT {
320 } else if x > max_sig {
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)
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;
348 if *k == T::MIN_EXP_INT {
349 // Underflow or subnormal. Leave it to the main function.
352 if *k == T::MAX_EXP_INT {
353 // Overflow. Leave it to the main function.
356 let log2_ratio = (log2_u + u_shift) - (log2_v + v_shift);
357 if log2_ratio < target_ratio - 1 {
360 } else if log2_ratio > target_ratio + 1 {
367 u.mul_pow2(u_shift as usize);
368 v.mul_pow2(v_shift as usize);
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);
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:
382 // 1010101010101010.10101010101010 * 2^k
383 // \-----/\-------/ \------------/
384 // q trunc. (represented by rem)
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),
399 Equal if rem.is_zero() && q_even => z,
400 Equal => next_float(z),
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;
410 } else if r > v_minus_r {
412 } else if q % 2 == 0 {