Last active
August 29, 2015 14:07
-
-
Save vitor-mariano/46d1925605e341a1d7a3 to your computer and use it in GitHub Desktop.
Geometria Analítica abstraída em Ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Geometry | |
class Point | |
attr_accessor :coordenates | |
def initialize *coordenates | |
@coordenates = coordenates.map { |c| c.to_f.round 4 } | |
end | |
def add point | |
self.class.new *operate([@coordenates, point.coordenates], :+) | |
end | |
alias_method :+, :add | |
def subtract point | |
add self.class.new *point.coordenates.map { |c| -c } | |
end | |
alias_method :-, :subtract | |
def scalar object | |
if object.is_a? Point | |
object = operate([@coordenates, object.coordenates], :*) | |
else | |
object = @coordenates.map { |c| object * c } | |
end | |
self.class.new *object | |
end | |
alias_method :*, :scalar | |
protected | |
def operate array, type | |
array.transpose.map { |c| c.reduce type } | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "matrix" | |
module Geometry | |
class Vector < Geometry::Point | |
def scalar object | |
if object.is_a? Vector | |
([@coordenates, object.coordenates].transpose.map { |c| c.reduce :* }).reduce :+ | |
else | |
self.class.new *@coordenates.map { |c| object * c } | |
end | |
end | |
alias_method :dot, :scalar | |
alias_method :inner, :scalar | |
def cross vector | |
self.class.new Matrix[[self.coordenates[1], self.coordenates[2]], [vector.coordenates[1], vector.coordenates[2]]].det, -1 * Matrix[[self.coordenates[0], self.coordenates[2]], [vector.coordenates[0], vector.coordenates[2]]].det, Matrix[[self.coordenates[0], self.coordenates[1]], [vector.coordenates[0], vector.coordenates[1]]].det | |
end | |
alias_method :vector, :cross | |
def norm | |
Math::sqrt inner self | |
end | |
def angle vector | |
Math::acos self.inner(vector) / (self.norm * vector.norm) | |
end | |
def projection vector | |
vector.inner self.inner(vector) / (vector.norm ** 2) | |
end | |
def perpendicular? vector | |
self.inner vector == 0 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment