Skip to content

Commit 3bd158c

Browse files
committed
Add example of estimating pi using Monte Carlo simulation to std::rand
1 parent ca89cfb commit 3bd158c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/libstd/rand/mod.rs

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

0 commit comments

Comments
 (0)