Skip to content

Instantly share code, notes, and snippets.

@aaronjeline
Created April 24, 2019 16:24
Show Gist options
  • Save aaronjeline/c8f44d1907f29672d2c0c7b4910aefa5 to your computer and use it in GitHub Desktop.
Save aaronjeline/c8f44d1907f29672d2c0c7b4910aefa5 to your computer and use it in GitHub Desktop.
Approximate pi
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