d3.ticks error
d3.ticks usually produces more ticks than expected.
by Alexander Shutov
HTML
<script src="https://d3js.org/d3-array.v1.min.js"></script>
JavaScript
const countMin = 2;
const countMax = 100;
const step = 1;
const start = 0;
const max = 100;
const threshold = 0.25;
let maxError = -Infinity;
let worst = null;
let total = 0;
let failures = 0;
for (let end = start + step; end <= max; end += step) {
for (let count = countMin; count <= countMax; count++) {
let ticks = d3.ticks(start, end, count);
let error = (ticks.length - count) / count;
if (error > 0 && error > maxError) {
maxError = error;
worst = {
start,
end,
count,
result: ticks.length
};
}
total++;
if (error > threshold) {
failures++;
}
}
}
const percent = (x) => `${(x * 100).toFixed()}%`;
console.log(`> Worst result: d3.ticks(${worst.start}, ${worst.end}, ${worst.count})`);
console.log(`> Array(${worst.result}) (error ${percent(maxError)})`);
console.log(`> Error more than ${percent(threshold)} in ${percent(failures / total)} cases`);