Created
May 14, 2021 23:56
-
-
Save Brandon-Rozek/552ee5084b2317dcb67c3bf94fe3b77c to your computer and use it in GitHub Desktop.
Approximation of Pi using Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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