Created
January 19, 2019 06:53
-
-
Save DPS0340/c38b54e6795dce9850c7713868c61912 to your computer and use it in GitHub Desktop.
Obtaining Pi with Monte Carlo Method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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