-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy pathcomplex_number.rb
58 lines (48 loc) · 1.62 KB
/
complex_number.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
# Problem
# Solution
class ComplexNumber
attr_accessor :real,:imaginary
def initialize(real=0,imaginary=0)
@real = real
@imaginary = imaginary
end
def +(other)
raise ArgumentError unless other.is_a?(ComplexNumber)
real = self.real + other.real
imaginary = self.imaginary + other.imaginary
ComplexNumber.new(real,imaginary)
end
def -(other)
raise ArgumentError unless other.is_a?(ComplexNumber)
real = self.real - other.real
imaginary = self.imaginary - other.imaginary
ComplexNumber.new(real,imaginary)
end
def *(other)
raise ArgumentError unless other.is_a?(ComplexNumber)
real = (self.real*other.real)-(self.imaginary*other.imaginary)
imaginary = (self.real*other.imaginary)+(self.imaginary*other.real)
ComplexNumber.new(real,imaginary)
end
def /(other)
raise ArgumentError unless other.is_a?(ComplexNumber)
real = ((self.real*other.real)+(self.imaginary*other.imaginary) )/ other.abs**2
imaginary = ((self.imaginary*other.real)-(self.real*other.imaginary)) / other.abs**2
ComplexNumber.new(real,imaginary)
end
def ==(other)
raise ArgumentError unless other.is_a?(ComplexNumber)
(self.real-other.real).abs <1e-15 and (self.imaginary-other.imaginary).abs < 1e-15
end
def abs
Math.sqrt(@real**2+@imaginary**2)
end
def conjugate
ComplexNumber.new(@real,-1*@imaginary)
end
def exp
real = Math.exp(@real)*Math.cos(@imaginary)
imaginary = Math.exp(@real)*Math.sin(@imaginary)
ComplexNumber.new(real,imaginary)
end
end