Skip to content

Instantly share code, notes, and snippets.

@lencioni
Created March 14, 2021 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lencioni/c494cd2c10cb0eed088b9e2df6dc60ed to your computer and use it in GitHub Desktop.
Save lencioni/c494cd2c10cb0eed088b9e2df6dc60ed to your computer and use it in GitHub Desktop.
Calculate pi
// See "Unbounded Spigot Algorithms for the Digits of Pi," by Jeremy Gibbons,
// Math. Monthly, April 2006, pages 318-328.
// Adapted from https://gustavus.edu/mcs/max/pi/
let app;
let q = BigInt(1);
let r = BigInt(0);
let t = BigInt(1);
let k = BigInt(1);
let n = BigInt(3);
function piDigit() {
while (true) {
if (q * BigInt(4) + r - t < n * t) {
app.textContent += n;
if (k === BigInt(2)) {
app.textContent += ".";
}
const oldQ = q;
const oldR = r;
q *= BigInt(10);
r = BigInt(10) * (r - n * t);
n = (BigInt(10) * (BigInt(3) * oldQ + oldR)) / t - BigInt(10) * n;
break;
} else {
const l = BigInt(2) * k + BigInt(1);
const oldQ = q;
const oldR = r;
const oldT = t;
const oldK = k;
q *= k;
r = (BigInt(2) * oldQ + r) * l;
t *= l;
k += BigInt(1);
n = (oldQ * (BigInt(7) * oldK + BigInt(2)) + oldR * l) / (oldT * l);
}
}
requestAnimationFrame(piDigit);
}
function startPi() {
app = document.createElement("div");
app.setAttribute("style", "word-wrap: break-word;");
document.body.appendChild(app);
requestAnimationFrame(piDigit);
}
startPi();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment