Published
Edited
Jul 1, 2020
Insert cell
Insert cell
array = [0, 0.2, 1]
Insert cell
d3.quantile(array, 0.5)
Insert cell
Insert cell
Insert cell
d3.quantileSorted(array, 0.5625)
Insert cell
Insert cell
// Approximate Newton-Raphson
// Solve f(x) = y, start from x
function solve(f, y, x) {
var steps = 100,
delta,
f0,
f1,
epsilon = 1e-6,
abs = Math.abs;
x = x === undefined ? 0 : +x;
y = +y;
do {
f0 = f(x);
f1 = f(x + epsilon);
if (f0 === f1) f1 = f0 + epsilon;
x -= delta = (-1 * epsilon * (f0 - y)) / (f0 - f1);
} while (steps-- > 0 && abs(delta) > epsilon);
return steps < 0 ? NaN : x;
}
Insert cell
function quantileinvert(array, q) {
const sorted = new Float64Array(array).sort();
function invert(q) {
return solve(function(t) {
const t0 = Math.max(0, Math.min(1, t));
return d3.quantileSorted(array, t0) + (t - t0);
}, q);
}
// currying
return q === undefined ? invert : invert(q);
}
Insert cell
quantileinvert(array)
Insert cell
Insert cell
quantileinvert(array, 0.3)
Insert cell
d3 = require("d3@5", "d3-array@2")
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