Skip to content

Commit

Permalink
fixes issue #9 - histogram of equal values returns Infinity
Browse files Browse the repository at this point in the history
Explicitly set bin size to 1 for all arrays with the same value, regardless of
the size.  That deals with this case (and many other similar cases to it).
  • Loading branch information
jtprince committed Oct 3, 2015
1 parent a24adbb commit 73d32ea
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
6 changes: 6 additions & 0 deletions lib/histogram.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,15 @@ def median(sorted)
#
# middle is the median between the other three values
#
# Note: always returns 1 if all values are the same.
#
# inspired by {Richard Cotton's matlab
# implementation}[http://www.mathworks.com/matlabcentral/fileexchange/21033-calculate-number-of-bins-for-histogram]
# and the {histogram page on
# wikipedia}[http://en.wikipedia.org/wiki/Histogram]
def number_of_bins(methd=DEFAULT_BIN_METHOD, quartile_method=DEFAULT_QUARTILE_METHOD)
return 1 if self.to_a.uniq.size == 1

if methd == :middle
[:scott, :sturges, :fd].map {|v| number_of_bins(v) }.sort[1]
else
Expand Down Expand Up @@ -171,6 +175,8 @@ def number_of_bins(methd=DEFAULT_BIN_METHOD, quartile_method=DEFAULT_QUARTILE_ME
# (so, values lower than first bin are not included, but all values
# higher, than last bin are included. Current implementation of custom
# bins is slow.
# * If the number of bins must be determined and all values are the same,
# will use 1 bin.
# * if other_sets are supplied, the same bins will be used for all the sets.
# It is useful if you just want a certain number of bins and for the sets
# to share the exact same bins. In this case returns [bins, freqs(caller),
Expand Down
2 changes: 1 addition & 1 deletion lib/histogram/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Histogram
VERSION = "0.2.3.0"
VERSION = "0.2.4.0"
end
6 changes: 6 additions & 0 deletions spec/histogram_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@ def round(n=nil)
bins, freq = obj8.histogram
end

it 'uses 1 bin if all values are the same' do
bins, freq = obj6.histogram(:sturges)
bins.to_a.should == [0]
freq.to_a.should == [5]
end

end

describe Histogram do
Expand Down

0 comments on commit 73d32ea

Please sign in to comment.