Monte Carlo methods: Difference between revisions

(Added solution for Action!)
Line 1,497:
{{Out}} (5 sample runs with increasing sample sizes)
<lang JavaScript>[3.14, 3.1404, 3.13304, 3.142408, 3.1420304, 3.14156788]</lang>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
jq does not have a built-in PRNG so we will use /dev/urandom
as a source of entropy by invoking jq as follows:
<lang sh># 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</lang>
 
'''program.jq'''
<lang jq>def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
def percent: "\(10000 * . | round / 100)%";
 
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))" )</lang>
{{out}}
<pre>
Iterations -> Approx Pi -> Error
---------- ---------- ------
10 2.4 23.61%
100 3.2 1.86%
1000 3.192 1.6%
10000 3.1012 1.29%
100000 3.14772 0.2%
1000000 3.141632 0%
</pre>
 
 
=={{header|Jsish}}==
2,442

edits