Skip to content

Instantly share code, notes, and snippets.

@corona10
Created June 11, 2017 06:13
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 corona10/f8dc947c19c3d9644280b420184148f1 to your computer and use it in GitHub Desktop.
Save corona10/f8dc947c19c3d9644280b420184148f1 to your computer and use it in GitHub Desktop.
gopy: getpi
package calculatePi
import (
"math"
"math/rand"
"runtime"
"sync"
"time"
)
func monte_carlo_pi(reps int, result *int, wait *sync.WaitGroup) {
var x, y float64
count := 0
seed := rand.NewSource(time.Now().UnixNano())
random := rand.New(seed)
for i := 0; i < reps; i++ {
x = random.Float64() * 1.0
y = random.Float64() * 1.0
if num := math.Sqrt(x*x + y*y); num < 1.0 {
count++
}
}
*result = count
wait.Done()
}
func GetPI(samples int) float64 {
cores := runtime.NumCPU()
runtime.GOMAXPROCS(cores)
var wait sync.WaitGroup
counts := make([]int, cores)
wait.Add(cores)
for i := 0; i < cores; i++ {
go monte_carlo_pi(samples/cores, &counts[i], &wait)
}
wait.Wait()
total := 0
for i := 0; i < cores; i++ {
total += counts[i]
}
pi := (float64(total) / float64(samples)) * 4
return pi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment