]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/flt2dec/strategy/dragon.rs
aa6a08cb2057ea34a4e1faed0dfa1c700a56b5a6
[rust.git] / src / libcore / num / flt2dec / strategy / dragon.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Almost direct (but slightly optimized) Rust translation of Figure 3 of "Printing
12 //! Floating-Point Numbers Quickly and Accurately"[^1].
13 //!
14 //! [^1]: Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers
15 //!   quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116.
16
17 use cmp::Ordering;
18
19 use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up};
20 use num::flt2dec::estimator::estimate_scaling_factor;
21 use num::bignum::Digit32 as Digit;
22 use num::bignum::Big32x40 as Big;
23
24 static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000,
25                              1000000, 10000000, 100000000, 1000000000];
26 static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000,
27                                 2000000, 20000000, 200000000, 2000000000];
28
29 // precalculated arrays of `Digit`s for 10^(2^n)
30 static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2];
31 static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee];
32 static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03];
33 static POW10TO128: [Digit; 14] =
34     [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08,
35      0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e];
36 static POW10TO256: [Digit; 27] =
37     [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6,
38      0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e,
39      0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7];
40
41 #[doc(hidden)]
42 pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big {
43     debug_assert!(n < 512);
44     if n &   7 != 0 { x.mul_small(POW10[n & 7]); }
45     if n &   8 != 0 { x.mul_small(POW10[8]); }
46     if n &  16 != 0 { x.mul_digits(&POW10TO16); }
47     if n &  32 != 0 { x.mul_digits(&POW10TO32); }
48     if n &  64 != 0 { x.mul_digits(&POW10TO64); }
49     if n & 128 != 0 { x.mul_digits(&POW10TO128); }
50     if n & 256 != 0 { x.mul_digits(&POW10TO256); }
51     x
52 }
53
54 fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big {
55     let largest = POW10.len() - 1;
56     while n > largest {
57         x.div_rem_small(POW10[largest]);
58         n -= largest;
59     }
60     x.div_rem_small(TWOPOW10[n]);
61     x
62 }
63
64 // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)`
65 fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big,
66                        scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) {
67     let mut d = 0;
68     if *x >= *scale8 { x.sub(scale8); d += 8; }
69     if *x >= *scale4 { x.sub(scale4); d += 4; }
70     if *x >= *scale2 { x.sub(scale2); d += 2; }
71     if *x >= *scale  { x.sub(scale);  d += 1; }
72     debug_assert!(*x < *scale);
73     (d, x)
74 }
75
76 /// The shortest mode implementation for Dragon.
77 pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) {
78     // the number `v` to format is known to be:
79     // - equal to `mant * 2^exp`;
80     // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and
81     // - followed by `(mant + 2 * plus) * 2^exp` in the original type.
82     //
83     // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.)
84     // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too.
85     //
86     // this also means that any number between `low = (mant - minus) * 2^exp` and
87     // `high = (mant + plus) * 2^exp` will map to this exact floating point number,
88     // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`).
89
90     assert!(d.mant > 0);
91     assert!(d.minus > 0);
92     assert!(d.plus > 0);
93     assert!(d.mant.checked_add(d.plus).is_some());
94     assert!(d.mant.checked_sub(d.minus).is_some());
95     assert!(buf.len() >= MAX_SIG_DIGITS);
96
97     // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}`
98     let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal};
99
100     // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`.
101     // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later.
102     let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp);
103
104     // convert `{mant, plus, minus} * 2^exp` into the fractional form so that:
105     // - `v = mant / scale`
106     // - `low = (mant - minus) / scale`
107     // - `high = (mant + plus) / scale`
108     let mut mant = Big::from_u64(d.mant);
109     let mut minus = Big::from_u64(d.minus);
110     let mut plus = Big::from_u64(d.plus);
111     let mut scale = Big::from_small(1);
112     if d.exp < 0 {
113         scale.mul_pow2(-d.exp as usize);
114     } else {
115         mant.mul_pow2(d.exp as usize);
116         minus.mul_pow2(d.exp as usize);
117         plus.mul_pow2(d.exp as usize);
118     }
119
120     // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
121     if k >= 0 {
122         mul_pow10(&mut scale, k as usize);
123     } else {
124         mul_pow10(&mut mant, -k as usize);
125         mul_pow10(&mut minus, -k as usize);
126         mul_pow10(&mut plus, -k as usize);
127     }
128
129     // fixup when `mant + plus > scale` (or `>=`).
130     // we are not actually modifying `scale`, since we can skip the initial multiplication instead.
131     // now `scale < mant + plus <= scale * 10` and we are ready to generate digits.
132     //
133     // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`.
134     // in this case rounding-up condition (`up` below) will be triggered immediately.
135     if scale.cmp(mant.clone().add(&plus)) < rounding {
136         // equivalent to scaling `scale` by 10
137         k += 1;
138     } else {
139         mant.mul_small(10);
140         minus.mul_small(10);
141         plus.mul_small(10);
142     }
143
144     // cache `(2, 4, 8) * scale` for digit generation.
145     let mut scale2 = scale.clone(); scale2.mul_pow2(1);
146     let mut scale4 = scale.clone(); scale4.mul_pow2(2);
147     let mut scale8 = scale.clone(); scale8.mul_pow2(3);
148
149     let mut down;
150     let mut up;
151     let mut i = 0;
152     loop {
153         // invariants, where `d[0..n-1]` are digits generated so far:
154         // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)`
155         // - `v - low = minus / scale * 10^(k-n-1)`
156         // - `high - v = plus / scale * 10^(k-n-1)`
157         // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`)
158         // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) + ... + d[j-1] * 10 + d[j]`.
159
160         // generate one digit: `d[n] = floor(mant / scale) < 10`.
161         let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8);
162         debug_assert!(d < 10);
163         buf[i] = b'0' + d;
164         i += 1;
165
166         // this is a simplified description of the modified Dragon algorithm.
167         // many intermediate derivations and completeness arguments are omitted for convenience.
168         //
169         // start with modified invariants, as we've updated `n`:
170         // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)`
171         // - `v - low = minus / scale * 10^(k-n)`
172         // - `high - v = plus / scale * 10^(k-n)`
173         //
174         // assume that `d[0..n-1]` is the shortest representation between `low` and `high`,
175         // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't:
176         // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and
177         // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct).
178         //
179         // the second condition simplifies to `2 * mant <= scale`.
180         // solving invariants in terms of `mant`, `low` and `high` yields
181         // a simpler version of the first condition: `-plus < mant < minus`.
182         // since `-plus < 0 <= mant`, we have the correct shortest representation
183         // when `mant < minus` and `2 * mant <= scale`.
184         // (the former becomes `mant <= minus` when the original mantissa is even.)
185         //
186         // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit.
187         // this is enough for restoring that condition: we already know that
188         // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`.
189         // in this case, the first condition becomes `-plus < mant - scale < minus`.
190         // since `mant < scale` after the generation, we have `scale < mant + plus`.
191         // (again, this becomes `scale <= mant + plus` when the original mantissa is even.)
192         //
193         // in short:
194         // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`).
195         // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`).
196         // - keep generating otherwise.
197         down = mant.cmp(&minus) < rounding;
198         up = scale.cmp(mant.clone().add(&plus)) < rounding;
199         if down || up { break; } // we have the shortest representation, proceed to the rounding
200
201         // restore the invariants.
202         // this makes the algorithm always terminating: `minus` and `plus` always increases,
203         // but `mant` is clipped modulo `scale` and `scale` is fixed.
204         mant.mul_small(10);
205         minus.mul_small(10);
206         plus.mul_small(10);
207     }
208
209     // rounding up happens when
210     // i) only the rounding-up condition was triggered, or
211     // ii) both conditions were triggered and tie breaking prefers rounding up.
212     if up && (!down || *mant.mul_pow2(1) >= scale) {
213         // if rounding up changes the length, the exponent should also change.
214         // it seems that this condition is very hard to satisfy (possibly impossible),
215         // but we are just being safe and consistent here.
216         if let Some(c) = round_up(buf, i) {
217             buf[i] = c;
218             i += 1;
219             k += 1;
220         }
221     }
222
223     (i, k)
224 }
225
226 /// The exact and fixed mode implementation for Dragon.
227 pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) {
228     assert!(d.mant > 0);
229     assert!(d.minus > 0);
230     assert!(d.plus > 0);
231     assert!(d.mant.checked_add(d.plus).is_some());
232     assert!(d.mant.checked_sub(d.minus).is_some());
233
234     // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`.
235     let mut k = estimate_scaling_factor(d.mant, d.exp);
236
237     // `v = mant / scale`.
238     let mut mant = Big::from_u64(d.mant);
239     let mut scale = Big::from_small(1);
240     if d.exp < 0 {
241         scale.mul_pow2(-d.exp as usize);
242     } else {
243         mant.mul_pow2(d.exp as usize);
244     }
245
246     // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`.
247     if k >= 0 {
248         mul_pow10(&mut scale, k as usize);
249     } else {
250         mul_pow10(&mut mant, -k as usize);
251     }
252
253     // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`.
254     // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`.
255     // we are not actually modifying `scale`, since we can skip the initial multiplication instead.
256     // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up.
257     if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale {
258         // equivalent to scaling `scale` by 10
259         k += 1;
260     } else {
261         mant.mul_small(10);
262     }
263
264     // if we are working with the last-digit limitation, we need to shorten the buffer
265     // before the actual rendering in order to avoid double rounding.
266     // note that we have to enlarge the buffer again when rounding up happens!
267     let mut len = if k < limit {
268         // oops, we cannot even produce *one* digit.
269         // this is possible when, say, we've got something like 9.5 and it's being rounded to 10.
270         // we return an empty buffer, with an exception of the later rounding-up case
271         // which occurs when `k == limit` and has to produce exactly one digit.
272         0
273     } else if ((k as i32 - limit as i32) as usize) < buf.len() {
274         (k - limit) as usize
275     } else {
276         buf.len()
277     };
278
279     if len > 0 {
280         // cache `(2, 4, 8) * scale` for digit generation.
281         // (this can be expensive, so do not calculate them when the buffer is empty.)
282         let mut scale2 = scale.clone(); scale2.mul_pow2(1);
283         let mut scale4 = scale.clone(); scale4.mul_pow2(2);
284         let mut scale8 = scale.clone(); scale8.mul_pow2(3);
285
286         for i in 0..len {
287             if mant.is_zero() { // following digits are all zeroes, we stop here
288                 // do *not* try to perform rounding! rather, fill remaining digits.
289                 for c in &mut buf[i..len] { *c = b'0'; }
290                 return (len, k);
291             }
292
293             let mut d = 0;
294             if mant >= scale8 { mant.sub(&scale8); d += 8; }
295             if mant >= scale4 { mant.sub(&scale4); d += 4; }
296             if mant >= scale2 { mant.sub(&scale2); d += 2; }
297             if mant >= scale  { mant.sub(&scale);  d += 1; }
298             debug_assert!(mant < scale);
299             debug_assert!(d < 10);
300             buf[i] = b'0' + d;
301             mant.mul_small(10);
302         }
303     }
304
305     // rounding up if we stop in the middle of digits
306     // if the following digits are exactly 5000..., check the prior digit and try to
307     // round to even (i.e. avoid rounding up when the prior digit is even).
308     let order = mant.cmp(scale.mul_small(5));
309     if order == Ordering::Greater || (order == Ordering::Equal &&
310                                       (len == 0 || buf[len-1] & 1 == 1)) {
311         // if rounding up changes the length, the exponent should also change.
312         // but we've been requested a fixed number of digits, so do not alter the buffer...
313         if let Some(c) = round_up(buf, len) {
314             // ...unless we've been requested the fixed precision instead.
315             // we also need to check that, if the original buffer was empty,
316             // the additional digit can only be added when `k == limit` (edge case).
317             k += 1;
318             if k > limit && len < buf.len() {
319                 buf[len] = c;
320                 len += 1;
321             }
322         }
323     }
324
325     (len, k)
326 }