Monte Carlo approximation (Golang)
Image by Gerd Altmann from Pixabay

Monte Carlo approximation (Golang)

Happy Pi day! Here's a Monte Carlo Pi approximation I whipped up in Go this afternoon.

package main


import (
	"fmt"
	"math"
	"math/rand"
)

func main() {
	samplesExponent := 10

	var r1 float64
	var r2 float64
	var heads float64
	samples := math.Pow(10, float64(samplesExponent))
	heads = 0
	for range make([]struct{}, int(samples)) {
		r1 = rand.Float64()
		r2 = rand.Float64()
		toss := math.Pow(r1-0.5, 2)+math.Pow(r2-0.5, 2)
		if toss < 0.25 {
    			heads++
		}
	}
	
	area := samples * 0.25
	
	pi := heads / area
	
	fmt.Printf("pi estimation - %f\n", pi)
}

This runs the typical unit square Monte Carlo algorithm on a quarter circle (that's where the numbers 0.5 and 0.25 come from). sampleSize is the size of the exponent on the number of samples. Here's a table with the execution time of the script for varying sampleSize's:

Image of example execution time, ranging from 14 microseconds for 10 samples to 13 minutes for 10^10 samples

The estimation at 10^9 samples almost looked accurate to 5 decimals, but my eyes deceived me ??

Running anything over 10 billion samples took longer than I cared to wait, so I tried making a version that ran fractions of my total samples on different threads and returned the number of heads back to the main thread. Here's the gist of my attempt.

Something in there isn't working quite right — but that's a problem for next Pi day ??

要查看或添加评论,请登录

William Harvey的更多文章

社区洞察

其他会员也浏览了