diff options
author | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2011-07-09 02:41:14 +0000 |
---|---|---|
committer | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2011-07-09 02:41:14 +0000 |
commit | 1e696acc7e86a6d57fe6afa91c7478420c62bc2b (patch) | |
tree | 9fdc14c700db920432aacb6ae429389a88a5ad6f /lib/matrix.rb | |
parent | d137810d3a79e42b8ea7a52b04df0d3d1bc03ab9 (diff) |
* lib/matrix.rb: Add Vector#normalize [ruby-dev:43829]
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@32467 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib/matrix.rb')
-rw-r--r-- | lib/matrix.rb | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/lib/matrix.rb b/lib/matrix.rb index b4ff31a218..360e79f3cc 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -1517,8 +1517,11 @@ end # Vector functions: # * <tt> #inner_product(v) </tt> # * <tt> #collect </tt> +# * <tt> #magnitude </tt> # * <tt> #map </tt> # * <tt> #map2(v) </tt> +# * <tt> #norm </tt> +# * <tt> #normalize </tt> # * <tt> #r </tt> # * <tt> #size </tt> # @@ -1778,6 +1781,30 @@ class Vector Math.sqrt(@elements.inject(0) {|v, e| v + e*e}) end alias r magnitude + alias norm magnitude + + # + # Like Vector#collect2, but returns a Vector instead of an Array. + # + def map2(v, &block) # :yield: e1, e2 + return to_enum(:map2, v) unless block_given? + els = collect2(v, &block) + Vector.elements(els, false) + end + + class ZeroVectorError < StandardError + end + # + # Returns a new vector with the same direction but with norm 1. + # v = Vector[5,8,2].normalize + # # => Vector[0.5184758473652127, 0.8295613557843402, 0.20739033894608505] + # v.norm => 1.0 + # + def normalize + n = magnitude + raise ZeroVectorError, "Zero vectors can not be normalized" if n == 0 + self / n + end #-- # CONVERTING |