Created
March 14, 2021 20:51
-
-
Save lencioni/c494cd2c10cb0eed088b9e2df6dc60ed to your computer and use it in GitHub Desktop.
Calculate pi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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