Complex 运算,complex运算,package numb
分享于 点击 3306 次 点评:123
Complex 运算,complex运算,package numb
package number.complex;public class Complex { private double real; private double img; /** * default constructor */ public Complex() { this.img = this.real = 0.0; } /** * constructor * * @param real * @param img */ public Complex(double real, double img) { this.img = img; this.real = real; } /** * @param arg * @return new complex */ public Complex divide(Complex arg) { double root = arg.img * arg.img + arg.real * arg.real; double real = (this.real * arg.real + this.img * arg.img) / root; double img = (this.real * arg.img - this.img * arg.real) / root; return new Complex(real, img); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!(obj instanceof Complex)) { return false; } Complex other = (Complex) obj; if (Double.doubleToLongBits(img) != Double.doubleToLongBits(other.img)) { return false; } if (Double.doubleToLongBits(real) != Double .doubleToLongBits(other.real)) { return false; } return true; } /** * get complex's img part * * @return */ public double getImg() { return img; } /** * get complex's real part * * @return */ public double getReal() { return real; } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(img); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(real); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } /** * @param arg * @return new complex */ public Complex minus(Complex arg) { return new Complex(this.real - arg.real, this.img - arg.img); } /** * @param arg * @return new complex */ public Complex multiply(Complex arg) { double real = this.real * arg.real - this.img * arg.img; double img = this.real * arg.img + this.img * arg.real; return new Complex(real, img); } /** * @param arg * @return new complex */ public Complex plus(Complex arg) { return new Complex(this.real + arg.real, this.img + arg.img); } /** * set comple's img part * * @param img */ public void setImg(double img) { this.img = img; } /** * set complex's real part * * @param real */ public void setReal(double real) { this.real = real; } /** * * @see java.lang.Object#toString() */ @Override public String toString() { return "Complex [real=" + real + ", img=" + img + "]"; } public static void main(String[] args) { Complex complex = new Complex(3, 4); Complex complex1 = new Complex(1, 2); System.out.println(complex.plus(complex1)); System.out.println(complex.minus(complex1)); System.out.println(complex.divide(complex1)); System.out.println(complex.multiply(complex1)); } /* result */ // Complex [real=4.0, img=6.0] // Complex [real=2.0, img=2.0] // Complex [real=2.2, img=0.4] // Complex [real=-5.0, img=10.0]}//该片段来自于http://byrx.net
用户点评