/** * A complex number with a real and imaginary part * * @author Phill Conrad * @version lab04 for CS10, Spring 2009 */ public class Complex { private double real; private double imag; /** * noarg Constructor for objects of class Complex */ public Complex() { real = 0; imag = 0; } /** * Two-arg Constructor for objects of class Complex * @param realPart real part * @param imagPart imaginary part */ public Complex(double realPart, double imagPart) { real = realPart; imag = imagPart; } /** * get the real part * @return real part */ public double getReal() { return real;} /** * get the imaginary part * @return imaginary part */ public double getImag() { return imag;} /** format Complex number as an expression like: * 2.0 + 3.0i, 2.5 + 0.0i, 0.0 + 0.0i, or -3.33 + -1.5i * * @return formatted complex number (e.g. 2.0 + 3.0i) */ public String toString() { return real + " + " + imag + "i"; } /** static method to add two complex numbers * * @param c1 a complex number * @param c2 a complex number * @return c1 + c2 */ public static Complex add(Complex c1, Complex c2) { // @@@ First, consult the testAdd1 and testAdd2 methods in ComplexTest // to review how we add complex numbers // @@@ Then, FILL IN THE BLANKS then uncomment this code // double first = c1._______ + c2.__________ ; // double last = __________ + _____________ ; // return new Complex(first, last); return new Complex(-99.9, -99.9); // @@@ stub -- remove when done } /** static method to multiply two complex numbers * * @param c1 a complex number * @param c2 a complex number * @return c1 * c2 */ public static Complex multiply(Complex c1, Complex c2) { // @@@ First, consult the testAdd1 and testAdd2 methods in ComplexTest // to review how we add complex numbers // @@@ Then, FILL IN THE BLANKS then uncomment this code //double first = __________________ ; //double outer = __________________ ; //double inner = __________________; //double last = ____________________; //return new Complex(_________, ____________); return new Complex(-99.9, -99.9); // @@@ stub -- remove when done } /** compare two Complex numbers for equality---if the difference in the * real part and the difference in the imaginary part of "this" object and * the c2 object it is being compared with are BOTH less than tol, * return true. For example, we can write: *
if (c1.equals(c2,TOL)) { System.out.println("equal"); }
*
* @param c2 a complex number
* @param tol the tolerance with which the corresponding real and imag parts of this
* object and c2 are compared
* @return true if c1 and c2 are approximately equal
*/
public boolean approxEquals(Complex c2, double tol)
{
return Math.abs(this.real - c2.real) < tol &&
Math.abs(this.imag- c2.imag) < tol;
}
}