GoLang: Compute the Math Pi Value via Monte Carlo Simulation


The Math Pi value is related to Circle. If we have a circle inside a square, the ration of area between circle and the square is:

tex_6363242eea946a10b43d5425189d0837 GoLang: Compute the Math Pi Value via Monte Carlo Simulation

Thus, if we have a good-enough psuedo random generator, we can generate as many points (x-y coordinate) as possible, and then count those who are inside the circle (by checking the distance between it to (0, 0) origin), and then count total points we have generated.

pi-circle-random-points-300x300 GoLang: Compute the Math Pi Value via Monte Carlo Simulation

In GoLang, we can use math/rand’s rand.Float64 to generate a random number at range [0, 1.0).

package main

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

func compute_pi(n int) float64 {
	var total int = 0
	var totalIn int = 0
	for i := 0; i < n; i++ {
		var x = rand.Float64()
		var y = rand.Float64()
		if x*x+y*y < 1 {
			totalIn++
		}
		total++
	}
	return float64(totalIn) * 4.0 / float64(total)
}

func main() {
	var n = 100000
	if len(os.Args) == 2 {
		intVar, err := strconv.Atoi(os.Args[1])
		if err == nil {
			n = intVar
		}
	}
	fmt.Println("Pi is:", compute_pi(n))
}

We can pass the number of iterations we want like this:

$ go run pi.go 1000
Pi is: 3.168
$ go run pi.go 10000
Pi is: 3.16
$ go run pi.go 100000
Pi is: 3.1518
$ go run pi.go 1000000
Pi is: 3.140552
$ go run pi.go 10000000
Pi is: 3.1414072

Monte Carlo Simulation Algorithms to compute the Pi based on Randomness:

–EOF (The Ultimate Computing & Technology Blog) —

694 words
Last Post: Teaching Kids Programming - Breadth First Search Algorithm to Compute the Max Width of a Binary Tree
Next Post: Teaching Kids Programming - Depth First Search Algorithm to Compute the Max Width of a Binary Tree

The Permanent URL is: GoLang: Compute the Math Pi Value via Monte Carlo Simulation (AMP Version)

Leave a Reply