Skip to content

Instantly share code, notes, and snippets.

@RabeaWahab
Created May 22, 2015 19:06
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 RabeaWahab/b2a305c2f65bc383965c to your computer and use it in GitHub Desktop.
Save RabeaWahab/b2a305c2f65bc383965c to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"time"
"runtime"
)
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
rand.Seed(time.Now().UnixNano())
}
func MultiPI(samples int) float64 {
cpus := runtime.NumCPU()
threadSamples := samples / cpus
results := make(chan float64, cpus)
fmt.Println(cpus);
for j := 0; j < cpus; j++ {
go func() {
var inside int
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < threadSamples; i++ {
x, y := r.Float64(), r.Float64()
if x*x+y*y <= 1 {
inside++
}
}
results <- float64(inside) / float64(threadSamples) * 4
}()
}
var total float64
for i := 0; i < cpus; i++ {
total += <-results
}
return total / float64(cpus)
}
func main () {
fmt.Println(MultiPI(1000000000))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment