Skip to content

Instantly share code, notes, and snippets.

@remogatto
Created June 4, 2010 09:42
Show Gist options
  • Save remogatto/425217 to your computer and use it in GitHub Desktop.
Save remogatto/425217 to your computer and use it in GitHub Desktop.
PI parallel computation
// Parallel algorithm for PI calculation
//
// Sources of inspiration:
//
// * https://computing.llnl.gov/tutorials/parallel_comp/#ExamplesPI
// * http://dos.iitm.ac.in/Vishwa/GCCourse/suneetha/picalc.html
//
// Thanks to aht for fixing the random generator issue:
// http://groups.google.com/group/golang-nuts/browse_thread/thread/f5c12ca69b46a931
package main
import (
"rand"
"time"
"flag"
"fmt"
)
func getCoord(rg *rand.Rand) float64 {
return -1 + rg.Float64()
}
func calcPartialPI(result chan<- float64, iter int) {
var circle, i int
rg := rand.New(rand.NewSource(time.Nanoseconds() % 1e9))
for i = 0; i < iter; i++ {
x, y := getCoord(rg), getCoord(rg)
if (x*x + y*y) < 1.0 {
circle++
}
}
result <- 4 * float64(circle) / float64(i)
}
func CalcPI(iter, processes int) float64 {
var acc float64
result := make(chan float64, processes)
for i := 0; i < processes; i++ {
go calcPartialPI(result, iter)
}
for i := 0; i < processes; i++ {
acc += <-result
}
return acc / float64(processes)
}
func main() {
iter := flag.Int("iter", 5000, "Iterations per process")
processes := flag.Int("processes", 100, "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