Created
June 16, 2015 18:47
-
-
Save AndrewRadev/3ca2f63f4f408bdea2b6 to your computer and use it in GitHub Desktop.
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 'rational' | |
require 'complex' | |
class Phasor | |
attr_reader :magnitude, :angle | |
class << self | |
def from_polar(magnitude, angle) | |
new(magnitude, angle) | |
end | |
def from_complex(c) | |
magnitude, angle_in_radians = c.polar | |
new(magnitude, radians_to_degrees(angle_in_radians)) | |
end | |
def degrees_to_radians(degrees) | |
(degrees / 180.0) * Math::PI | |
end | |
def radians_to_degrees(radians) | |
(radians * 180.0) / Math::PI | |
end | |
end | |
def initialize(magnitude, angle) | |
@magnitude = magnitude | |
@angle = angle % 360 | |
if @angle > 180 | |
@angle -= 360 | |
end | |
end | |
def to_c | |
Complex.polar(@magnitude, self.class.degrees_to_radians(@angle)) | |
end | |
def +(other) | |
self.class.from_complex(to_c + other.to_c) | |
end | |
def *(other) | |
self.class.from_polar(magnitude * other.magnitude, angle + other.angle) | |
end | |
def /(other) | |
self.class.from_polar(magnitude.to_f / other.magnitude, angle - other.angle) | |
end | |
def to_s_polar | |
"#{magnitude.round(2)}<#{angle.round(2)}∘" | |
end | |
def to_s_complex | |
c = to_c | |
c = Complex(c.real.round(2), c.imaginary.round(2)) | |
c.to_s | |
end | |
end | |
p1 = Phasor.new(4, 30) | |
p2 = Phasor.new(3, 20) | |
puts "sum" | |
puts (p1 + p2).to_s_polar | |
puts (p1 + p2).to_s_complex | |
puts | |
puts "product" | |
puts (p1 * p2).to_s_polar | |
puts (p1 * p2).to_s_complex | |
puts | |
puts "division" | |
puts (p1 / p2).to_s_polar | |
puts (p1 / p2).to_s_complex | |
puts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment