Created
May 4, 2013 19:34
-
-
Save gdiggs/5518491 to your computer and use it in GitHub Desktop.
Monte Carlo Tests to Calculate Pi in Go
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 ( | |
"flag" | |
"fmt" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
var ( | |
circle_area = 0.0 | |
square_area = 0.0 | |
m sync.Mutex | |
wg sync.WaitGroup | |
trials = flag.Int("t", 10000, "number of trials to perform") | |
) | |
func one_test() { | |
x := rand.Float32() | |
y := rand.Float32() | |
if ((x * x) + (y * y)) < 1 { | |
m.Lock() | |
circle_area += 1 | |
m.Unlock() | |
} | |
m.Lock() | |
square_area += 1 | |
m.Unlock() | |
wg.Done() | |
} | |
func main() { | |
flag.Parse() | |
t0 := time.Now() | |
for i := 0; i < *trials; i++ { | |
wg.Add(1) | |
go one_test() | |
} | |
wg.Wait() | |
pi := 4.0 * (circle_area / square_area) | |
t1 := time.Now() | |
fmt.Println("Approximate value of pi:", pi) | |
fmt.Printf("Calculated %d trials in %v.\n", trials, t1.Sub(t0)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment