Skip to content

Instantly share code, notes, and snippets.

@MattSurabian
Created August 10, 2015 22:57
Show Gist options
  • Save MattSurabian/aa3eafd1ba8955535e2e to your computer and use it in GitHub Desktop.
Save MattSurabian/aa3eafd1ba8955535e2e to your computer and use it in GitHub Desktop.
Monte Carlo experiment in Go
package main
import (
"time"
"math/rand"
"fmt"
)
func main() {
startTime := time.Now()
fmt.Print("How many trials: ")
var trials int
_, err := fmt.Scanf("%d", &trials)
if err != nil {
panic(err)
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
var hits int = 0
var numQuarters int = 8
var quarterDelta float32 = 6.667
var quarterRadius float32 = 1.213
var dimeRadius float32 = 0.895
var quarterLocations [8] float32
for i := 0; i < numQuarters; i++ {
quarterLocations[i] = float32(i + 1) * quarterDelta
}
for k := 0; k < trials; k++ {
var startPoint float32 = float32(r.Intn(60))
var dimeL float32 = startPoint - dimeRadius
var dimeR float32 = startPoint + dimeRadius
for j := 0; j < numQuarters; j++ {
var quarterL float32 = quarterLocations[j] - quarterRadius
var quarterR float32 = quarterLocations[j] + quarterRadius
if dimeR >= quarterL && dimeR <= quarterR {
hits+=1
continue
}
if dimeL >= quarterL && dimeL <= quarterR {
hits+=1
continue
}
}
}
elapsed := time.Since(startTime)/time.Millisecond
misses := trials - hits
println("There were ", hits, " hits")
println("There were ", misses, " misses")
println("Took ", elapsed, "ms")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment