Last active
November 3, 2018 17:54
-
-
Save captainbland/1cbf8928893d40d33254af85c067487b to your computer and use it in GitHub Desktop.
Monte carlo pi estimation in rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate rand; | |
use rand::{thread_rng, Rng}; | |
use std::f64; | |
struct Point { | |
pub x: f64, | |
pub y: f64 | |
} | |
fn point_in_unit_circle(pt: Point) -> bool { | |
let centre = 0.0; | |
let dist = f64::sqrt(pt.x*pt.x+pt.y*pt.y); | |
dist < 1.0 | |
} | |
fn estimate_pi(samples: i32) -> f64 { | |
let mut in_circle:i32 = 0; | |
let mut rng = thread_rng(); | |
for _i in 0..samples { | |
let s_x: f64 = rng.gen_range(-1.00, 1.00); | |
let s_y: f64 = rng.gen_range(-1.00, 1.00); | |
let point = Point{x:s_x, y:s_y}; | |
if point_in_unit_circle(point) { | |
in_circle += 1; | |
} | |
} | |
return ((f64::from(in_circle))/(f64::from(samples)))*4.0; | |
} | |
fn main() { | |
println!("Pi tho"); | |
for pw in 0..8 { | |
println!("10^{} samples: pi={}", pw, estimate_pi(i32::pow(10, pw))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
e.g.
10^0 samples: pi=4
10^1 samples: pi=1.6
10^2 samples: pi=3.28
10^3 samples: pi=3.06
10^4 samples: pi=3.1656
10^5 samples: pi=3.14236
10^6 samples: pi=3.142372
10^7 samples: pi=3.1408304