Created
April 24, 2019 16:24
-
-
Save aaronjeline/c8f44d1907f29672d2c0c7b4910aefa5 to your computer and use it in GitHub Desktop.
Approximate pi
This file contains hidden or 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
use rand::prelude::*; | |
fn main() { | |
println!("pi = {}", approx(1000000)); | |
} | |
fn approx(count: u64) -> f64 { | |
let mut rng = rand::thread_rng(); | |
let mut circle = 0; | |
for _ in 0..count { | |
let (a,b):(f64,f64) = (rng.gen(),rng.gen()); | |
let (x,y) = (a * 2.0 - 1.0, b * 2.0 - 1.0); | |
if x.powf(2.0) + y.powf(2.0) < 1.0 { | |
circle += 1; | |
} | |
} | |
let ratio = circle as f64 / count as f64; | |
ratio * 4.0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment