1、代码。
package com.zxj.reptile.utils.number;
public class Complex {
private double real;//实数
private double image;//虚数
public Complex() {
real = 0;
image = 0;
}
public Complex(double real, double image) {
this.real = real;
this.image = image;
}
//加:(a+bi)+(c+di)=(a+c)+(b+d)i
public Complex add(Complex complex) {
double real = complex.getReal();
double image = complex.getImage();
double newReal = this.real + real;
double newImage = this.image + image;
return new Complex(newReal, newImage);
}
//减:(a+bi)-(c+di)=(a-c)+(b-d)i
public Complex sub(Complex complex) {
double real = complex.getReal();
double image = complex.getImage();
double newReal = this.real - real;
double newImage = this.image - image;
return new Complex(newReal, newImage);
}
//乘:(a+bi)(c+di)=(ac-bd)+(bc+ad)i
public Complex mul(Complex complex) {
double real = complex.getReal();
double image = complex.getImage();
double newReal = this.real * real - this.image * image;
double newImage = this.image * real + this.real * image;
return new Complex(newReal, newImage);
}
//乘:a(c+di)=ac+adi
public Complex mul(double multiplier) {
return mul(new Complex(multiplier, 0));
}
//除:(a+bi)/(c+di)=(ac+bd)/(c^2+d^2) +((bc-ad)/(c^2+d^2))i
public Complex div(Complex complex) {
double real = complex.getReal();
double image = complex.getImage();
double denominator = real * real + image * image;
double newReal = (this.real * real + this.image * image) / denominator;
double newImage = (this.image * real - this.real * image) / denominator;
return new Complex(newReal, newImage);
}
//欧拉公式 e^(ix)=cosx+isinx
public static Complex euler(double x) {
double newReal = Math.cos(x);
double newImage = Math.sin(x);
return new Complex(newReal, newImage);
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImage() {
return image;
}
public void setImage(double image) {
this.image = image;
}
@Override
public String toString() {
String str = "";
if (real != 0) {
str += real;
} else {
str += "0";
}
if (image < 0) {
str += image + "i";
} else if (image > 0) {
str += "+" + image + "i";
}
return str;
}
}
2、复数四则运算的例子。
package com.zxj.reptile.test.number;
import com.zxj.reptile.utils.number.Complex;
public class ComplexTest {
public static void main(String[] args) {
Complex ab = new Complex(2, 3);
Complex cd = new Complex(5, -4);
double multiplier = -1;
System.out.println("复数四则运算的例子:");
System.out.println(String.format("加发: (%s) + (%s) = (%s)", ab, cd, ab.add(cd)));
System.out.println(String.format("减法: (%s) - (%s) = (%s)", ab, cd, ab.sub(cd)));
System.out.println(String.format("乘法: (%s) * (%s) = (%s)", ab, cd, ab.mul(cd)));
System.out.println(String.format("乘法: (%s) * (%f) = (%s)", ab, multiplier, ab.mul(multiplier)));
System.out.println(String.format("除法: (%s) / (%s) = (%s)", ab, cd, ab.div(cd)));
}
}
3、结果。