• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict'
2
3/* A simple π estimation function using a Monte Carlo method
4 * For 0 to `points`, take 2 random numbers < 1, square and add them to
5 * find the area under that point in a 1x1 square. If that area is <= 1
6 * then it's *within* a quarter-circle, otherwise it's outside.
7 * Take the number of points <= 1 and multiply it by 4 and you have an
8 * estimate!
9 * Do this across multiple processes and average the results to
10 * increase accuracy.
11 */
12
13module.exports = function (points, callback) {
14  let inside = 0
15    , i = points
16
17  while (i--)
18    if (Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) <= 1)
19      inside++
20
21  callback(null, (inside / points) * 4)
22}
23