Skip to content

Commit 48e69ea

Browse files
committed
Fix histogram for small bin range
1 parent ba76e8a commit 48e69ea

File tree

2 files changed

+27
-10
lines changed

2 files changed

+27
-10
lines changed

ext/enumerable/statistics/extension/statistics.c

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2104,18 +2104,22 @@ histogram_edge_bin_index(VALUE edge, VALUE rb_x, int left_p)
21042104
static void
21052105
histogram_weights_push_values(VALUE bin_weights, VALUE edge, VALUE values, VALUE weight_array, int left_p)
21062106
{
2107+
const VALUE one = INT2FIX(1);
2108+
long bi, i, n, n_bins, weighted = 0;
21072109
VALUE x, cur;
2108-
long i, n, bi, one, weighted = 0;
2110+
2111+
assert(RB_TYPE_P(edge, T_ARRAY));
2112+
assert(RB_TYPE_P(values, T_ARRAY));
21092113

21102114
n = RARRAY_LEN(values);
2115+
n_bins = RARRAY_LEN(edge) - 1;
21112116

21122117
if (! NIL_P(weight_array)) {
21132118
assert(RB_TYPE_P(weight_array, T_ARRAY));
21142119
assert(RARRAY_LEN(weight_array) == n);
21152120
weighted = 1;
21162121
}
21172122

2118-
one = INT2FIX(1);
21192123
for (i = 0; i < n; ++i) {
21202124
x = RARRAY_AREF(values, i);
21212125

@@ -2143,15 +2147,17 @@ histogram_weights_push_values(VALUE bin_weights, VALUE edge, VALUE values, VALUE
21432147

21442148
bi = histogram_edge_bin_index(edge, x, left_p);
21452149

2146-
cur = rb_ary_entry(bin_weights, bi);
2147-
if (NIL_P(cur)) {
2148-
cur = w;
2149-
}
2150-
else {
2151-
cur = rb_funcall(cur, idPLUS, 1, w);
2152-
}
2150+
if (0 <= bi && bi < n_bins) {
2151+
cur = rb_ary_entry(bin_weights, bi);
2152+
if (NIL_P(cur)) {
2153+
cur = w;
2154+
}
2155+
else {
2156+
cur = rb_funcall(cur, idPLUS, 1, w);
2157+
}
21532158

2154-
rb_ary_store(bin_weights, bi, cur);
2159+
rb_ary_store(bin_weights, bi, cur);
2160+
}
21552161
}
21562162
return;
21572163

spec/histogram/array_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,17 @@
137137
expect(histogram.density?).to eq(false)
138138
end
139139
end
140+
141+
context 'edges: [3.0, 6.0, 9.0]' do
142+
let(:kwargs) { {edges: [3.0, 6.0, 9.0]} }
143+
144+
specify do
145+
expect(histogram.edge).to eq([3.0, 6.0, 9.0])
146+
expect(histogram.weights).to eq([3, 3])
147+
expect(histogram.closed).to eq(:left)
148+
expect(histogram.density?).to eq(false)
149+
end
150+
end
140151
end
141152

142153
context "with 10,000 normal random values" do

0 commit comments

Comments
 (0)