Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "context"
- "log"
- "math/rand"
- "runtime"
- "sync"
- "time"
- )
- var timeout = 3 * time.Second
- var worker = runtime.GOMAXPROCS(0)
- // pi = 4 * P(l <= r)
- func main() {
- // trace.Start(os.Stdout)
- // defer trace.Stop()
- // f, err := os.Create("cpuprofile")
- // if err != nil {
- // panic(err)
- // }
- // err = pprof.StartCPUProfile(f)
- // if err != nil {
- // panic(err)
- // }
- // defer pprof.StopCPUProfile()
- wg := sync.WaitGroup{}
- ctx, _ := context.WithTimeout(context.Background(), timeout)
- inCh, totalCh := make(chan int, worker), make(chan int, worker)
- for i := 0; i < worker; i++ {
- wg.Add(1)
- r := rand.New(rand.NewSource(time.Now().UnixNano()))
- go func() {
- defer wg.Done()
- in, total := 0, 0
- for i := 0; ; i++ {
- if i%1000 == 0 {
- select {
- case <-ctx.Done():
- inCh <- in
- totalCh <- total
- return
- default:
- }
- }
- total++
- x, y := r.Float64(), r.Float64()
- if isIn(x, y) {
- in++
- }
- }
- }()
- }
- wg.Wait()
- in, total := 0, 0
- close(inCh)
- close(totalCh)
- for v := range inCh {
- in += v
- }
- for v := range totalCh {
- total += v
- }
- log.Printf("pi is %5f, sample size is %d", float64(in)/float64(total)*4, total)
- }
- func isIn(x, y float64) bool {
- return x*x+y*y <= 1
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement