-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathComplexNumber.java
More file actions
38 lines (30 loc) · 1.21 KB
/
ComplexNumber.java
File metadata and controls
38 lines (30 loc) · 1.21 KB
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
package com.example.task03;
public class ComplexNumber {
private final double realPart;
private final double imaginaryPart;
public ComplexNumber(double realPart, double imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public double getRealPart() {
return realPart;
}
public double getImaginaryPart() {
return imaginaryPart;
}
public ComplexNumber add(ComplexNumber other) {
double newReal = this.realPart + other.realPart;
double newImaginary = this.imaginaryPart + other.imaginaryPart;
return new ComplexNumber(newReal, newImaginary);
}
public ComplexNumber multiply(ComplexNumber other) {
// (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
double newReal = this.realPart * other.realPart - this.imaginaryPart * other.imaginaryPart;
double newImaginary = this.realPart * other.imaginaryPart + this.imaginaryPart * other.realPart;
return new ComplexNumber(newReal, newImaginary);
}
public String toString() {
if (imaginaryPart >= 0) return realPart + "+" + imaginaryPart + "i";
else return realPart + " - " + Math.abs(imaginaryPart) + "i";
}
}