Class: EasyGeometry::D2::Vector

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_geometry/d2/vector.rb

Overview

A vector in a 2-dimensional Euclidean space.

Constant Summary collapse

EQUITY_TOLERANCE =
0.0000000000001

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(x, y) ⇒ Vector

Returns a new instance of Vector.



9
10
11
12
13
14
# File 'lib/easy_geometry/d2/vector.rb', line 9

def initialize(x, y)
  @x = x; @y = y

  validate!
  converting_to_rational!
end

Instance Attribute Details

#xObject (readonly)

Returns the value of attribute x.



5
6
7
# File 'lib/easy_geometry/d2/vector.rb', line 5

def x
  @x
end

#yObject (readonly)

Returns the value of attribute y.



5
6
7
# File 'lib/easy_geometry/d2/vector.rb', line 5

def y
  @y
end

Instance Method Details

#-(other) ⇒ Object

Subtract two vectors.

Raises:

  • (TypeError)


23
24
25
26
# File 'lib/easy_geometry/d2/vector.rb', line 23

def -(other)
  raise TypeError, "Subtract between Vector and #{ other.class } is not defined" unless other.is_a?(Vector)
  Vector.new(self.x - other.x, self.y - other.y)
end

#==(other) ⇒ Object

Compare self and other Vector.



17
18
19
20
# File 'lib/easy_geometry/d2/vector.rb', line 17

def ==(other)
  return false unless other.is_a?(Vector)
  (x - other.x).abs < EQUITY_TOLERANCE && (y - other.y).abs < EQUITY_TOLERANCE
end

#cross_product(other) ⇒ Object

It is positive if other vector should be turned counter-clockwise in order to superpose them. It is negative if other vector should be turned clockwise in order to superpose them. It is zero when vectors are collinear.

Raises:

  • (TypeError)


43
44
45
46
# File 'lib/easy_geometry/d2/vector.rb', line 43

def cross_product(other)
  raise TypeError, "Cross product between Vector and #{ other.class } is not defined" unless other.is_a?(Vector)
  x * other.y - y * other.x
end

#dot(other) ⇒ Object

Dot product, also known as inner product or scalar product.

Raises:

  • (TypeError)


49
50
51
52
# File 'lib/easy_geometry/d2/vector.rb', line 49

def dot(other)
  raise TypeError, "Scalar (dot) product between Vector and #{ other.class } is not defined" unless other.is_a?(Vector)
  x * other.x + y * other.y
end

#orthogonal_directionObject

Returns a non-zero vector that is orthogonal to the line containing self and the origin.



30
31
32
33
34
35
36
37
38
# File 'lib/easy_geometry/d2/vector.rb', line 30

def orthogonal_direction
  # if a coordinate is zero, we can put a 1 there and zeros elsewhere
  return Vector.new(1, 0) if x.zero?
  return Vector.new(0, 1) if y.zero?

  # if the first two coordinates aren't zero, we can create a non-zero
  # orthogonal vector by swapping them, negating one, and padding with zeros
  Vector.new(-y, x)
end

#to_pointObject

Converts the vector to a point.



55
56
57
# File 'lib/easy_geometry/d2/vector.rb', line 55

def to_point
  Point.new(x, y)
end