Skip to content

Commit 87f185c

Browse files
authored
Add monte carlo pi calculation (#354)
1 parent 40a975f commit 87f185c

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

math/pi/montecarlopi.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// montecarlopi.go
2+
// description: Calculating pi by the Monte Carlo method
3+
// details:
4+
// implementation of Monte Carlo Algorithm for the calculating of Pi - [Monte Carlo method](https://en.wikipedia.org/wiki/Monte_Carlo_method)
5+
// author(s) [red_byte](https://github.com/i-redbyte)
6+
// see montecarlopi_test.go
7+
8+
package pi
9+
10+
import (
11+
"math/rand"
12+
"time"
13+
)
14+
15+
func MonteCarloPi(randomPoints int) float64 {
16+
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
17+
inside := 0
18+
for i := 0; i < randomPoints; i++ {
19+
x := rnd.Float64()
20+
y := rnd.Float64()
21+
if x*x+y*y <= 1 {
22+
inside += 1
23+
}
24+
}
25+
pi := float64(inside) / float64(randomPoints) * float64(4)
26+
return pi
27+
}

math/pi/montecarlopi_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// montecarlopi_test.go
2+
// description: Test for calculating pi by the Monte Carlo method
3+
// author(s) [red_byte](https://github.com/i-redbyte)
4+
// see montecarlopi.go
5+
6+
package pi
7+
8+
import (
9+
"fmt"
10+
"testing"
11+
)
12+
13+
func TestMonteCarloPi(t *testing.T) {
14+
t.Run("Monte Carlo Pi", func(t *testing.T) {
15+
result := fmt.Sprintf("%.2f", MonteCarloPi(100000000))
16+
t.Log(result)
17+
if result != "3.14" {
18+
t.Errorf("Wrong result! Expected:%f, returned:%s ", 3.1415, result)
19+
}
20+
})
21+
}
22+
23+
func BenchmarkMonteCarloPi(b *testing.B) {
24+
for i := 0; i < b.N; i++ {
25+
MonteCarloPi(100000000)
26+
}
27+
}

0 commit comments

Comments
 (0)