diff options
| author | nham <hamann.nick@gmail.com> | 2014-08-08 15:37:06 -0400 |
|---|---|---|
| committer | nham <hamann.nick@gmail.com> | 2014-08-08 15:37:06 -0400 |
| commit | 3bd158c665f7f464ed9e0d5b02a408eedbf4d610 (patch) | |
| tree | a42766c971afb02cf597422b7530feca7e0c7a70 | |
| parent | ca89cfb0e3ea96116c01ec4c11f36a0b504ccde1 (diff) | |
| download | rust-3bd158c665f7f464ed9e0d5b02a408eedbf4d610.tar.gz rust-3bd158c665f7f464ed9e0d5b02a408eedbf4d610.zip | |
Add example of estimating pi using Monte Carlo simulation to std::rand
| -rw-r--r-- | src/libstd/rand/mod.rs | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index 40d8f80171c..06b9b464ebd 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -70,6 +70,51 @@ //! println!("{}", tuple) //! ``` //! +//! ## Monte Carlo estimation of pi +//! +//! For this example, imagine we have a square with sides of length 2 and a unit +//! circle, both centered at the origin. Since the area of a unit circle is pi, +//! the ratio +//! +//! (area of unit circle) / (area of square) +//! +//! is equal to pi / 4. So if we sample many points randomly from the square, +//! roughly pi / 4 of them should be inside the circle. +//! +//! We can use the above fact to estimate the value of pi: pick many points in the +//! square at random, calculate the fraction that fall within the circle, and +//! multiply this fraction by 4. +//! +//! ``` +//! use std::rand; +//! use std::rand::distributions::{IndependentSample, Range}; +//! +//! fn dist(x: f64, y: f64) -> f64 { +//! (x*x + y*y).sqrt() +//! } +//! +//! fn main() { +//! let between = Range::new(-1f64, 1.); +//! let mut rng = rand::task_rng(); +//! +//! let total = 1_000_000u; +//! let mut in_circle = 0u; +//! +//! for _ in range(0u, total) { +//! let a = between.ind_sample(&mut rng); +//! let b = between.ind_sample(&mut rng); +//! if dist(a, b) <= 1. { +//! in_circle += 1; +//! } +//! } +//! +//! // prints something close to 3.14159... +//! println!("{}", 4. * (in_circle as f64) / (total as f64)); +//! } +//! ``` +//! +//! ## Monty Hall Problem +//! //! This is a simulation of the [Monty Hall Problem][]: //! //! > Suppose you're on a game show, and you're given the choice of three doors: |
