1
+ # Problem
2
+
3
+ # Solution
4
+ class ComplexNumber
5
+ attr_accessor :real , :imaginary
6
+
7
+ def initialize ( real = 0 , imaginary = 0 )
8
+ @real = real
9
+ @imaginary = imaginary
10
+ end
11
+
12
+ def +( other )
13
+ raise ArgumentError unless other . is_a? ( ComplexNumber )
14
+ real = self . real + other . real
15
+ imaginary = self . imaginary + other . imaginary
16
+ ComplexNumber . new ( real , imaginary )
17
+ end
18
+
19
+ def -( other )
20
+ raise ArgumentError unless other . is_a? ( ComplexNumber )
21
+ real = self . real - other . real
22
+ imaginary = self . imaginary - other . imaginary
23
+ ComplexNumber . new ( real , imaginary )
24
+ end
25
+
26
+ def *( other )
27
+ raise ArgumentError unless other . is_a? ( ComplexNumber )
28
+ real = ( self . real *other . real ) -( self . imaginary *other . imaginary )
29
+ imaginary = ( self . real *other . imaginary ) +( self . imaginary *other . real )
30
+ ComplexNumber . new ( real , imaginary )
31
+ end
32
+
33
+ def /( other )
34
+ raise ArgumentError unless other . is_a? ( ComplexNumber )
35
+ real = ( ( self . real *other . real ) +( self . imaginary *other . imaginary ) ) / other . abs **2
36
+ imaginary = ( ( self . imaginary *other . real ) -( self . real *other . imaginary ) ) / other . abs **2
37
+ ComplexNumber . new ( real , imaginary )
38
+ end
39
+
40
+ def ==( other )
41
+ raise ArgumentError unless other . is_a? ( ComplexNumber )
42
+ ( self . real -other . real ) . abs <1e-15 and ( self . imaginary -other . imaginary ) . abs < 1e-15
43
+ end
44
+
45
+ def abs
46
+ Math . sqrt ( @real **2 +@imaginary **2 )
47
+ end
48
+
49
+ def conjugate
50
+ ComplexNumber . new ( @real , -1 *@imaginary )
51
+ end
52
+
53
+ def exp
54
+ real = Math . exp ( @real ) *Math . cos ( @imaginary )
55
+ imaginary = Math . exp ( @real ) *Math . sin ( @imaginary )
56
+ ComplexNumber . new ( real , imaginary )
57
+ end
58
+ end
0 commit comments