-
-
Save aht/425738 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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