java - 如何在 Complex 类中实现 square()、modulus Squared() 和 add() 方法?

标签 java methods complex-numbers

我有一个名为Complex的类,它具有实数和虚数的访问器方法,以及将复数表示为字符串的方法和获取复数大小的方法。我在实现最后三个方法 square()(对复数求平方)、modulusSquared()(返回复数模数的平方)和最后 >add(Complex d),它将把复数 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);

    }

}

感谢您的宝贵时间。

最佳答案

您的 addsquare 方法非常简单。据我了解 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); 
}

关于java - 如何在 Complex 类中实现 square()、modulus Squared() 和 add() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35853761/

相关文章:

c - 如果使用实数,C 如何处理复杂的方程式

java - 如何获取复数值?

java - "class A <T extends SomeClass<T>>"与 B 类 <T extends SomeInterface<T>> 的工作方式不同? (是的)

java - 如何在一种方法中获取用户输入并在另一种方法中使用它

javascript - 如何在对象中使用 .includes() 或类似方法?

Ruby:在方法之间传递选项参数

javascript - 我需要帮助弄清楚如何在计算复数时修复输出

java - 是否可以使用 plafyramework2 for java 和 groovy 模板?

Java 使用 For 循环移动数组中的元素

java - 名称为 [DEFAULT] 的 FirebaseApp 不存在。 (对于 Spring 启动)