Created
December 15, 2016 22:20
-
-
Save fuqcool/d401cdffe00fecae2008e20f33d8964d to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"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