Created
September 7, 2012 04:15
-
-
Save klgraham/3663085 to your computer and use it in GitHub Desktop.
Complex arithmetic in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Complex { | |
private double real; | |
private double imag; | |
public Complex(final double real, final double imag) { | |
this.real = real; | |
this.imag = imag; | |
} | |
public double real() { | |
return real; | |
} | |
public double imag() { | |
return imag; | |
} | |
public Complex add(final Complex that) { | |
return new Complex(this.real + that.real, this.imag + that.imag); | |
} | |
public Complex subtract(final Complex that) { | |
return new Complex(this.real - that.real, this.imag - that.imag); | |
} | |
public Complex mult(final Complex that) { | |
double real = this.real * that.real - this.imag * that.imag; | |
double imag = this.real * that.imag + this.imag * that.real; | |
return new Complex(real, imag); | |
} | |
public static double mod(final Complex z) { | |
return Math.sqrt(z.real * z.real + z.imag * z.imag); | |
} | |
public Complex divide(final Complex that) { | |
double real = this.real * that.real + this.imag * that.imag; | |
double imag = this.imag * that.real - this.real * that.imag; | |
double denom = mod(that); | |
return new Complex(real / denom, imag / denom); | |
} | |
public Complex mult(final double scalar) { | |
return new Complex(this.real * scalar, this.imag * scalar); | |
} | |
public Complex divide(final double scalar) { | |
return new Complex(this.real / scalar, this.imag / scalar); | |
} | |
@Override | |
public String toString() { | |
return "Complex(" + this.real + ", " + this.imag + ")"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment