Skip to content

Commit 45270ad

Browse files
authored
Merge pull request #147 from Jess3Jane/master
Added a rust version of the monte carlo example
2 parents 548a33c + 018eec7 commit 45270ad

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Submitted by jess 3jane
2+
3+
extern crate rand;
4+
5+
use std::f64::consts::PI;
6+
7+
fn in_circle(x: f64, y: f64, radius: f64) -> bool {
8+
x * x + y * y < radius * radius
9+
}
10+
11+
fn monte_carlo(n: i64) -> f64 {
12+
let mut count = 0;
13+
14+
for _ in 0..n {
15+
let x = rand::random();
16+
let y = rand::random();
17+
if in_circle(x, y, 1.0) {
18+
count += 1;
19+
}
20+
}
21+
22+
// return our pi estimate
23+
(4 * count) as f64 / n as f64
24+
}
25+
26+
fn main() {
27+
let pi_estimate = monte_carlo(10000000);
28+
29+
println!("Percent error is {:.3}%", (100.0 * (PI - pi_estimate) / PI));
30+
}

chapters/monte_carlo/monte_carlo.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,9 @@ Feel free to submit your version via pull request, and thanks for reading!
7878
{% sample lang="hs" %}
7979
### Haskell
8080
[import, lang:"haskell"](code/haskell/monteCarlo.hs)
81+
{%sample lang="rs" %}
82+
### Rust
83+
[import, lang:"rust"](code/rust/monte_carlo.rs)
8184
{% endmethod %}
8285

8386

0 commit comments

Comments
 (0)