Skip to content

Instantly share code, notes, and snippets.

@xuanthulabnet
Created September 11, 2019 16:20
Show Gist options
  • Select an option

  • Save xuanthulabnet/a899e15113174be7c6fdb5bf8af48e93 to your computer and use it in GitHub Desktop.

Select an option

Save xuanthulabnet/a899e15113174be7c6fdb5bf8af48e93 to your computer and use it in GitHub Desktop.
package net.xuanthulab;
public class Complex {
private double re; // phần thực
private double im; // phần ảo
//Thiết lập phần thực vào ảo
private void Init(double re, double im) {
this.re = re;
this.im = im;
};
// Khởi tạo mặc định, không tham số (phần ảo, thực bằng 0)
public Complex() {
Init(0,0);
}
// Khởi tạo với phần thực và phần ảo
public Complex(double re, double im) {
Init(re, im);
}
// Khởi tạo 1 tham số là phần thực, phần ảo bằng 0
public Complex(double re) {
Init(re, 0);
}
// Khởi tạo từ một số phức khác
public Complex(Complex complex) {
Init(complex.getRe(), complex.getIm());
}
//Getter thuộc tinh phần thực re
public double getRe() {
return re;
}
public double getIm() {
return im;
}
//Setter thuộc tinh phần thực re
public void setRe(double re) {
this.re = re;
}
public void setIm(double im) {
this.im = im;
}
// phép cộng hai số phức a + b
public static Complex cong(Complex a, Complex b) {
double real = a.re + b.re;
double imag = a.im + b.im;
return new Complex(real, imag);
}
// Trừ 2 số phức a - b
public static Complex tru(Complex a, Complex b) {
double real = a.re - b.re;
double imag = a.im - b.im;
return new Complex(real, imag);
}
// Nhân 2 số phức a * b
public static Complex nhan(Complex a,Complex b) {
double real = a.re * b.re - a.im * b.im;
double imag = a.re * b.im + a.im * b.re;
return new Complex(real, imag);
}
// Chia 2 số phức a / b
public static Complex chia(Complex a, Complex b) {
double _re = b.getRe();
double _im = b.getIm();
double scale = _re*_re + _im*_im;
return nhan(a, new Complex(_re / scale, -_im / scale));
}
public String toString() {
if (im == 0) return re + "";
if (re == 0) return im + "i";
if (im < 0) return re + " - " + (-im) + "i";
return re + " + " + im + "i";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment