summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPatrick Simianer <p@simianer.de>2015-07-16 15:51:20 +0200
committerPatrick Simianer <p@simianer.de>2015-07-16 15:51:20 +0200
commitb6820b015c1a2767916e3d894cd9cd76d67b94b9 (patch)
tree0f1485df4a2cbfa6d6e6add9ae483ce9320fc776
parent537183518280e379236711dc18fac1fa58c8c054 (diff)
SparseVector: norm, unit
-rw-r--r--lib/zipf/SparseVector.rb15
-rwxr-xr-xtest/test_sparsevector.rb18
2 files changed, 33 insertions, 0 deletions
diff --git a/lib/zipf/SparseVector.rb b/lib/zipf/SparseVector.rb
index 5d219b8..976ecaf 100644
--- a/lib/zipf/SparseVector.rb
+++ b/lib/zipf/SparseVector.rb
@@ -199,5 +199,20 @@ class SparseVector < Hash
mean.each_pair { |k,v| mean[k] = v/n }
return mean
end
+
+ def norm
+ return Math.sqrt(self.dot(self))
+ end
+
+ def unit!
+ n = self.norm
+ self.each_pair { |k,v|
+ self[k] /= n
+ }
+ end
+
+ def unit
+ return SparseVector.new(self).unit!
+ end
end
diff --git a/test/test_sparsevector.rb b/test/test_sparsevector.rb
new file mode 100755
index 0000000..a23a7d3
--- /dev/null
+++ b/test/test_sparsevector.rb
@@ -0,0 +1,18 @@
+#!/usr/bin/env ruby
+
+require_relative '../lib/zipf/SparseVector'
+require 'test/unit'
+
+class TestSparseVector < Test::Unit::TestCase
+
+ def test_unit
+ v = SparseVector.new
+ v[:a] = 1
+ v[:b] = 2
+ v[:c] = 3
+ assert_equal Math.sqrt(1**2+2**2+3**2), v.norm
+ v.unit!
+ assert_equal v.norm, 1.0
+ end
+end
+