forked from ark-lang/ark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpi_monte_carlo.ark
42 lines (32 loc) · 874 Bytes
/
pi_monte_carlo.ark
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
[c] func printf(fmt: ^u8, ...);
[c] func srand(seed: uint);
[c] func time(ptr: u64) -> uint;
[c] func rand() -> int;
[c] func sqrt(in: f64) -> f64;
func randFloat() -> f64 {
RAND_MAX := 2147483647; // hack for now
return f64(C::rand()) / f64(RAND_MAX);
}
func calculate(iters: int) -> f64 {
radius: f64 = 10.0;
width := radius * 2.0;
mut totalInCircle: u64 = 0;
mut i := 0;
for i < iters {
dx := randFloat() * width - radius;
dy := randFloat() * width - radius;
if C::sqrt(dx*dx+dy*dy) < radius {
totalInCircle += 1;
}
i += 1;
}
return 4.0 * f64(totalInCircle) / f64(iters);
}
pub func main() -> int {
C::srand(C::time(0));
iters := 20000000;
res := calculate(iters);
C::printf(c"Result of Monte Carlo pi estimation with %d iterations:\n", iters);
C::printf(c"%f\n", res);
return 0;
}