diff --git a/chapters/monte_carlo/code/go/monteCarlo.go b/chapters/monte_carlo/code/go/monteCarlo.go new file mode 100644 index 000000000..bea71ef41 --- /dev/null +++ b/chapters/monte_carlo/code/go/monteCarlo.go @@ -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) +} diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index 846dcc6f6..bbd33671f 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -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, @@ -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 %}