Monte Carlo methods: Difference between revisions

Line 1,464:
===ES6===
<lang JavaScript>(() => {
'"use strict'";
 
// --- APPROXIMATION OF PI BY A MONTE CARLO METHOD ---
 
// monteCarloPi :: Int -> Float
const monteCarloPi = n =>
4 * rangeenumFromTo(1, )(n).reduce(a => {
.reduce(a => {
const [x, y] = [rnd(), rnd()];
 
return (x * x) + (y * y) < 1 ? a + 1 : a;(
1 + a
) : a;
}, 0) / n;
 
 
// --------------------- GENERIC FUNCTIONS---------------------
 
// rangeenumFromTo :: Int -> Int -> [Int]
const rangeenumFromTo = (m, n) =>
n => Array.from({
length: Math.floor(1 + n - m) + 1
}, (_, i) => m + i);
 
 
// rnd :: () -> Float
Line 1,487 ⟶ 1,492:
 
 
// ---------------------- TEST -----------------------
// TEST with fromFrom 1000 samples to 10E810E7 samples
return range(3, 8)
return enumFromTo(3)(7).forEach(x => {
.map(x => monteCarloPi(Math.pow(10, x)));
const nSamples = 10 ** x;
 
console.log(
// e.g. -> [3.14, 3.1404, 3.13304, 3.142408, 3.1420304, 3.14156788]
`${nSamples} samples: ${monteCarloPi(nSamples)}`
})();
);
</lang>
});
})();</lang>
 
{{Out}} For example:
{{Out}} (5 sample runs with increasing sample sizes)
<pre>1000 samples: 3.064
<lang JavaScript>[3.14, 3.1404, 3.13304, 3.142408, 3.1420304, 3.14156788]</lang>
10000 samples: 3.1416
100000 samples: 3.14756
1000000 samples: 3.142536
10000000 samples: 3.142808</pre>
 
=={{header|jq}}==
9,655

edits