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