Reputation: 719
I have a class called Complex
which has accessor methods for the real and imaginary numbers as well as a method to represent the complex number as a string and a method to get the magnitude of the complex number. I am having trouble implementing my last three methods square()
, which squares the complex number, modulusSquared()
, which returns the square of modulus of complex number and lastly add(Complex d)
, which will add the complex number d to this complex number. I have attempted this but I think I am understanding this wrong. Here is my code:
public class Complex { //real + imaginary*i
private double re;
private double im;
public Complex(double real, double imaginary) {
this.re = real;
this.im = imaginary;
}
public String toString() { //display complex number as string
StringBuffer sb = new StringBuffer().append(re);
if (im>0)
sb.append('+');
return sb.append(im).append('i').toString();
}
public double magnitude() { //return magnitude of complex number
return Math.sqrt(re*re + im*im);
}
public void setReal(double m) {
this.re = m;
}
public double getReal() {
return re;
}
public void setImaginary(double n) {
this.im = n;
}
public double getImaginary() {
return im;
}
public void square() { //squares complex number
Complex = (re + im)*(re + im);
}
public void modulusSquared() { //returns square of modulus of complex number
Math.abs(Complex);
}
public void add(Complex d) { //adds complex number d to this number
return add(this, d);
}
}
Thanks for your time.
Upvotes: 1
Views: 355
Reputation: 6767
Your add
and square
methods are pretty straightforward. From what I understand modulusSquared
is |x+iy| = Square Root(x^2 + y^2), so the implementation is also really simple for that, too:
public void add(Complex d) { // adds complex number d to this number
this.re += d.getReal(); // add real part
this.im += d.getImaginary();// add imaginary part
}
public void square(){
double temp1 = this.re * this.re; // real * real
double temp2 = this.re * this.im; // real * imaginary (will be the only one to carry around an 'i' wth it
double temp3 = -1 * this.im * this.im; // squared imaginary so multiply by -1 (i squared)
this.re = temp1 + temp3; // do the math for real
this.im = temp2; // do the math for imaginary
}
public double modulusSquared() { // gets the modulus squared
return Math.sqrt(this.re * this.re + this.im * this.im);
}
Upvotes: 1