Commits

John Floren committed 7f94218

added trivial pi calculation example, serial and parallel

Comments (0)

Files changed (2)

+package main
+
+import (
+	"fmt"
+	"flag"
+	"math/rand"
+	"time"
+)
+
+var nproc = flag.Int("nproc", 10, "Number of goroutines to spawn")
+
+func main() {
+	flag.Parse()
+
+	npoints := 100000000
+	circle_count := 0
+
+	done := make(chan int, *nproc)
+
+	start := time.Now()
+	for i := 0; i < *nproc; i++ {
+		go func(n, seed int, done chan int){
+			r := rand.New(rand.NewSource(int64(seed)))
+			fmt.Printf("starting to calculate %v points\n", n)
+			count := 0
+			for i := 0; i < n; i++ {
+				x := r.Float64()
+				y := r.Float64()
+
+				if ((x*x) + (y*y)) <= 1.0 {
+					count++
+				}
+			}
+			done<- count
+		}(npoints/(*nproc), i, done)
+	}
+	for i := 0; i < *nproc; i++ {
+		circle_count += <-done
+	}
+	end := time.Now()
+
+	pi := 4.0 * float64(circle_count)/float64(npoints)
+	fmt.Printf("Pi is %v, took %v to run\n", pi, end.Sub(start))
+}
+package main
+
+import (
+	"fmt"
+	"math/rand"
+	"time"
+)
+
+func main() {
+	npoints := 100000000
+	circle_count := 0
+
+	start := time.Now()
+	for i := 0; i < npoints; i++ {
+		x := rand.Float64()
+		y := rand.Float64()
+
+		if ((x*x) + (y*y)) <= 1.0 {
+			circle_count++
+		}
+	}
+	end := time.Now()
+
+	pi := 4.0 * float64(circle_count)/float64(npoints)
+	fmt.Printf("Pi is %v, took %v to run\n", pi, end.Sub(start))
+}