How to resolve the algorithm Monte Carlo methods step by step in the jq programming language
How to resolve the algorithm Monte Carlo methods step by step in the jq programming language
Table of Contents
Problem Statement
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
. If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be
π
/
4
{\displaystyle \pi /4}
. So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately
π
/
4
{\displaystyle \pi /4}
.
Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number
π
{\displaystyle \pi }
is not built-in, we give
π
{\displaystyle \pi }
as a number of digits:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Monte Carlo methods step by step in the jq programming language
Source code in the jq programming language
# In case gojq is used, trim leading 0s:
function prng {
cat /dev/urandom | tr -cd '0-9' | fold -w 10 | sed 's/^0*\(.*\)*\(.\)*$/\1\2/'
}
prng | jq -nMr -f program.jq
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
def percent: "\(100000 * . | round / 1000)%";
def pi: 4* (1|atan);
def rfloat: input/1E10;
def mcPi:
. as $n
| reduce range(0; $n) as $i (0;
rfloat as $x
| rfloat as $y
| if ($x*$x + $y*$y <= 1) then . + 1 else . end)
| 4 * . / $n ;
"Iterations -> Approx Pi -> Error",
"---------- ---------- ------",
( pi as $pi
| range(1; 7)
| pow(10;.) as $p
| ($p | mcPi) as $mcpi
| ((($pi - $mcpi)|length) / $pi) as $error
| "\($p|lpad(10)) \($mcpi|lpad(10)) \($error|percent|lpad(6))" )
You may also check:How to resolve the algorithm Combinations and permutations step by step in the Python programming language
You may also check:How to resolve the algorithm Count in octal step by step in the Z80 Assembly programming language
You may also check:How to resolve the algorithm FizzBuzz step by step in the TI-83 Hex Assembly programming language
You may also check:How to resolve the algorithm Soloway's recurring rainfall step by step in the Ruby programming language
You may also check:How to resolve the algorithm Anagrams step by step in the ALGOL 68 programming language