]>
Commit | Line | Data |
---|---|---|
0731742a XL |
1 | // Copyright 2018 Developers of the Rand project. |
2 | // Copyright 2013-2018 The Rust Project Developers. | |
b7449926 XL |
3 | // |
4 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
5 | // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
6 | // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your | |
7 | // option. This file may not be copied, modified, or distributed | |
8 | // except according to those terms. | |
9 | ||
10 | //! # Monte Carlo estimation of π | |
11 | //! | |
12 | //! Imagine that we have a square with sides of length 2 and a unit circle | |
13 | //! (radius = 1), both centered at the origin. The areas are: | |
416331ca | 14 | //! |
b7449926 XL |
15 | //! ```text |
16 | //! area of circle = πr² = π * r * r = π | |
17 | //! area of square = 2² = 4 | |
18 | //! ``` | |
19 | //! | |
20 | //! The circle is entirely within the square, so if we sample many points | |
21 | //! randomly from the square, roughly π / 4 of them should be inside the circle. | |
22 | //! | |
23 | //! We can use the above fact to estimate the value of π: pick many points in | |
24 | //! the square at random, calculate the fraction that fall within the circle, | |
25 | //! and multiply this fraction by 4. | |
26 | ||
416331ca | 27 | #![cfg(feature = "std")] |
b7449926 XL |
28 | |
29 | use rand::distributions::{Distribution, Uniform}; | |
30 | ||
31 | fn main() { | |
416331ca XL |
32 | let range = Uniform::new(-1.0f64, 1.0); |
33 | let mut rng = rand::thread_rng(); | |
34 | ||
35 | let total = 1_000_000; | |
36 | let mut in_circle = 0; | |
37 | ||
38 | for _ in 0..total { | |
39 | let a = range.sample(&mut rng); | |
40 | let b = range.sample(&mut rng); | |
dfeec247 | 41 | if a * a + b * b <= 1.0 { |
416331ca XL |
42 | in_circle += 1; |
43 | } | |
44 | } | |
45 | ||
46 | // prints something close to 3.14159... | |
dfeec247 XL |
47 | println!( |
48 | "π is approximately {}", | |
49 | 4. * (in_circle as f64) / (total as f64) | |
50 | ); | |
b7449926 | 51 | } |