Skip to content

Instantly share code, notes, and snippets.

@DPS0340
Created January 19, 2019 06:53
Show Gist options
  • Save DPS0340/c38b54e6795dce9850c7713868c61912 to your computer and use it in GitHub Desktop.
Save DPS0340/c38b54e6795dce9850c7713868c61912 to your computer and use it in GitHub Desktop.
Obtaining Pi with Monte Carlo Method
package main
import "fmt"
import "math/rand"
import "sync"
func main() {
var wg sync.WaitGroup
length := 1.0
oncircle := 0
onsquare := 0
try := 10000000
randomdot := func(maxLength float64) {
defer wg.Done()
x := rand.Float64() * maxLength
y := rand.Float64() * maxLength
if x*x + y*y > maxLength*maxLength {
onsquare++
} else {
oncircle++
}
}
for i := 0; i<try; i++ {
wg.Add(1)
go randomdot(length)
}
wg.Wait()
fmt.Println(onsquare)
fmt.Println(oncircle)
fmt.Println((float64(oncircle) / float64(onsquare + oncircle)) * 4.0 / (length * length))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment