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 | |
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
-rw-r--r-- | ChangeLog | 4 | ||||
-rw-r--r-- | NEWS | 3 | ||||
-rw-r--r-- | lib/matrix.rb | 27 |
3 files changed, 33 insertions, 1 deletions
@@ -1,3 +1,7 @@ +Sat Jul 9 11:41:03 2011 Marc-Andre Lafortune <ruby-core@marc-andre.ca> + + * lib/matrix.rb: Add Vector#normalize [ruby-dev:43829] + Sat Jul 9 09:25:06 2011 Eric Hodel <drbrain@segment7.net> * enumerator.c: Remove "enumeration sequenced by". @@ -182,7 +182,8 @@ with all sufficient information, see the ChangeLog file. * Matrix#unitary? * Matrix#upper_triangular? * Matrix#zero? - * Vector#magnitude + * Vector#magnitude, #norm + * Vector#normalize * extended methods: * Matrix#each and #each_with_index can iterate on a subset of the elements * Matrix#find_index returns [row, column] and can iterate on a subset 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 |