Skip to content

Instantly share code, notes, and snippets.

@Brandon-Rozek
Created May 14, 2021 23:56
Show Gist options
  • Save Brandon-Rozek/552ee5084b2317dcb67c3bf94fe3b77c to your computer and use it in GitHub Desktop.
Save Brandon-Rozek/552ee5084b2317dcb67c3bf94fe3b77c to your computer and use it in GitHub Desktop.
Approximation of Pi using Go
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
// Returns the number of successes, to approx pi use formula
// (successes / totalSimulations) * 4
func monteCarloPi(numSimulations int, c chan <- int) {
random := rand.New(rand.NewSource(time.Now().UnixNano()))
successes := 0
for i := 0; i < numSimulations; i++ {
x := random.Float64()
y := random.Float64()
if math.Pow(x,2) + math.Pow(y,2) <= 1 {
successes++
}
}
c <- successes
}
func main() {
start := time.Now()
c := make(chan int)
var successes int
numPerSimulation := 50000000
numSimulations := 5
for i := 0; i < numSimulations; i++ {
go monteCarloPi(numPerSimulation, c)
}
for i:= 0; i < numSimulations; i++ {
successes += <-c
}
fmt.Printf("The approximate value of pi is %v \n", float64(successes) / float64(numSimulations * numPerSimulation) * 4.0)
fmt.Printf("%.2fs total\n", time.Since(start).Seconds())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment