Skip to content

Instantly share code, notes, and snippets.

@jstiehl
Created August 30, 2019 23:25
Show Gist options
  • Save jstiehl/3b7edababd7de2a8d093335d764aa8f3 to your computer and use it in GitHub Desktop.
Save jstiehl/3b7edababd7de2a8d093335d764aa8f3 to your computer and use it in GitHub Desktop.
Estimate Pi by randomly generating points in a 1x1 square and finding fraction of points that fall within a 1/4 circle of radius 1
package main
import (
"fmt"
"math"
"math/rand"
)
func main() {
converged := false
inRange := 0
total := 0
for !converged {
// generate random point in a 1x1 square
x := rand.Float64()
y := rand.Float64()
//find distance of point from origin (0,0)
d := math.Sqrt(x*x + y*y)
// check to see if random point falls within circle of radius 1
if d <= 1 {
inRange++
}
total++
// calculate Pi estimate from area of quarter circle. 4*Area of Quarter circle = Pi
// if estimaate is within 5 decimal places of actual value stop loop
if math.Abs(4*float64(inRange)/float64(total) - math.Pi) < 0.00001 {
converged = true
}
}
piEstimate := 4*float64(inRange)/float64(total)
fmt.Println(piEstimate)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment