Advertisement
Stuntkoala

Golang Monte Carlo Pi

May 24th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.14 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "math"
  6.     "math/rand"
  7.     "time"
  8. )
  9.  
  10. const SAMPLES uint64 = 1000000000
  11.  
  12. func main() {
  13.  
  14.     startTime := time.Now()
  15.  
  16.     seed := rand.NewSource(time.Now().UnixNano())
  17.     r := rand.New(seed)
  18.     pointsInside := 0
  19.     var mpi float64
  20.     var x, y float64
  21.  
  22.     var i uint64
  23.     for i = 0; i < SAMPLES; i++ {
  24.         x, y = r.Float64(), r.Float64()
  25.  
  26.         //p = a^2 + b^2 = c^2
  27.         //sqrt not necessary because checking for p^2 > 1 is the same as p > 1
  28.         p2 := x*x + y*y
  29.  
  30.         //check if inside quartercircle
  31.         if p2 < 1 {
  32.             pointsInside++
  33.         }
  34.         mpi = float64(pointsInside*4) / float64(i)
  35.  
  36.         //Print current result every 10000000 samples
  37.         if i > 0 && (i%100000000 == 0) {
  38.             fmt.Printf("\nMontecarlo Pi with %v Samples: %v"+
  39.                 "\nCurrent Error: %v\n", i, mpi, math.Abs(math.Pi-mpi))
  40.         }
  41.     }
  42.  
  43.     //Final Conclusion
  44.     mpi = float64(pointsInside*4) / float64(SAMPLES)
  45.     fmt.Println("\nPoints inside quarter circle:", pointsInside, "of", SAMPLES)
  46.     fmt.Println("Montecarlo Pi with", SAMPLES, "Samples:", mpi)
  47.     fmt.Println("real Pi:", math.Pi)
  48.     fmt.Println("Error:", math.Abs(math.Pi-mpi))
  49.     fmt.Println("Time:", time.Now().Sub(startTime))
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement