A complex number is a number in the form a+bi, where a and b are real numbers and i is
(square root of -1).
The numbers a and b are known as the real part and imaginary part of the complex number, respectively. You can perform addition, subtraction, multiplication, and division for complex numbers using the following formulas:
a+bi+c+di = (a + c) + (b+d)i
a+bi (c+di) = (ac) + (b-d)i
(a + bi)*(c+di) = (ac-bd) + (bc + ad)i (a + bi)/(c+di) = (ac+bd)/(c² +d²) + (bc-ad)i/(c² +d²)
You can also obtain the absolute value for a complex number using the following formula:
|a + bil= √a² + b²
(A complex number can be interpreted as a point on a plane by identifying the (a,b) values as the coordinates of the point. The absolute value of the complex number corresponds to the distance of the point to the origin)
Design a class named Complex for representing complex numbers and the methods add, subtract,
multiply, divide, and abs for performing complex-number operations, and override toStrin
public class Complex {
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public double getReal() { return real; }
public double getImaginary() { return imaginary; }
public static Complex add(final Complex lhs, final Complex rhs) {
return new Complex(lhs.real + rhs.real, lhs.imaginary + rhs.imaginary);
}
public static Complex subtract(final Complex lhs, final Complex rhs) {
return new Complex(lhs.real - rhs.real, lhs.imaginary - rhs.imaginary);
}
public static Complex multiply(final Complex lhs, final Complex rhs) {
return new Complex((lhs.real * rhs.real - lhs.imaginary * rhs.imaginary),
(lhs.real * rhs.imaginary + lhs.imaginary * rhs.real));
}
public static Complex divide(final Complex lhs, final Complex rhs) {
double dominator = rhs.real * rhs.real + rhs.imaginary * rhs.imaginary;
return new Complex((lhs.real * rhs.real + lhs.imaginary * rhs.imaginary) / dominator,
(lhs.real * rhs.imaginary + lhs.imaginary * rhs.real) / dominator);
}
public static double abs(final Complex complex) {
return Math.sqrt(complex.real * complex.real + complex.imaginary * complex.imaginary);
}
@Override
public String toString() {
return String.format("( %.2f ) + ( %.2f ) i", real, imaginary);
}
}
Comments
Leave a comment