]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/dec2flt/rawfp.rs
Rollup merge of #30689 - Manishearth:lifetime-bound, r=steveklabnik
[rust.git] / src / libcore / num / dec2flt / rawfp.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 //! Bit fiddling on positive IEEE 754 floats. Negative numbers aren't and needn't be handled.
12 //! Normal floating point numbers have a canonical representation as (frac, exp) such that the
13 //! value is 2^exp * (1 + sum(frac[N-i] / 2^i)) where N is the number of bits. Subnormals are
14 //! slightly different and weird, but the same principle applies.
15 //!
16 //! Here, however, we represent them as (sig, k) with f positive, such that the value is f * 2^e.
17 //! Besides making the "hidden bit" explicit, this changes the exponent by the so-called
18 //! mantissa shift.
19 //!
20 //! Put another way, normally floats are written as (1) but here they are written as (2):
21 //!
22 //! 1. `1.101100...11 * 2^m`
23 //! 2. `1101100...11 * 2^n`
24 //!
25 //! We call (1) the **fractional representation** and (2) the **integral representation**.
26 //!
27 //! Many functions in this module only handle normal numbers. The dec2flt routines conservatively
28 //! take the universally-correct slow path (Algorithm M) for very small and very large numbers.
29 //! That algorithm needs only next_float() which does handle subnormals and zeros.
30 use prelude::v1::*;
31 use u32;
32 use cmp::Ordering::{Less, Equal, Greater};
33 use ops::{Mul, Div, Neg};
34 use fmt::{Debug, LowerExp};
35 use mem::transmute;
36 use num::diy_float::Fp;
37 use num::FpCategory::{Infinite, Zero, Subnormal, Normal, Nan};
38 use num::Float;
39 use num::dec2flt::num::{self, Big};
40 use num::dec2flt::table;
41
42 #[derive(Copy, Clone, Debug)]
43 pub struct Unpacked {
44     pub sig: u64,
45     pub k: i16,
46 }
47
48 impl Unpacked {
49     pub fn new(sig: u64, k: i16) -> Self {
50         Unpacked { sig: sig, k: k }
51     }
52 }
53
54 /// A helper trait to avoid duplicating basically all the conversion code for `f32` and `f64`.
55 ///
56 /// See the parent module's doc comment for why this is necessary.
57 ///
58 /// Should **never ever** be implemented for other types or be used outside the dec2flt module.
59 /// Inherits from `Float` because there is some overlap, but all the reused methods are trivial.
60 /// The "methods" (pseudo-constants) with default implementation should not be overriden.
61 pub trait RawFloat : Float + Copy + Debug + LowerExp
62                     + Mul<Output=Self> + Div<Output=Self> + Neg<Output=Self>
63 {
64     /// Get the raw binary representation of the float.
65     fn transmute(self) -> u64;
66
67     /// Transmute the raw binary representation into a float.
68     fn from_bits(bits: u64) -> Self;
69
70     /// Decode the float.
71     fn unpack(self) -> Unpacked;
72
73     /// Cast from a small integer that can be represented exactly.  Panic if the integer can't be
74     /// represented, the other code in this module makes sure to never let that happen.
75     fn from_int(x: u64) -> Self;
76
77     /// Get the value 10^e from a pre-computed table. Panics for e >= ceil_log5_of_max_sig().
78     fn short_fast_pow10(e: usize) -> Self;
79
80     // FIXME Everything that follows should be associated constants, but taking the value of an
81     // associated constant from a type parameter does not work (yet?)
82     // A possible workaround is having a `FloatInfo` struct for all the constants, but so far
83     // the methods aren't painful enough to rewrite.
84
85     /// What the name says. It's easier to hard code than juggling intrinsics and
86     /// hoping LLVM constant folds it.
87     fn ceil_log5_of_max_sig() -> i16;
88
89     // A conservative bound on the decimal digits of inputs that can't produce overflow or zero or
90     /// subnormals. Probably the decimal exponent of the maximum normal value, hence the name.
91     fn max_normal_digits() -> usize;
92
93     /// When the most significant decimal digit has a place value greater than this, the number
94     /// is certainly rounded to infinity.
95     fn inf_cutoff() -> i64;
96
97     /// When the most significant decimal digit has a place value less than this, the number
98     /// is certainly rounded to zero.
99     fn zero_cutoff() -> i64;
100
101     /// The number of bits in the exponent.
102     fn exp_bits() -> u8;
103
104     /// The number of bits in the singificand, *including* the hidden bit.
105     fn sig_bits() -> u8;
106
107     /// The number of bits in the singificand, *excluding* the hidden bit.
108     fn explicit_sig_bits() -> u8 {
109         Self::sig_bits() - 1
110     }
111
112     /// The maximum legal exponent in fractional representation.
113     fn max_exp() -> i16 {
114         (1 << (Self::exp_bits() - 1)) - 1
115     }
116
117     /// The minimum legal exponent in fractional representation, excluding subnormals.
118     fn min_exp() -> i16 {
119         -Self::max_exp() + 1
120     }
121
122     /// `MAX_EXP` for integral representation, i.e., with the shift applied.
123     fn max_exp_int() -> i16 {
124         Self::max_exp() - (Self::sig_bits() as i16 - 1)
125     }
126
127     /// `MAX_EXP` encoded (i.e., with offset bias)
128     fn max_encoded_exp() -> i16 {
129         (1 << Self::exp_bits()) - 1
130     }
131
132     /// `MIN_EXP` for integral representation, i.e., with the shift applied.
133     fn min_exp_int() -> i16 {
134         Self::min_exp() - (Self::sig_bits() as i16 - 1)
135     }
136
137     /// The maximum normalized singificand in integral representation.
138     fn max_sig() -> u64 {
139         (1 << Self::sig_bits()) - 1
140     }
141
142     /// The minimal normalized significand in integral representation.
143     fn min_sig() -> u64 {
144         1 << (Self::sig_bits() - 1)
145     }
146 }
147
148 impl RawFloat for f32 {
149     fn sig_bits() -> u8 {
150         24
151     }
152
153     fn exp_bits() -> u8 {
154         8
155     }
156
157     fn ceil_log5_of_max_sig() -> i16 {
158         11
159     }
160
161     fn transmute(self) -> u64 {
162         let bits: u32 = unsafe { transmute(self) };
163         bits as u64
164     }
165
166     fn from_bits(bits: u64) -> f32 {
167         assert!(bits < u32::MAX as u64, "f32::from_bits: too many bits");
168         unsafe { transmute(bits as u32) }
169     }
170
171     fn unpack(self) -> Unpacked {
172         let (sig, exp, _sig) = self.integer_decode();
173         Unpacked::new(sig, exp)
174     }
175
176     fn from_int(x: u64) -> f32 {
177         // rkruppe is uncertain whether `as` rounds correctly on all platforms.
178         debug_assert!(x as f32 == fp_to_float(Fp { f: x, e: 0 }));
179         x as f32
180     }
181
182     fn short_fast_pow10(e: usize) -> Self {
183         table::F32_SHORT_POWERS[e]
184     }
185
186     fn max_normal_digits() -> usize {
187         35
188     }
189
190     fn inf_cutoff() -> i64 {
191         40
192     }
193
194     fn zero_cutoff() -> i64 {
195         -48
196     }
197 }
198
199
200 impl RawFloat for f64 {
201     fn sig_bits() -> u8 {
202         53
203     }
204
205     fn exp_bits() -> u8 {
206         11
207     }
208
209     fn ceil_log5_of_max_sig() -> i16 {
210         23
211     }
212
213     fn transmute(self) -> u64 {
214         let bits: u64 = unsafe { transmute(self) };
215         bits
216     }
217
218     fn from_bits(bits: u64) -> f64 {
219         unsafe { transmute(bits) }
220     }
221
222     fn unpack(self) -> Unpacked {
223         let (sig, exp, _sig) = self.integer_decode();
224         Unpacked::new(sig, exp)
225     }
226
227     fn from_int(x: u64) -> f64 {
228         // rkruppe is uncertain whether `as` rounds correctly on all platforms.
229         debug_assert!(x as f64 == fp_to_float(Fp { f: x, e: 0 }));
230         x as f64
231     }
232
233     fn short_fast_pow10(e: usize) -> Self {
234         table::F64_SHORT_POWERS[e]
235     }
236
237     fn max_normal_digits() -> usize {
238         305
239     }
240
241     fn inf_cutoff() -> i64 {
242         310
243     }
244
245     fn zero_cutoff() -> i64 {
246         -326
247     }
248
249 }
250
251 /// Convert an Fp to the closest f64. Only handles number that fit into a normalized f64.
252 pub fn fp_to_float<T: RawFloat>(x: Fp) -> T {
253     let x = x.normalize();
254     // x.f is 64 bit, so x.e has a mantissa shift of 63
255     let e = x.e + 63;
256     if e > T::max_exp() {
257         panic!("fp_to_float: exponent {} too large", e)
258     }  else if e > T::min_exp() {
259         encode_normal(round_normal::<T>(x))
260     } else {
261         panic!("fp_to_float: exponent {} too small", e)
262     }
263 }
264
265 /// Round the 64-bit significand to 53 bit with half-to-even. Does not handle exponent overflow.
266 pub fn round_normal<T: RawFloat>(x: Fp) -> Unpacked {
267     let excess = 64 - T::sig_bits() as i16;
268     let half: u64 = 1 << (excess - 1);
269     let (q, rem) = (x.f >> excess, x.f & ((1 << excess) - 1));
270     assert_eq!(q << excess | rem, x.f);
271     // Adjust mantissa shift
272     let k = x.e + excess;
273     if rem < half {
274         Unpacked::new(q, k)
275     } else if rem == half && (q % 2) == 0 {
276         Unpacked::new(q, k)
277     } else if q == T::max_sig() {
278         Unpacked::new(T::min_sig(), k + 1)
279     } else {
280         Unpacked::new(q + 1, k)
281     }
282 }
283
284 /// Inverse of `RawFloat::unpack()` for normalized numbers.
285 /// Panics if the significand or exponent are not valid for normalized numbers.
286 pub fn encode_normal<T: RawFloat>(x: Unpacked) -> T {
287     debug_assert!(T::min_sig() <= x.sig && x.sig <= T::max_sig(),
288         "encode_normal: significand not normalized");
289     // Remove the hidden bit
290     let sig_enc = x.sig & !(1 << T::explicit_sig_bits());
291     // Adjust the exponent for exponent bias and mantissa shift
292     let k_enc = x.k + T::max_exp() + T::explicit_sig_bits() as i16;
293     debug_assert!(k_enc != 0 && k_enc < T::max_encoded_exp(),
294         "encode_normal: exponent out of range");
295     // Leave sign bit at 0 ("+"), our numbers are all positive
296     let bits = (k_enc as u64) << T::explicit_sig_bits() | sig_enc;
297     T::from_bits(bits)
298 }
299
300 /// Construct the subnormal. A mantissa of 0 is allowed and constructs zero.
301 pub fn encode_subnormal<T: RawFloat>(significand: u64) -> T {
302     assert!(significand < T::min_sig(), "encode_subnormal: not actually subnormal");
303     // Encoded exponent is 0, the sign bit is 0, so we just have to reinterpret the bits.
304     T::from_bits(significand)
305 }
306
307 /// Approximate a bignum with an Fp. Rounds within 0.5 ULP with half-to-even.
308 pub fn big_to_fp(f: &Big) -> Fp {
309     let end = f.bit_length();
310     assert!(end != 0, "big_to_fp: unexpectedly, input is zero");
311     let start = end.saturating_sub(64);
312     let leading = num::get_bits(f, start, end);
313     // We cut off all bits prior to the index `start`, i.e., we effectively right-shift by
314     // an amount of `start`, so this is also the exponent we need.
315     let e = start as i16;
316     let rounded_down = Fp { f: leading, e: e }.normalize();
317     // Round (half-to-even) depending on the truncated bits.
318     match num::compare_with_half_ulp(f, start) {
319         Less => rounded_down,
320         Equal if leading % 2 == 0 => rounded_down,
321         Equal | Greater => match leading.checked_add(1) {
322             Some(f) => Fp { f: f, e: e }.normalize(),
323             None => Fp { f: 1 << 63, e: e + 1 },
324         }
325     }
326 }
327
328 /// Find the largest floating point number strictly smaller than the argument.
329 /// Does not handle subnormals, zero, or exponent underflow.
330 pub fn prev_float<T: RawFloat>(x: T) -> T {
331     match x.classify() {
332         Infinite => panic!("prev_float: argument is infinite"),
333         Nan => panic!("prev_float: argument is NaN"),
334         Subnormal => panic!("prev_float: argument is subnormal"),
335         Zero => panic!("prev_float: argument is zero"),
336         Normal => {
337             let Unpacked { sig, k } = x.unpack();
338             if sig == T::min_sig() {
339                 encode_normal(Unpacked::new(T::max_sig(), k - 1))
340             } else {
341                 encode_normal(Unpacked::new(sig - 1, k))
342             }
343         }
344     }
345 }
346
347 // Find the smallest floating point number strictly larger than the argument.
348 // This operation is saturating, i.e. next_float(inf) == inf.
349 // Unlike most code in this module, this function does handle zero, subnormals, and infinities.
350 // However, like all other code here, it does not deal with NaN and negative numbers.
351 pub fn next_float<T: RawFloat>(x: T) -> T {
352     match x.classify() {
353         Nan => panic!("next_float: argument is NaN"),
354         Infinite => T::infinity(),
355         // This seems too good to be true, but it works.
356         // 0.0 is encoded as the all-zero word. Subnormals are 0x000m...m where m is the mantissa.
357         // In particular, the smallest subnormal is 0x0...01 and the largest is 0x000F...F.
358         // The smallest normal number is 0x0010...0, so this corner case works as well.
359         // If the increment overflows the mantissa, the carry bit increments the exponent as we
360         // want, and the mantissa bits become zero. Because of the hidden bit convention, this
361         // too is exactly what we want!
362         // Finally, f64::MAX + 1 = 7eff...f + 1 = 7ff0...0 = f64::INFINITY.
363         Zero | Subnormal | Normal => {
364             let bits: u64 = x.transmute();
365             T::from_bits(bits + 1)
366         }
367     }
368 }