Skip to content

add Go implementation of monte carlo #165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions chapters/monte_carlo/code/go/monteCarlo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Submitted by Chinmaya Mahesh (chin123)

package main

import (
"fmt"
"math"
"math/rand"
"time"
)

func inCircle(x, y float64) bool {
return x*x+y*y < 1.0 // the radius of an unit circle is 1.0
}

func monteCarlo(samples int) {
count := 0
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)

for i := 0; i < samples; i++ {
x, y := r.Float64(), r.Float64()

if inCircle(x, y) {
count += 1
}
}

estimate := 4.0 * float64(count) / float64(samples)

fmt.Println("The estimate of pi is", estimate)
fmt.Printf("Which has an error of %f%%\n", 100*math.Abs(math.Pi-estimate)/math.Pi)
}

func main() {
monteCarlo(10000000)
}
5 changes: 5 additions & 0 deletions chapters/monte_carlo/monte_carlo.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ each point is tested to see whether it's in the circle or not:
[import:7-9, lang:"rust"](code/rust/monte_carlo.rs)
{% sample lang="d" %}
[import:2-5, lang:"d"](code/rust/monte_carlo.d)
{% sample lang="go" %}
[import:12-14, lang:"go"](code/go/monteCarlo.go)
{% endmethod %}

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


Expand Down