]>
git.proxmox.com Git - cargo.git/blob - 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.
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.
11 //! # Monte Carlo estimation of π
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:
17 //! area of circle = πr² = π * r * r = π
18 //! area of square = 2² = 4
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.
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.
28 #![cfg(feature="std")]
33 use rand
::distributions
::{Distribution, Uniform}
;
36 let range
= Uniform
::new(-1.0f64, 1.0);
37 let mut rng
= rand
::thread_rng();
39 let total
= 1_000_000;
40 let mut in_circle
= 0;
43 let a
= range
.sample(&mut rng
);
44 let b
= range
.sample(&mut rng
);
50 // prints something close to 3.14159...
51 println
!("π is approximately {}", 4. * (in_circle
as f64) / (total
as f64));