Skip to content

Instantly share code, notes, and snippets.

@dotmh
Created June 18, 2020 13:57
Show Gist options
  • Save dotmh/5e875bc88557fdee70f24ae5df6de678 to your computer and use it in GitHub Desktop.
Save dotmh/5e875bc88557fdee70f24ae5df6de678 to your computer and use it in GitHub Desktop.
Calculate PI using Random Numbers

Calculate PI

I got inspired by a recent youtube video I watched called Generating π from 1,000 random numbers.

In this video the presenter Matt Paker shows you how to calculate PI from 1000 random numbers.

I decided to code this in JS. This is slightly different as I decided to get the average of 1000 attempts at calculating pi from 1000 random numbers.

Configuartion

The 3 constants upper, sampleSize and attempts can be used to reconfigure this.

  • Upper is the upper bound of the random number.
  • sampleSize is the number of random number pairs to use.
  • attempts is the number of times we calculate pi.

Caveats

There are a few caveats to using this

  1. I have used Arrays so there is a maxiumn number of both sampleSize and attempts 4.29 billion.
  2. It takes it a bit to work out all of this so it may pause before giving an answer the pause length is really how fast your machine is.

Usage

To save me a load of time I used mathjs so you will need to install that.

then simple run the script with node

node ./CalculatePi.js

Dont want to go to all the fuss of installing node then using RunJS works , It was what I did this in myself. you can read how to install mathjs at https://github.com/lukehaas/RunJS/tree/v1.9.0

Last Run Pi

The last time I ran this I got the result PI is 3.143409347609027

const mjs = require("mathjs");
const upper = 10000000;
const sampleSize = 1000;
const attempts = 1000;
const calculatePi = () => {
const a = Array(sampleSize)
.fill(0)
.map(() => [mjs.ceil(mjs.random(1, upper)), mjs.ceil(mjs.random(1, upper))])
.map(([a, b]) => mjs.gcd(a, b) === 1)
.filter(Boolean).length;
const p = a / sampleSize;
return mjs.sqrt(6 / p);
};
const a = (Array(attempts).fill(0).map(() => calculatePi()).reduce((a, i) => a + i, 0)) / attempts;
console.log(`PI is ${a}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment