-
Notifications
You must be signed in to change notification settings - Fork 1
/
Complex.java
129 lines (102 loc) · 2.49 KB
/
Complex.java
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package Geometry;
public class Complex {
final double x;
final double y;
public Complex(double x) {
this.x = x;
this.y = 0;
}
public Complex(double x, double y) {
this.x = x;
this.y = y;
}
public Complex conj() {
return new Complex(x, -y);
}
public Complex sub(Complex b) {
return new Complex(x - b.x, y - b.y);
}
public Complex add(Complex b) {
return new Complex(x + b.x, y + b.y);
}
public Complex mul(Complex b) {
return new Complex(x * b.x - y * b.y, x * b.y + y * b.x);
}
public Complex div(Complex b) {
return this.mul(b.conj()).mul(1 / b.len2());
}
public Complex mul(double b) {
return new Complex(x * b, y * b);
}
public double len2() {
return x * x + y * y;
}
public double abs() {
return Math.sqrt(x * x + y * y);
}
public Complex norm() {
return abs() == 0 ? new Complex(0, 0) : mul(1 / abs());
}
public double cross(Complex b) {
return x * b.y - y * b.x;
}
double cross2(Complex b) {
return this.conj().mul(b).y;
}
public double dot(Complex b) {
return x * b.x + y * b.y;
}
double dot2(Complex b) {
return this.conj().mul(b).x;
}
public static Complex polar(double r, double theta) {
return new Complex(r * Math.cos(theta), r * Math.sin(theta));
}
public static Complex exp(Complex a) {
return polar(Math.exp(a.x), a.y);
}
public double arg() {
return Math.atan2(y, x);
}
public Complex rot90() {
return new Complex(-y, x);
}
public Complex rotate(Complex p, double angle) {
return p.sub(this).mul(exp(new Complex(0, angle))).add(this);
}
public Complex rotate2(Complex p, double angle) {
p = p.sub(this);
double cs = Math.cos(angle);
double sn = Math.sin(angle);
return new Complex(p.x * cs - p.y * sn, p.x * sn + p.y * cs).add(this);
}
public Complex reflect(Complex p, Complex q) {
Complex s = q.sub(p);
return this.sub(p).div(s).conj().mul(s).add(p);
}
public double proj(Complex p) {
return dot(p) / this.abs();
}
public static double angle(Complex a, Complex p, Complex b) {
a = a.sub(p);
b = b.sub(p);
return Math.atan2(a.cross(b), a.dot(b));
}
@Override
public String toString() {
return "Complex [x=" + x + ", y=" + y + "]";
}
// Usage example
public static void main(String[] args) {
Complex z = new Complex(3, 2);
z = z.div(z);
System.out.println(z);
System.out.println();
Complex u = new Complex(0, 0);
Complex v = new Complex(1, 0);
Complex a = u.rotate(v, Math.PI * 1.0);
Complex b = v.rot90().rot90();
System.out.println(a);
System.out.println(b);
}
}