SHARE
TWEET

Untitled

a guest Jan 18th, 2020 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "context"
  5.     "log"
  6.     "math/rand"
  7.     "runtime"
  8.     "sync"
  9.     "time"
  10. )
  11.  
  12. var timeout = 3 * time.Second
  13.  
  14. var worker = runtime.GOMAXPROCS(0)
  15.  
  16. // pi = 4 * P(l <= r)
  17. func main() {
  18.     // trace.Start(os.Stdout)
  19.     // defer trace.Stop()
  20.  
  21.     // f, err := os.Create("cpuprofile")
  22.     // if err != nil {
  23.     //  panic(err)
  24.     // }
  25.     // err = pprof.StartCPUProfile(f)
  26.     // if err != nil {
  27.     //  panic(err)
  28.     // }
  29.     // defer pprof.StopCPUProfile()
  30.     wg := sync.WaitGroup{}
  31.     ctx, _ := context.WithTimeout(context.Background(), timeout)
  32.     inCh, totalCh := make(chan int, worker), make(chan int, worker)
  33.     for i := 0; i < worker; i++ {
  34.         wg.Add(1)
  35.         r := rand.New(rand.NewSource(time.Now().UnixNano()))
  36.         go func() {
  37.             defer wg.Done()
  38.             in, total := 0, 0
  39.             for i := 0; ; i++ {
  40.                 if i%1000 == 0 {
  41.                     select {
  42.                     case <-ctx.Done():
  43.                         inCh <- in
  44.                         totalCh <- total
  45.                         return
  46.                     default:
  47.                     }
  48.                 }
  49.                 total++
  50.                 x, y := r.Float64(), r.Float64()
  51.                 if isIn(x, y) {
  52.                     in++
  53.                 }
  54.             }
  55.         }()
  56.     }
  57.     wg.Wait()
  58.     in, total := 0, 0
  59.     close(inCh)
  60.     close(totalCh)
  61.     for v := range inCh {
  62.         in += v
  63.     }
  64.     for v := range totalCh {
  65.         total += v
  66.     }
  67.     log.Printf("pi is %5f, sample size is %d", float64(in)/float64(total)*4, total)
  68. }
  69.  
  70. func isIn(x, y float64) bool {
  71.     return x*x+y*y <= 1
  72. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top