diff options
| author | bors <bors@rust-lang.org> | 2014-08-21 07:50:55 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2014-08-21 07:50:55 +0000 |
| commit | 5305f9b89419b2b31e00fc69bf9cc90469cbbc41 (patch) | |
| tree | cc8062243ba65a4c3a6dd6baa54a76cc752c1f37 /src/libstd | |
| parent | 20b3313c8c14a8f7ee29215734b26f79b4f2b2a4 (diff) | |
| parent | 86587224d0b99c69da01ebfaf98052694036302b (diff) | |
| download | rust-5305f9b89419b2b31e00fc69bf9cc90469cbbc41.tar.gz rust-5305f9b89419b2b31e00fc69bf9cc90469cbbc41.zip | |
auto merge of #16362 : nham/rust/std_rand_pi_example, r=huonw
Pros: I like this example because it's concise without being trivial. The Monty Hall example code is somewhat lengthy and possibly inaccessible to those unfamiliar with probability. Cons: The Monty Hall example already exists. Do we need another example? Also, this is probably inaccessible to people who don't know basic geometry.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/rand/mod.rs | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index c02a97e09a4..b7bf75e39a5 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -70,6 +70,49 @@ //! println!("{}", tuple) //! ``` //! +//! ## Monte Carlo estimation of π +//! +//! 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 π, +//! we have: +//! +//! ```notrust +//! (area of unit circle) / (area of square) = π / 4 +//! ``` +//! +//! So if we sample many points randomly from the square, roughly π / 4 of them +//! should be inside the circle. +//! +//! We can use the above fact to estimate the value of π: 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 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 a*a + b*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: |
