Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix for quantization error with fractional step #247

Merged
merged 2 commits into from Apr 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -42,6 +42,7 @@
},
"devDependencies": {
"@rollup/plugin-node-resolve": "13",
"d3-dsv": "3",
"d3-random": "2 - 3",
"eslint": "8",
"jsdom": "19",
Expand Down
3 changes: 2 additions & 1 deletion src/bin.js
Expand Up @@ -91,7 +91,8 @@ export default function bin() {
} else if (step < 0) {
for (i = 0; i < n; ++i) {
if ((x = values[i]) != null && x0 <= x && x <= x1) {
bins[Math.floor((x0 - x) * step)].push(data[i]);
const j = Math.floor((x0 - x) * step);
bins[j + (tz[j] <= x)].push(data[i]); // handle off-by-one due to rounding
}
}
}
Expand Down
16 changes: 15 additions & 1 deletion test/bin-test.js
@@ -1,5 +1,7 @@
import assert from "assert";
import {bin, extent, histogram, thresholdSturges} from "../src/index.js";
import {csvParse} from "d3-dsv";
import {readFile} from "fs/promises";
import {bin, extent, histogram, thresholdSturges, ticks} from "../src/index.js";

it("histogram is a deprecated alias for bin", () => {
assert.strictEqual(histogram, bin);
Expand Down Expand Up @@ -221,6 +223,18 @@ it("bin(data) coerces values to numbers as expected", () => {
]);
});

it("bin(athletes) produces the expected result", async () => {
const height = csvParse(await readFile("./test/data/athletes.csv", "utf8")).filter(d => d.height).map(d => +d.height);
const bins = bin().thresholds(57)(height);
assert.deepStrictEqual(bins.map(b => b.length), [1, 0, 0, 0, 0, 0, 2, 1, 2, 1, 1, 4, 11, 7, 13, 39, 78, 93, 119, 193, 354, 393, 573, 483, 651, 834, 808, 763, 627, 648, 833, 672, 578, 498, 395, 425, 278, 235, 182, 128, 91, 69, 43, 29, 21, 23, 3, 3, 1, 1, 1]);
});

it("bin(data) assigns floating point values to the correct bins", () => {
for (const n of [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000]) {
assert.ok(bin().thresholds(n)(ticks(1, 2, n)).every(d => d.length === 1));
}
});

function box(bin, x0, x1) {
bin.x0 = x0;
bin.x1 = x1;
Expand Down