fork download
  1. // Monte Carlo Method
  2.  
  3. const maxn = 1000000;
  4. let count = 0;
  5.  
  6. for (let i = 0; i < maxn; i++) {
  7. let x = Math.random();
  8. let y = Math.random();
  9. if (x * x + y * y <= 1) {
  10. count = count + 1;
  11. }
  12. }
  13.  
  14. const mypi = count * 4 / maxn;
  15. let devi = 100 * Math.abs(Math.PI - mypi) / Math.PI;
  16. console.log(`Estimate: ${mypi.toFixed(4)}, Deviation: ${devi.toFixed(2)}%`);
Success #stdin #stdout 0.06s 17568KB
stdin
Standard input is empty
stdout
Estimate: 3.1426, Deviation: 0.03%