]> git.proxmox.com Git - cargo.git/blob - vendor/rand-0.5.6/examples/monte-carlo.rs
New upstream version 0.33.0
[cargo.git] / vendor / rand-0.5.6 / examples / monte-carlo.rs
1 // Copyright 2013-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // https://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or https://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 //! # Monte Carlo estimation of π
12 //!
13 //! Imagine that we have a square with sides of length 2 and a unit circle
14 //! (radius = 1), both centered at the origin. The areas are:
15 //!
16 //! ```text
17 //! area of circle = πr² = π * r * r = π
18 //! area of square = 2² = 4
19 //! ```
20 //!
21 //! The circle is entirely within the square, so if we sample many points
22 //! randomly from the square, roughly π / 4 of them should be inside the circle.
23 //!
24 //! We can use the above fact to estimate the value of π: pick many points in
25 //! the square at random, calculate the fraction that fall within the circle,
26 //! and multiply this fraction by 4.
27
28 #![cfg(feature="std")]
29
30
31 extern crate rand;
32
33 use rand::distributions::{Distribution, Uniform};
34
35 fn main() {
36 let range = Uniform::new(-1.0f64, 1.0);
37 let mut rng = rand::thread_rng();
38
39 let total = 1_000_000;
40 let mut in_circle = 0;
41
42 for _ in 0..total {
43 let a = range.sample(&mut rng);
44 let b = range.sample(&mut rng);
45 if a*a + b*b <= 1.0 {
46 in_circle += 1;
47 }
48 }
49
50 // prints something close to 3.14159...
51 println!("π is approximately {}", 4. * (in_circle as f64) / (total as f64));
52 }