Skip to content

Instantly share code, notes, and snippets.

@fuqcool
Created December 15, 2016 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fuqcool/d401cdffe00fecae2008e20f33d8964d to your computer and use it in GitHub Desktop.
Save fuqcool/d401cdffe00fecae2008e20f33d8964d to your computer and use it in GitHub Desktop.
package main
import (
"math/rand"
"runtime"
"fmt"
)
const TEST_COUNT = 100000000
// Calculates PI using Monte-Carlo method
func main() {
numOfCpu := runtime.NumCPU()
c := make(chan int, numOfCpu)
for i := 0; i < numOfCpu; i++ {
go func (n int) {
inside := runner(n)
fmt.Println(inside, "out of", n)
c <- inside
}(TEST_COUNT / numOfCpu)
}
result := make([]int, numOfCpu)
for i := 0; i < numOfCpu; i++ {
result[i] = <-c
}
insideCount := sum(result)
fmt.Println(float64(insideCount) / TEST_COUNT * 4)
}
func sum(a []int) int {
result := 0
for _, n := range a {
result += n
}
return result
}
func runner(n int) int {
count := 0
for i := 0; i < n; i++ {
x := rand.Float64()
y := rand.Float64()
if (x * x + y * y < 1) {
count++
}
}
return count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment