1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

lib/matrix: Fix potential bug of Vector#angle_with

Could happen for some linearly dependent vectors.
Patch by Vasiliy Petrov. [Fix GH-1803]

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@64761 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
marcandre 2018-09-16 04:18:50 +00:00
parent 2492402249
commit 1a6c27346e
2 changed files with 9 additions and 3 deletions

View file

@ -2080,7 +2080,7 @@ class Vector
end
#
# Returns an angle with another vector. Result is within the [0...Math::PI].
# Returns an angle with another vector. Result is within the [0..Math::PI].
# Vector[1,0].angle_with(Vector[0,1])
# # => Math::PI / 2
#
@ -2089,8 +2089,12 @@ class Vector
Vector.Raise ErrDimensionMismatch if size != v.size
prod = magnitude * v.magnitude
raise ZeroVectorError, "Can't get angle of zero vector" if prod == 0
Math.acos( inner_product(v) / prod )
dot = inner_product(v)
if dot.abs >= prod
dot.positive? ? 0 : Math::PI
else
Math.acos(dot / prod)
end
end
#--

View file

@ -223,6 +223,8 @@ class TestVector < Test::Unit::TestCase
assert_in_epsilon(Math::PI/2, Vector[1, 0].angle_with(Vector[0, -1]))
assert_in_epsilon(Math::PI/4, Vector[2, 2].angle_with(Vector[0, 1]))
assert_in_delta(0.0, Vector[1, 1].angle_with(Vector[1, 1]), 0.00001)
assert_equal(Vector[6, 6].angle_with(Vector[7, 7]), 0.0)
assert_equal(Vector[6, 6].angle_with(Vector[-7, -7]), Math::PI)
assert_raise(Vector::ZeroVectorError) { Vector[1, 1].angle_with(Vector[0, 0]) }
assert_raise(Vector::ZeroVectorError) { Vector[0, 0].angle_with(Vector[1, 1]) }