Skip to content

Commit 6358f9a

Browse files
chin123zsparal
authored andcommitted
add Go implementation of monte carlo (#165)
* add Go implementation of monte carlo * Add Go heading before import in monte carlo * Update monteCarlo.go * Update monte_carlo.md
1 parent 908e7b6 commit 6358f9a

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Submitted by Chinmaya Mahesh (chin123)
2+
3+
package main
4+
5+
import (
6+
"fmt"
7+
"math"
8+
"math/rand"
9+
"time"
10+
)
11+
12+
func inCircle(x, y float64) bool {
13+
return x*x+y*y < 1.0 // the radius of an unit circle is 1.0
14+
}
15+
16+
func monteCarlo(samples int) {
17+
count := 0
18+
s := rand.NewSource(time.Now().UnixNano())
19+
r := rand.New(s)
20+
21+
for i := 0; i < samples; i++ {
22+
x, y := r.Float64(), r.Float64()
23+
24+
if inCircle(x, y) {
25+
count += 1
26+
}
27+
}
28+
29+
estimate := 4.0 * float64(count) / float64(samples)
30+
31+
fmt.Println("The estimate of pi is", estimate)
32+
fmt.Printf("Which has an error of %f%%\n", 100*math.Abs(math.Pi-estimate)/math.Pi)
33+
}
34+
35+
func main() {
36+
monteCarlo(10000000)
37+
}

chapters/monte_carlo/monte_carlo.md

+5
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ each point is tested to see whether it's in the circle or not:
4747
[import:7-9, lang:"rust"](code/rust/monte_carlo.rs)
4848
{% sample lang="d" %}
4949
[import:2-5, lang:"d"](code/rust/monte_carlo.d)
50+
{% sample lang="go" %}
51+
[import:12-14, lang:"go"](code/go/monteCarlo.go)
5052
{% endmethod %}
5153

5254
If it's in the circle, we increase an internal count by one, and in the end,
@@ -93,6 +95,9 @@ Feel free to submit your version via pull request, and thanks for reading!
9395
### D
9496
{%sample lang="d" %}
9597
[import, lang:"d"](code/d/monte_carlo.d)
98+
### Go
99+
{%sample lang="go" %}
100+
[import, lang:"go"](code/go/monteCarlo.go)
96101
{% endmethod %}
97102

98103

0 commit comments

Comments
 (0)