Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Complex {
- private final double real;
- private final double imaginary;
- /** A convenience method, shorter than a constructor call, for
- * creating complex numbers.
- * @param real The real component of the number.
- * @param imaginary The imaginary component of the number.
- * @return An immutable instance of <code>Complex</code>
- * representing the indicated number.
- */
- public Complex(double real, double imaginary) {
- this.real = real;
- this.imaginary = imaginary;
- }
- /** The real component of this number. */
- public double getReal() {
- return this.real;
- }
- /** The imaginary component of this number. */
- public double getImaginary(){
- return this.imaginary;
- }
- public boolean isZero(){
- return this.real == 0 && this.imaginary == 0;
- }
- public double getMagnitude(){
- return Math.hypot(real, imaginary);
- }
- public Complex add(Complex that){
- Complex a = this;
- double real = a.real + that.real; // or a.getReal() + that.getReal();
- double imaginary = a.getImaginary() + that.getImaginary();
- return new Complex(real, imaginary);
- }
- public Complex subtract(Complex that){
- Complex a = this;
- double real = a.real - that.real;
- double imaginary = a.getImaginary() - that.getImaginary();
- return new Complex(real, imaginary);
- }
- /** Returns the product of this number and <code>that</code>. Does
- * not change either <code>this</code> or the argument. We use the
- * standard definition of complex arithmetic; see for example
- * http://mathworld.wolfram.com/ComplexNumber.html . */
- public Complex multiply(Complex that){
- Complex a = this;
- double real = (a.real * that.real) - (a.imaginary * that.imaginary);
- double imaginary =
- (a.getReal() * that.getImaginary()) + (a.getImaginary() * that.getReal());
- return new Complex(real, imaginary);
- }
- /** Returns the quotient of this number over <code>that</code>.
- * Does not change either <code>this</code> or the argument. We use
- * the standard definition of complex arithmetic; see for example
- * http://mathworld.wolfram.com/ComplexNumber.html . */
- public Complex dividedBy(Complex that){
- // FILL IN
- // Multiply the expression by the conjugate of the divisor/denominator!!!!
- return this;
- }
- public Complex conjugate() {
- return new Complex(real, -imaginary); // CALL THIS METHOD IN THE dividedBy() method!
- }
- public Complex reciprocal() {
- return this; // FILL IN THEN CALL THIS METHOD IN THE dividedBy() method!
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment