Skip to content

Commit

Permalink
fix bug with percentile function
Browse files Browse the repository at this point in the history
Sorting arrays of small doubles was inconsistent with the previous method
  • Loading branch information
corybuecker committed Mar 3, 2024
1 parent d6010d9 commit 019718f
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
ruby_native_statistics (1.0.2)
ruby_native_statistics (1.1.0)
rake-compiler (~> 1.2)

GEM
Expand Down
4 changes: 4 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Version 1.1.0

- Fix percentile bug reported by @Gbird22

# Version 1.0.3

- Update all supported Ruby versions
Expand Down
15 changes: 13 additions & 2 deletions ext/ruby_native_statistics/conversions.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "conversions.h"
#include "float.h"

int compare_doubles(const void *a, const void *b)
{
Expand All @@ -8,7 +9,17 @@ int compare_doubles(const void *a, const void *b)
double cmp_a = *dbl_a;
double cmp_b = *dbl_b;

return (cmp_a - cmp_b);
if (fabs(cmp_a - cmp_b) <= (DBL_EPSILON * fabs(cmp_a + cmp_b)))
{
return 0;
}

if (cmp_a > cmp_b)
{
return 1;
}

return -1;
}

double *sorted_ruby_array(VALUE array, long array_length)
Expand All @@ -20,7 +31,7 @@ double *sorted_ruby_array(VALUE array, long array_length)

if (working_array == NULL)
{
rb_raise(rb_eStandardError, "unknown problem calculating median (possibly array is too large)");
rb_raise(rb_eStandardError, "unknown problem sorting array (possibly array is too large)");
}

for (i = 0; i < array_length; i++)
Expand Down
2 changes: 1 addition & 1 deletion lib/ruby_native_statistics/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module RubyNativeStatistics
VERSION = "1.0.3"
VERSION = "1.1.0"
end
15 changes: 15 additions & 0 deletions test/dispersion_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,19 @@ def test_percentile_floats
assert_in_delta 0.73895928, array.percentile(0.333), 0.000001
assert_in_delta 11.43290852, array.percentile(0.928), 0.000001
end

def test_percentile_repeating
array = [5.4, 5.3, 5.2, 5.4, 5.2].to_a.shuffle

assert_in_delta 5.4, array.percentile(0.9), 0.000001
assert_in_delta 5.2, array.percentile(0.1), 0.000001
assert_in_delta 5.3, array.percentile(0.5), 0.000001
assert_in_delta 5.26, array.percentile(0.4), 0.000001
end

def test_percentile_duplicates
array = [5.2, 5.2, 5.2, 5.2, 5.2].to_a.shuffle

assert_in_delta 5.2, array.percentile(0.9), 0.000001
end
end

0 comments on commit 019718f

Please sign in to comment.