Published
Edited
Mar 21, 2020
Insert cell
md`# Grain Arithmetic`
Insert cell
decimal.set({precision: 24})
Insert cell
error = (nGrain, multiplier) => {
if (!Number.isInteger(nGrain)) {throw new Error("Invalid nGrain")}
const grain = BigInt(nGrain) * 10n ** 18n;
const dGrain = decimal(grain.toString())
const naive = decimal(Math.floor(Number(grain) * multiplier))
const actual = dGrain.mul(decimal(multiplier))
const error = naive.sub(actual)
return error
}
Insert cell
error(1, 1/1337).toString()
Insert cell
error(1, 1/10**6).toString()
Insert cell
error(1, 1/13371337).toString()
Insert cell
error(1, Math.PI).toString()
Insert cell
error(1, 1338 * Math.PI * 10).toString()
Insert cell
error(1, Math.PI * 1337).toString()
Insert cell
fSlices = d3.range(0,12).map((x) => 2**x)
Insert cell
dSlices = fSlices.map((x) => decimal(x))
Insert cell
fSum = d3.sum(fSlices)
Insert cell
dSum = {
let tot = decimal(0);
for (const s of fSlices) {tot = tot.plus(s)}
return tot;
}
Insert cell
bGrain = 1n * 10n**18n
Insert cell
dGrain = decimal(bGrain.toString())
Insert cell
flint = (x) => BigInt(Math.floor(x))
Insert cell
f1 = (x) => flint(Number(bGrain) * x / fSum)
Insert cell
f2 = (x) => bGrain * flint(x / d3.sum(fSlices) * 10**18) / 10n**18n
Insert cell
f3 = (x) => bGrain * flint(x * 10**18 / d3.sum(fSlices)) / 10n**18n
Insert cell
fValidate = (x) => BigInt((dGrain.mul(decimal(x)).div(dSum)).floor().toFixed(0))
Insert cell
bAbs = (b) => b < 0n ? -b : b;
Insert cell
metrics = (f) => {
let tot = 0n;
let err = 0n;
let errSq = 0n;
for (const s of fSlices) {
const actual = f(s);
tot += actual;
const expected = fValidate(s)
let sErr = bAbs(actual - expected)
err += sErr;
errSq += sErr ** 2n;
}
return {
dust: bGrain - tot,
err,
errSq,
}
}
Insert cell
d3 = require("d3@5")
Insert cell
decimal = require("decimal.js-light")
Insert cell
new decimal.Decimal("123.45")
Insert cell
dGrain.div(1337).toString()
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more