Skip to content

Commit 5305f9b

Browse files
committed
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.
2 parents 20b3313 + 8658722 commit 5305f9b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/libstd/rand/mod.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,49 @@
7070
//! println!("{}", tuple)
7171
//! ```
7272
//!
73+
//! ## Monte Carlo estimation of π
74+
//!
75+
//! For this example, imagine we have a square with sides of length 2 and a unit
76+
//! circle, both centered at the origin. Since the area of a unit circle is π,
77+
//! we have:
78+
//!
79+
//! ```notrust
80+
//! (area of unit circle) / (area of square) = π / 4
81+
//! ```
82+
//!
83+
//! So if we sample many points randomly from the square, roughly π / 4 of them
84+
//! should be inside the circle.
85+
//!
86+
//! We can use the above fact to estimate the value of π: pick many points in the
87+
//! square at random, calculate the fraction that fall within the circle, and
88+
//! multiply this fraction by 4.
89+
//!
90+
//! ```
91+
//! use std::rand;
92+
//! use std::rand::distributions::{IndependentSample, Range};
93+
//!
94+
//! fn main() {
95+
//! let between = Range::new(-1f64, 1.);
96+
//! let mut rng = rand::task_rng();
97+
//!
98+
//! let total = 1_000_000u;
99+
//! let mut in_circle = 0u;
100+
//!
101+
//! for _ in range(0u, total) {
102+
//! let a = between.ind_sample(&mut rng);
103+
//! let b = between.ind_sample(&mut rng);
104+
//! if a*a + b*b <= 1. {
105+
//! in_circle += 1;
106+
//! }
107+
//! }
108+
//!
109+
//! // prints something close to 3.14159...
110+
//! println!("{}", 4. * (in_circle as f64) / (total as f64));
111+
//! }
112+
//! ```
113+
//!
114+
//! ## Monty Hall Problem
115+
//!
73116
//! This is a simulation of the [Monty Hall Problem][]:
74117
//!
75118
//! > Suppose you're on a game show, and you're given the choice of three doors:

0 commit comments

Comments
 (0)