Skip to content

Instantly share code, notes, and snippets.

@gdiggs
Created May 4, 2013 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdiggs/5518491 to your computer and use it in GitHub Desktop.
Save gdiggs/5518491 to your computer and use it in GitHub Desktop.
Monte Carlo Tests to Calculate Pi in Go
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