[英]How can I implement my square(), modulusSqaured() and add() methods in my Complex class?
我有一個名為Complex
的類,該類具有用於實數和虛數的訪問器方法,以及一種將復雜數表示為字符串的方法和一種用於獲取該復雜數的大小的方法。 我在實現我的最后三個方法square()
時遇到麻煩, square()
對復數進行平方, modulusSquared()
量模量modulusSquared()
,該方法返回復數模量的平方,最后add(Complex d)
,這會將add(Complex d)
添加到此復數數。 我已經嘗試過了,但是我想我理解這是錯誤的。 這是我的代碼:
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);
}
}
謝謝你的時間。
您的add
和square
方法非常簡單。 據我了解, modulusSquared
是| x + iy | = Square Root(x ^ 2 + y ^ 2) ,因此實現也非常簡單:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.