Skip to content

Added a rust version of the monte carlo example #147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 28, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions chapters/monte_carlo/code/rust/monte_carlo.rs
Original file line number Diff line number Diff line change
@@ -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));
}
3 changes: 3 additions & 0 deletions chapters/monte_carlo/monte_carlo.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 %}


Expand Down