You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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