summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPatrick Simianer <p@simianer.de>2014-02-13 17:39:24 +0100
committerPatrick Simianer <p@simianer.de>2014-02-13 17:39:24 +0100
commit2e16486848a761d5f341ede096944a8526b97fc3 (patch)
tree68aa2ce125449c937f5e38a4be2998952e095bb7
parentbd9d9cbe8252d4d32b0c414009b85267fffae1ce (diff)
SparseVector: approx_eql?, misc
-rw-r--r--lib/nlp_ruby/SparseVector.rb15
-rw-r--r--lib/nlp_ruby/misc.rb8
2 files changed, 22 insertions, 1 deletions
diff --git a/lib/nlp_ruby/SparseVector.rb b/lib/nlp_ruby/SparseVector.rb
index 6843b70..fc9d55c 100644
--- a/lib/nlp_ruby/SparseVector.rb
+++ b/lib/nlp_ruby/SparseVector.rb
@@ -1,8 +1,11 @@
class SparseVector < Hash
- def initialize
+ def initialize arg=nil
super
self.default = 0
+ if arg.is_a? Array
+ from_a arg
+ end
end
def from_a a
@@ -21,6 +24,16 @@ class SparseVector < Hash
self.values.inject(:+)
end
+ def approx_eql? other, p=10**-10
+ return false if !other
+ return false if other.size!=self.size
+ return false if other.keys.sort!=self.keys.sort
+ self.keys.each { |k|
+ return false if (self[k]-other[k]).abs>p
+ }
+ return true
+ end
+
def average
self.sum/self.size.to_f
end
diff --git a/lib/nlp_ruby/misc.rb b/lib/nlp_ruby/misc.rb
index 1fa3878..80d932c 100644
--- a/lib/nlp_ruby/misc.rb
+++ b/lib/nlp_ruby/misc.rb
@@ -11,6 +11,14 @@ class Array
}
return true
end
+
+ def sum
+ self.inject(:+)
+ end
+
+ def mean
+ self.sum.to_f/self.size
+ end
end
def spawn_with_timeout cmd, t=4, debug=false