Skip to content

Instantly share code, notes, and snippets.

@aht
Forked from remogatto/gist:425217
Created June 4, 2010 18:05
Show Gist options
  • Save aht/425738 to your computer and use it in GitHub Desktop.
Save aht/425738 to your computer and use it in GitHub Desktop.
package main
import (
"rand"
"time"
"flag"
"fmt"
)
func getCoord(rg *rand.Rand) float64 {
return -1 + rg.Float64()
}
func countInsidePoints(result chan<- int, iter int) {
inside := 0
rg := rand.New(rand.NewSource(time.Nanoseconds()))
for i := 0; i < iter; i++ {
x, y := getCoord(rg), getCoord(rg)
if (x*x + y*y) < 1.0 {
inside++
}
}
result <- inside
}
func CalcPI(iter, processes int) float64 {
inside := 0
result := make(chan int, processes)
for i := 0; i < processes; i++ {
go countInsidePoints(result, iter)
}
for i := 0; i < processes; i++ {
inside += <-result
}
return 4 * float64(inside) / float64(iter * processes)
}
func main() {
iter := flag.Int("iter", 1000000, "Iterations per process")
processes := flag.Int("processes", 4, "Num of processes")
flag.Parse()
start := time.Nanoseconds()
fmt.Printf("Approx PI value %f calculated in %f ms\n",
CalcPI(*iter, *processes),
float(time.Nanoseconds() - start) / float(10e6))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment