Skip to content

Commit 7857f18

Browse files
transclaude
andcommitted
Review Math methods; fix broken kldivergence
- Fix Math.kldivergence (was calling self/each_with_index instead of array parameter — has been broken since it was written) - 63 Math methods reviewed: 48 unique, 7 redirects, 4 safe clashes (log2 guarded, lgamma commented out, gcd/lcm different namespace) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 39b4cd9 commit 7857f18

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

HISTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ Changes:
137137
* Fix Pathname#glob to wrap Ruby's built-in, adding symbol flag support.
138138
* Remove Pathname#empty? (built into Ruby).
139139
* Deprecate Pathname.null (use Pathname.new(File::NULL)).
140+
* Fix `Math.kldivergence` (was broken — referenced `self` instead of array parameter).
140141
* Drop unused `test_files` directive from gemspec. (PR#301)
141142

142143

lib/standard/facets/math/kldivergence.rb

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
module Math
22

3-
# The Kullback-Leibler divergence from this array to that of +q+.
3+
# The Kullback-Leibler divergence from distribution +p+ to distribution +q+.
4+
#
5+
# Both arrays must be the same size and represent probability distributions
6+
# (values should be positive).
47
#
58
# NB: You will possibly want to sort both P and Q before calling this
69
# depending on what you're actually trying to measure.
710
#
811
# http://en.wikipedia.org/wiki/Kullback-Leibler_divergence
912
#
10-
def self.kldivergence(array, q)
11-
fail "Buggy."
12-
fail "Cannot compare differently sized arrays." unless size = q.size
13-
kld = 0
14-
each_with_index { |pi,i| kld += pi*Math::log(pi.to_f/q[i].to_f) }
13+
def self.kldivergence(p, q)
14+
raise ArgumentError, "Cannot compare differently sized arrays." unless p.size == q.size
15+
kld = 0.0
16+
p.each_with_index { |pi, i| kld += pi * Math.log(pi.to_f / q[i].to_f) }
1517
kld
1618
end
1719

1820
end
19-

0 commit comments

Comments
 (0)