Skip to content

Instantly share code, notes, and snippets.

@geekynils
Created January 5, 2014 17:30
Show Gist options
  • Save geekynils/8271156 to your computer and use it in GitHub Desktop.
Save geekynils/8271156 to your computer and use it in GitHub Desktop.
Calculating Pi..
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func calcPiRandom(nPoints int) float64 {
rand.Seed(time.Now().UTC().UnixNano())
// In- or outside of the circle.
var nPointsInside int = 0
var nPointsOutside int = 0
for i := 0; i < nPoints; i++ {
x, y := rand.Float64(), rand.Float64()
if x*x+y*y < 1 {
nPointsInside++
} else {
nPointsOutside++
}
}
areaRatio := float64(nPointsInside) / float64(nPointsInside+nPointsOutside)
// Note that areaRatio = (Pi*r^2) / (4*r^2)
// So: 4 * areaRatio = Pi
Pi := 4 * areaRatio
return Pi
}
func calcPi(nPoints int) float64 {
a := math.Sqrt(float64(nPoints))
var stepSize float64 = 1.0 / a
var nPointsInside int = 0
var nPointsOutside int = 0
for x := 0.0; x < 1; x += stepSize {
for y := 0.0; y < 1; y += stepSize {
if x*x+y*y < 1 {
nPointsInside++
} else {
nPointsOutside++
}
}
}
areaRatio := float64(nPointsInside) / float64(nPointsInside+nPointsOutside)
return 4 * areaRatio
}
func main() {
fmt.Printf("Iteratively calculated Pi %f\n", calcPi(10000))
fmt.Printf("Randomly calculated Pi %f\n", calcPiRandom(1000000))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment