]>
git.proxmox.com Git - cargo.git/blob - vendor/rand/examples/monte-carlo.rs
1 // Copyright 2018 Developers of the Rand project.
2 // Copyright 2013-2018 The Rust Project Developers.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 //! # Monte Carlo estimation of π
12 //! Imagine that we have a square with sides of length 2 and a unit circle
13 //! (radius = 1), both centered at the origin. The areas are:
16 //! area of circle = πr² = π * r * r = π
17 //! area of square = 2² = 4
20 //! The circle is entirely within the square, so if we sample many points
21 //! randomly from the square, roughly π / 4 of them should be inside the circle.
23 //! We can use the above fact to estimate the value of π: pick many points in
24 //! the square at random, calculate the fraction that fall within the circle,
25 //! and multiply this fraction by 4.
27 #![cfg(feature = "std")]
29 use rand
::distributions
::{Distribution, Uniform}
;
32 let range
= Uniform
::new(-1.0f64, 1.0);
33 let mut rng
= rand
::thread_rng();
35 let total
= 1_000_000;
36 let mut in_circle
= 0;
39 let a
= range
.sample(&mut rng
);
40 let b
= range
.sample(&mut rng
);
46 // prints something close to 3.14159...
47 println
!("π is approximately {}", 4. * (in_circle
as f64) / (total
as f64));