Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "math"
- "math/rand"
- "time"
- )
- const SAMPLES uint64 = 1000000000
- func main() {
- startTime := time.Now()
- seed := rand.NewSource(time.Now().UnixNano())
- r := rand.New(seed)
- pointsInside := 0
- var mpi float64
- var x, y float64
- var i uint64
- for i = 0; i < SAMPLES; i++ {
- x, y = r.Float64(), r.Float64()
- //p = a^2 + b^2 = c^2
- //sqrt not necessary because checking for p^2 > 1 is the same as p > 1
- p2 := x*x + y*y
- //check if inside quartercircle
- if p2 < 1 {
- pointsInside++
- }
- mpi = float64(pointsInside*4) / float64(i)
- //Print current result every 10000000 samples
- if i > 0 && (i%100000000 == 0) {
- fmt.Printf("\nMontecarlo Pi with %v Samples: %v"+
- "\nCurrent Error: %v\n", i, mpi, math.Abs(math.Pi-mpi))
- }
- }
- //Final Conclusion
- mpi = float64(pointsInside*4) / float64(SAMPLES)
- fmt.Println("\nPoints inside quarter circle:", pointsInside, "of", SAMPLES)
- fmt.Println("Montecarlo Pi with", SAMPLES, "Samples:", mpi)
- fmt.Println("real Pi:", math.Pi)
- fmt.Println("Error:", math.Abs(math.Pi-mpi))
- fmt.Println("Time:", time.Now().Sub(startTime))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement