Public
Edited
Aug 9, 2024
2 forks
Importers
20 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function binaryPow(b, e) {
let y = 1;
while (e > 0) {
if (e & 1) y *= b;
b *= b;
e >>= 1;
}
return y;
}
Insert cell
binaryPow(3, 17)
Insert cell
Insert cell
function modPow(b, e, m) {
b = b % m;
let y = 1;
while (e > 0) {
if (e & 1) y = (y * b) % m;
b = (b * b) % m;
e >>= 1;
}
return y;
}
Insert cell
Insert cell
modPow(3, 17, 50)
Insert cell
Insert cell
3 ** 17 % 50
Insert cell
Insert cell
function mod(x, n) {
x %= n;
return x < 0 ? x + n : x;
}
Insert cell
Insert cell
computePi = {
function S(j, n) {
// Lefthand summation. Add a number of terms equal
// to the starting digit. Most of the time is spent
// in this loop.
let left = 0;
for (let k = 0; k <= n; k++) {
let r = 8 * k + j;
left = mod(left + modPow(16, n - k, r) / r, 1);
}

// Righthand summation. Add a small number of terms
// until the result stops changing.
let right = 0;
for (let k = n + 1; ; k++) {
let rnew = right + 16 ** (n - k) / (8 * k + j);
if (right === rnew) break;
right = rnew;
}

return left + right;
}

// Start at digit d and compute n digits
return function piBBP(d, n) {
// Seems to be the convention for including the leading 3
d -= 1;
// Shift n digits to the left of the radix point to obtain our final
// result as a integer
return Math.floor(
16 ** n * mod(4 * S(1, d) - 2 * S(4, d) - S(5, d) - S(6, d), 1)
);
};
}
Insert cell
computePi(0, 10).toString(16)
Insert cell
Insert cell
Insert cell
Insert cell
BBPbigint = {
if (!supportsBigInt) return () => () => 0;

return new Function(`
function modPow(b, e, m) {
if (!e) return 1n;
b = b % m;
let y = 1n;
while (true) {
if (e & 1n) y = (y * b) % m;
e >>= 1n;
if (!e) return y;
b = (b * b) % m;
}
}

function S(j, n, d, mask) {
const shift = d << 2n;
let left = 0n;
for (let k = 0n; k <= n; k++) {
let r = k * 8n + j;
left = (left + (modPow(16n, n - k, r) << shift) / r) & mask;
}
let right = 0n;
for (let k = n + 1n; ; k++) {
let rnew = right + 16n ** (d + n - k) / (k * 8n + j);
if (right === rnew) break;
right = rnew;
}
return left + right;
}

return function computePi(dd, nn) {
const n = BigInt(nn);
const d = BigInt(dd) - 1n;
const mask = 16n ** n - 1n;
return (
4n * S(1n, d, n, mask) -
2n * S(4n, d, n, mask) -
S(5n, d, n, mask) -
S(6n, d, n, mask)
) & mask;
};`)();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more