]> git.lizzy.rs Git - rust.git/blob - src/libcore/tests/num/flt2dec/random.rs
315ac4d7d99f53650a3a61c07307078bef959df9
[rust.git] / src / libcore / tests / num / flt2dec / random.rs
1 // Copyright 2017 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 #![cfg(not(target_arch = "wasm32"))]
12
13 use std::i16;
14 use std::mem;
15 use std::str;
16
17 use core::num::flt2dec::MAX_SIG_DIGITS;
18 use core::num::flt2dec::strategy::grisu::format_exact_opt;
19 use core::num::flt2dec::strategy::grisu::format_shortest_opt;
20 use core::num::flt2dec::{decode, DecodableFloat, FullDecoded, Decoded};
21
22 use rand::{self, Rand, XorShiftRng};
23 use rand::distributions::{IndependentSample, Range};
24
25 pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
26     match decode(v).1 {
27         FullDecoded::Finite(decoded) => decoded,
28         full_decoded => panic!("expected finite, got {:?} instead", full_decoded)
29     }
30 }
31
32
33 fn iterate<F, G, V>(func: &str, k: usize, n: usize, mut f: F, mut g: G, mut v: V) -> (usize, usize)
34         where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>,
35               G: FnMut(&Decoded, &mut [u8]) -> (usize, i16),
36               V: FnMut(usize) -> Decoded {
37     assert!(k <= 1024);
38
39     let mut npassed = 0; // f(x) = Some(g(x))
40     let mut nignored = 0; // f(x) = None
41
42     for i in 0..n {
43         if (i & 0xfffff) == 0 {
44             println!("in progress, {:x}/{:x} (ignored={} passed={} failed={})",
45                      i, n, nignored, npassed, i - nignored - npassed);
46         }
47
48         let decoded = v(i);
49         let mut buf1 = [0; 1024];
50         if let Some((len1, e1)) = f(&decoded, &mut buf1[..k]) {
51             let mut buf2 = [0; 1024];
52             let (len2, e2) = g(&decoded, &mut buf2[..k]);
53             if e1 == e2 && &buf1[..len1] == &buf2[..len2] {
54                 npassed += 1;
55             } else {
56                 println!("equivalence test failed, {:x}/{:x}: {:?} f(i)={}e{} g(i)={}e{}",
57                          i, n, decoded, str::from_utf8(&buf1[..len1]).unwrap(), e1,
58                                         str::from_utf8(&buf2[..len2]).unwrap(), e2);
59             }
60         } else {
61             nignored += 1;
62         }
63     }
64     println!("{}({}): done, ignored={} passed={} failed={}",
65              func, k, nignored, npassed, n - nignored - npassed);
66     assert!(nignored + npassed == n,
67             "{}({}): {} out of {} values returns an incorrect value!",
68             func, k, n - nignored - npassed, n);
69     (npassed, nignored)
70 }
71
72 pub fn f32_random_equivalence_test<F, G>(f: F, g: G, k: usize, n: usize)
73         where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>,
74               G: FnMut(&Decoded, &mut [u8]) -> (usize, i16) {
75     let mut rng: XorShiftRng = Rand::rand(&mut rand::thread_rng());
76     let f32_range = Range::new(0x0000_0001u32, 0x7f80_0000);
77     iterate("f32_random_equivalence_test", k, n, f, g, |_| {
78         let i: u32 = f32_range.ind_sample(&mut rng);
79         let x: f32 = unsafe {mem::transmute(i)};
80         decode_finite(x)
81     });
82 }
83
84 pub fn f64_random_equivalence_test<F, G>(f: F, g: G, k: usize, n: usize)
85         where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>,
86               G: FnMut(&Decoded, &mut [u8]) -> (usize, i16) {
87     let mut rng: XorShiftRng = Rand::rand(&mut rand::thread_rng());
88     let f64_range = Range::new(0x0000_0000_0000_0001u64, 0x7ff0_0000_0000_0000);
89     iterate("f64_random_equivalence_test", k, n, f, g, |_| {
90         let i: u64 = f64_range.ind_sample(&mut rng);
91         let x: f64 = unsafe {mem::transmute(i)};
92         decode_finite(x)
93     });
94 }
95
96 pub fn f32_exhaustive_equivalence_test<F, G>(f: F, g: G, k: usize)
97         where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>,
98               G: FnMut(&Decoded, &mut [u8]) -> (usize, i16) {
99     // we have only 2^23 * (2^8 - 1) - 1 = 2,139,095,039 positive finite f32 values,
100     // so why not simply testing all of them?
101     //
102     // this is of course very stressful (and thus should be behind an `#[ignore]` attribute),
103     // but with `-C opt-level=3 -C lto` this only takes about an hour or so.
104
105     // iterate from 0x0000_0001 to 0x7f7f_ffff, i.e. all finite ranges
106     let (npassed, nignored) = iterate("f32_exhaustive_equivalence_test",
107                                       k, 0x7f7f_ffff, f, g, |i: usize| {
108         let x: f32 = unsafe {mem::transmute(i as u32 + 1)};
109         decode_finite(x)
110     });
111     assert_eq!((npassed, nignored), (2121451881, 17643158));
112 }
113
114 #[test]
115 fn shortest_random_equivalence_test() {
116     use core::num::flt2dec::strategy::dragon::format_shortest as fallback;
117     f64_random_equivalence_test(format_shortest_opt, fallback, MAX_SIG_DIGITS, 10_000);
118     f32_random_equivalence_test(format_shortest_opt, fallback, MAX_SIG_DIGITS, 10_000);
119 }
120
121 #[test] #[ignore] // it is too expensive
122 fn shortest_f32_exhaustive_equivalence_test() {
123     // it is hard to directly test the optimality of the output, but we can at least test if
124     // two different algorithms agree to each other.
125     //
126     // this reports the progress and the number of f32 values returned `None`.
127     // with `--nocapture` (and plenty of time and appropriate rustc flags), this should print:
128     // `done, ignored=17643158 passed=2121451881 failed=0`.
129
130     use core::num::flt2dec::strategy::dragon::format_shortest as fallback;
131     f32_exhaustive_equivalence_test(format_shortest_opt, fallback, MAX_SIG_DIGITS);
132 }
133
134 #[test] #[ignore] // it is too expensive
135 fn shortest_f64_hard_random_equivalence_test() {
136     // this again probably has to use appropriate rustc flags.
137
138     use core::num::flt2dec::strategy::dragon::format_shortest as fallback;
139     f64_random_equivalence_test(format_shortest_opt, fallback,
140                                          MAX_SIG_DIGITS, 100_000_000);
141 }
142
143 #[test]
144 fn exact_f32_random_equivalence_test() {
145     use core::num::flt2dec::strategy::dragon::format_exact as fallback;
146     for k in 1..21 {
147         f32_random_equivalence_test(|d, buf| format_exact_opt(d, buf, i16::MIN),
148                                              |d, buf| fallback(d, buf, i16::MIN), k, 1_000);
149     }
150 }
151
152 #[test]
153 fn exact_f64_random_equivalence_test() {
154     use core::num::flt2dec::strategy::dragon::format_exact as fallback;
155     for k in 1..21 {
156         f64_random_equivalence_test(|d, buf| format_exact_opt(d, buf, i16::MIN),
157                                              |d, buf| fallback(d, buf, i16::MIN), k, 1_000);
158     }
159 }
160