-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTriplet.rb
154 lines (127 loc) · 3.21 KB
/
Triplet.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
class Triplet
attr_accessor :x, :y, :z
# methods required for calcuration
def coerce(numeric)
[self, numeric]
end
def -@
self.class.new(-@x, -@y, -@z)
end
def **(num)
@x ** num + @y ** num + @z ** num
end
def length
Math.sqrt(self ** 2)
end
def plus_equal(ins)
@x += ins.x
@y += ins.y
@z += ins.z
end
def minus_equal(ins)
@x -= ins.x
@y -= ins.y
@z -= ins.z
end
def mtply_equal(num)
@x *= num
@y *= num
@z *= num
end
def div_equal(num)
@x /= num.to_f
@y /= num.to_f
@z /= num.to_f
end
[:+, :-].each{|sym|
define_method(sym){|operand|
self.class.new(
@x.send(sym, operand.x),
@y.send(sym, operand.y),
@z.send(sym, operand.z)
)
}
}
[:/, :%].each{|sym|
define_method(sym){|operand|
self.class.new(
@x.send(sym, operand.to_f),
@y.send(sym, operand.to_f),
@z.send(sym, operand.to_f)
)
}
}
def *(operand)
if [:x, :y, :z].all?{|attribute| operand.respond_to?(attribute) } then
self.class.new(
@x.send(:*, operand.x),
@y.send(:*, operand.y),
@z.send(:*, operand.z)
)
else
self.class.new(
@x.send(:*, operand),
@y.send(:*, operand),
@z.send(:*, operand)
)
end
end
def self.dot(u, v)
u.x * v.x + u.y * v.y + u.z * u.z
end
def dot(v)
@x * v.x + @y * v.y + @z * v.z
end
def self.cross(u, v)
self.class.new(u.y * v.z - u.z * v.y,
u.z * v.x - u.x * v.z,
u.x * v.y - u.y * v.x)
end
def cross(v)
self.class.new(@y * v.z - @z * v.y,
@z * v.x - @x * v.z,
@x * v.y - @y * v.x)
end
def sqrt
self.class.new(Math.sqrt(@x), Math.sqrt(@y), Math.sqrt(@z))
end
def unit_vector
self / self.length
end
def near_zero?
almost_zero = 1e-8
[@x, @y, @z].all?{ _1 < almost_zero }
end
# normal (and utilities) methods below
def initialize(x = 0, y = nil, z = nil)
if x.kind_of?(Triplet) then
x = x.to_trpl
@x, @y, @z = [:x, :y, :z].map{ x.send(_1) }
return self
end
@x, @y, @z = x.to_f, (y || x).to_f, (z || x).to_f
end
def [](idx)
[@x, @y, @z][idx]
end
def set(x, y, z)
@x, @y, @z = x, y, z
end
def join(str = "")
[@x, @y, @z].reduce{|result, pt| result.to_s + str + pt.to_s }
end
def to_s
join(" ")
end
def to_trpl
self.clone
end
def self.rand(lower_limit = -1.0, upper_limit = 1.0)
lower_limit, upper_limit = Float(lower_limit), Float(upper_limit)
range = lower_limit..upper_limit
self.new(Kernel.rand(range), Kernel.rand(range), Kernel.rand(range))
end
end
def trpl(x = 0, y = 0, z = 0)
Triplet.new(x, y, z)
end