BASH Script to Compute the Math.PI constant via Monte Carlo Simulation


Based on the calc function defined in BASH via AWK, we can perform floating point computation in BASH.

The $RANDOM variable gives a psuedo random integer that is within the range of [0, 32767] aka 16-bit. Then, we can generate a random point (X, Y) and compute the distance to the origin (0, 0). Count the number of points that fall inside the circle and the result will be the ratio multiplied by four.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/bin/bash
 
function calc() {
    awk "BEGIN { print $*; }"    
}
 
function pi() {
    local n=$1
    local total=0
    local inside=0
    local RAND_MAX=32767
    local i=0
    while [[ $i -lt $n ]]; do
        local x=$RANDOM
        local y=$RANDOM
        local xxyy=$(calc "(($x/$RAND_MAX)**2+($y/$RAND_MAX)**2)<=1")
        if [[ $xxyy -eq 1 ]]; then
            inside=$((inside+1))
        fi
        total=$((total+1))
        i=$((i+1))
    done
    calc $inside*4/$total
}
 
if [[ -z "$1" ]]; then
    pi 5000
else
    pi $1
fi
#!/bin/bash

function calc() {
    awk "BEGIN { print $*; }"    
}

function pi() {
    local n=$1
    local total=0
    local inside=0
    local RAND_MAX=32767
    local i=0
    while [[ $i -lt $n ]]; do
        local x=$RANDOM
        local y=$RANDOM
        local xxyy=$(calc "(($x/$RAND_MAX)**2+($y/$RAND_MAX)**2)<=1")
        if [[ $xxyy -eq 1 ]]; then
            inside=$((inside+1))
        fi
        total=$((total+1))
        i=$((i+1))
    done
    calc $inside*4/$total
}

if [[ -z "$1" ]]; then
    pi 5000
else
    pi $1
fi

If you don't specify the parameter (iterations of Monte carlo) it is default to 5000.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ ./pi.sh 11
3.1344
$ ./pi.sh 11
3.63636
$ ./pi.sh 11
2.90909
$ ./pi.sh 100
2.92
$ ./pi.sh 100
3.48
$ ./pi.sh 
3.1512
$ ./pi.sh 1000
3.084
$ ./pi.sh 10000
3.1412
$ ./pi.sh 11
3.1344
$ ./pi.sh 11
3.63636
$ ./pi.sh 11
2.90909
$ ./pi.sh 100
2.92
$ ./pi.sh 100
3.48
$ ./pi.sh 
3.1512
$ ./pi.sh 1000
3.084
$ ./pi.sh 10000
3.1412

More iterations higher accuracy of the Estimation which means we will get a better approximation of the Math Constant PI value.

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

--EOF (The Ultimate Computing & Technology Blog) --

GD Star Rating
loading...
644 words
Last Post: Teaching Kids Programming - Build Array from Permutation
Next Post: Teaching Kids Programming - Count Square Sum (Pythagorean) Triples

The Permanent URL is: BASH Script to Compute the Math.PI constant via Monte Carlo Simulation

Leave a Reply