Skip to content

Commit d6109e7

Browse files
authored
Monte Carlo Pi algorithm
add Monte Carlo Pi algorithm
2 parents e04399c + 6b3e780 commit d6109e7

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Monte Carlo Pi
2+
// [Monte Carlo method](https://en.wikipedia.org/wiki/Monte_Carlo_method) to calculate Pi
3+
//
4+
// The basic idea of Monte Carlo is:
5+
// 1. Define a domain of possible inputs
6+
// 2. Generate inputs randomly from a probability distribution over the domain
7+
// 3. Perform a deterministic computation on the inputs
8+
// 4. Aggregate the results
9+
//
10+
// Thus the algorithm to calculate Pi is:
11+
//
12+
// 1. Given a circle inscribed in a square with side length 1.
13+
// 2. randomly draw n points (x, y) | x,y in [0.0,1.0)
14+
// 3. Count the amount of points inside the circle
15+
// 4. pi = 4 * (points inside the circle) / n
16+
//
17+
// A point (x, y) is inside the circle if:
18+
//
19+
// x*x + y*y <= 1
20+
//
21+
22+
package main
23+
24+
import (
25+
"math"
26+
"math/rand"
27+
)
28+
29+
// MonteCarloPi calculates Pi using the Monte Carlo method
30+
func MonteCarloPi(iterations uint) float64 {
31+
var inside, total uint
32+
33+
for total = uint(0); total < iterations; total++ {
34+
if in := math.Hypot(rand.Float64(), rand.Float64()) <= 1; in {
35+
inside++
36+
}
37+
}
38+
39+
return float64(4) * (float64(inside) / float64(total))
40+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package main
2+
3+
import (
4+
"math"
5+
"testing"
6+
)
7+
8+
func TestMonteCarloPi(t *testing.T) {
9+
delta := 0.0001
10+
11+
pi := MonteCarloPi(100000000)
12+
13+
if math.Abs(pi-math.Pi) > delta {
14+
t.Errorf("Given: %.4f, expected: %.4f", pi, math.Pi)
15+
}
16+
}

0 commit comments

Comments
 (0)