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: Regression in hist panicking on out of bounds index #20016

Merged
merged 2 commits into from
Nov 27, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions crates/polars-ops/src/chunked_array/hist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,21 +93,22 @@ where
let min_break: f64 = breaks[0];
let max_break: f64 = breaks[num_bins];
let width = breaks[1] - min_break; // guaranteed at least one bin
let is_integer = !T::get_dtype().is_float();

for chunk in ca.downcast_iter() {
for item in chunk.non_null_values_iter() {
let item = item.to_f64().unwrap();
if include_lower && item == min_break {
count[0] += 1;
} else if item > min_break && item <= max_break {
let idx = (item - min_break) / width;
// This is needed for numeric stability for integers.
// We can fall directly on a boundary with an integer.
let idx = if is_integer && (idx.round() - idx).abs() < 0.0000001 {
idx.round() - 1.0
} else if item == max_break {
count[num_bins - 1] += 1;
} else if item > min_break && item < max_break {
let width_multiple = (item - min_break) / width;
let idx = width_multiple.floor();
// handle the case where item lands on the boundary
let idx = if idx == width_multiple {
idx - 1.0
} else {
idx.ceil() - 1.0
idx
};
count[idx as usize] += 1;
}
Expand Down
13 changes: 13 additions & 0 deletions py-polars/tests/unit/operations/test_hist.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,3 +410,16 @@ def test_hist_floating_point() -> None:
upper = bp[i]

assert ((s <= upper) & (s > lower)).sum() == count[i]


def test_hist_max_boundary_19998() -> None:
s = pl.Series(
[
9514.988509739183,
30738.098872148617,
41400.15705103004,
49093.06982022727,
]
)
result = s.hist(bin_count=50)
assert result["count"].sum() == 4