diff --git a/chapters/monte_carlo/code/rust/monte_carlo.rs b/chapters/monte_carlo/code/rust/monte_carlo.rs new file mode 100644 index 000000000..add6b0678 --- /dev/null +++ b/chapters/monte_carlo/code/rust/monte_carlo.rs @@ -0,0 +1,30 @@ +// Submitted by jess 3jane + +extern crate rand; + +use std::f64::consts::PI; + +fn in_circle(x: f64, y: f64, radius: f64) -> bool { + x * x + y * y < radius * radius +} + +fn monte_carlo(n: i64) -> f64 { + let mut count = 0; + + for _ in 0..n { + let x = rand::random(); + let y = rand::random(); + if in_circle(x, y, 1.0) { + count += 1; + } + } + + // return our pi estimate + (4 * count) as f64 / n as f64 +} + +fn main() { + let pi_estimate = monte_carlo(10000000); + + println!("Percent error is {:.3}%", (100.0 * (PI - pi_estimate) / PI)); +} diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index f7e9290a1..1d838f285 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -78,6 +78,9 @@ Feel free to submit your version via pull request, and thanks for reading! {% sample lang="hs" %} ### Haskell [import, lang:"haskell"](code/haskell/monteCarlo.hs) +{%sample lang="rs" %} +### Rust +[import, lang:"rust"](code/rust/monte_carlo.rs) {% endmethod %}