Skip to content

Instantly share code, notes, and snippets.

@wcharczuk
Created October 18, 2017 18:02
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 wcharczuk/aa006f37774c5bc1f9ff8881727c75ad to your computer and use it in GitHub Desktop.
Save wcharczuk/aa006f37774c5bc1f9ff8881727c75ad to your computer and use it in GitHub Desktop.
A golang implementation of the napa-js estimate pi example
package main
import (
"fmt"
"math"
"math/rand"
"os"
"sync"
"time"
)
func estimatePi(points float64) float64 {
var i = points
var inside float64
r := rand.New(rand.NewSource(time.Now().UnixNano()))
var x, y float64
for ; i > 0; i-- {
x = r.Float64()
y = r.Float64()
if (x*x)+(y*y) <= 1 {
inside++
}
}
return inside / points * 4
}
func run(points, batches int) (result float64, elapsed time.Duration) {
start := time.Now()
batchSize := float64(points) / float64(batches)
results := make([]float64, batches)
wg := sync.WaitGroup{}
wg.Add(batches)
for i := 0; i < batches; i++ {
go func(index int) {
defer wg.Done()
results[index] = estimatePi(batchSize)
}(i)
}
wg.Wait()
for _, subResult := range results {
result += subResult
}
result = result / float64(batches)
elapsed = time.Since(start)
printResults(points, batches, result, elapsed)
return
}
func printResults(points, batches int, pi float64, elapsed time.Duration) {
fmt.Printf("\t%d\t\t%d\t\t%s\t\t%v\t\t%.7f\t\t%.7f\n", points, batches, os.Getenv("GOMAXPROCS"), elapsed, pi, math.Abs(pi-math.Pi))
}
func main() {
fmt.Printf("\t# of points\t# of batches\t# of workers\tlatency in MS\testimated π\tdeviation\n")
fmt.Printf("\t---------------------------------------------------------------------------------------\n")
run(4000000, 1)
run(4000000, 2)
run(4000000, 4)
run(4000000, 8)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment