/Users/lyon/j4p/src/math/Complex.java
|
1 package math;
2
3 public class Complex {
4 private double real;
5 private double imaginary;
6
7 public Complex(double _x, double _y) {
8 real = _x;
9 imaginary = _y;
10 }
11
12 public Complex() {
13 real = 0;
14 imaginary = 0;
15 }
16
17 public void set(double _x, double _y) {
18 real = _x;
19 imaginary = _y;
20 }
21
22 public void setReal(double _x) {
23 real = _x;
24 }
25
26 public void setImaginary(double _i) {
27 imaginary = _i;
28 }
29
30 public void addReal(double _x) {
31 real += _x;
32 }
33
34 public void addImaginary(double _i) {
35 imaginary += _i;
36 }
37
38 public double getReal() {
39 return real;
40 }
41
42 public double getImaginary() {
43 return imaginary;
44 }
45
46 // c = a + b, c=a.plus(b)
47 public Complex plus(Complex b) {
48 return new Complex(
49 b.real + real,
50 b.imaginary + imaginary);
51 }
52
53 // c = a - b, c=a.minus(b);
54 public Complex minus(Complex b) {
55 return new Complex(
56 real - b.real,
57 imaginary - b.imaginary);
58 }
59
60 // c = a * b, c=a.times(b);
61 //(x1 + iy1)(x2 + iy2) =
62 // x1 * x2 - y1 * y2 +
63 // i(y1 * x2 + x1 * y2)
64 public Complex times(Complex b) {
65 return new Complex(
66 real * b.real - imaginary * b.imaginary,
67 imaginary * b.real + real * b.imaginary);
68 }
69
70 // c = a.abs()
71 public Complex abs() {
72 return new Complex(
73 Math.abs(real),
74 Math.abs(imaginary)
75 );
76 }
77
78 // c = 1/a, c=inverse(a);
79 public Complex inverse() {
80 double m = square();
81 return new Complex(
82 real / m,
83 -imaginary / m
84 );
85 }
86
87 // c = a^2, c = a.square();
88 public double square() {
89 return real * real + imaginary * imaginary;
90 }
91
92 // c = |a|, c=a.magnitude()
93 public double magnitude() {
94 return Math.sqrt(square());
95 }
96
97 // makes a copy of this
98 // c = a.copy();
99 public Complex copy() {
100 return new Complex(real, imaginary);
101 }
102
103 public void print() {
104 System.out.println("Complex: real = " + real + " Imaginary = " + imaginary);
105 }
106
107 public void print(String msg) {
108 System.out.println(msg + "(" + real + "," + imaginary + ")");
109 }
110 }