|
70 | 70 | //! println!("{}", tuple)
|
71 | 71 | //! ```
|
72 | 72 | //!
|
| 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 | +//! |
73 | 116 | //! This is a simulation of the [Monty Hall Problem][]:
|
74 | 117 | //!
|
75 | 118 | //! > Suppose you're on a game show, and you're given the choice of three doors:
|
|
0 commit comments