如何在 java 中处理复数?
How to work with complex numbers in java?
我是 java 的新手,不确定如何处理 java 中的复数。我正在为我的项目编写代码。我用欧拉恒等式exp(itheeta) = cos(theeta)+iSin(theeta)求出exp(i*2*pi*f)。我必须将这个生成的复数与数组 "d" 中的另一个数字相乘。这是我所做的
Complex Data[][] = new Complex[20][20];
for (int j = 0; j < d.size(); j++){
for (int k = 0; k<20; k++){
for (int l = 0; l<20; l++){
double re = Math.cos(2 * Math.PI * f);
double im = Math.sin(2 * Math.PI * f);
Complex p = new Complex(re, im);
Data[k][l] = ((d.get(j) * p.getReal()), (d.get(j) * p.getImaginary()));
}
}
}
但是,我在表达式 Data[k][l] = ((d.get(j) * p.getReal()), (d.get(j) * p.getImaginary()));
说 "The left-hand side of an assignment must be a variable" 时遇到错误。
请帮我解决这个问题。谢谢
不幸的是,它不像在 C++ 中那样使用复制构造函数或重载赋值运算符。
您必须显式调用复合体的构造函数,例如
Data[k][l] = new Complex(realValue, imaginaryVal);
当然,您需要使用复数的方法来将两个数相乘,因为 Java.
中没有任何其他运算符重载的概念
所以,也许 Complex
class 可能有一些您可以使用的方法来代替运算符,例如
class Complex {
public static Complex mul(Complex c0, Complex c1) {
double r0=c.getRe(), r1=c1.getRe();
double i0=c.getIm(), i1=c1.getIm();
return new Complex(r0*r1-i0*i1, r0*i1+r1*i0);
}
public static Complex mulStore(Complex res, Complex c0, Complex c1) {
double r0=c.getRe(), r1=c1.getRe();
double i0=c.getIm(), i1=c1.getIm();
if(res==null) {
res=new Complex();
}
res.setRe(r0*r1-i0*i1);
res.setIm(r0*i1+r1*i0);
return res;
}
// equiv with this *= rhs;
public void mulAssign(Complex rhs) {
// perform the "this * rhs" multiplication and
// store the result in this.
Complex.mulStore(this, rhs, this);
}
}
我是 java 的新手,不确定如何处理 java 中的复数。我正在为我的项目编写代码。我用欧拉恒等式exp(itheeta) = cos(theeta)+iSin(theeta)求出exp(i*2*pi*f)。我必须将这个生成的复数与数组 "d" 中的另一个数字相乘。这是我所做的
Complex Data[][] = new Complex[20][20];
for (int j = 0; j < d.size(); j++){
for (int k = 0; k<20; k++){
for (int l = 0; l<20; l++){
double re = Math.cos(2 * Math.PI * f);
double im = Math.sin(2 * Math.PI * f);
Complex p = new Complex(re, im);
Data[k][l] = ((d.get(j) * p.getReal()), (d.get(j) * p.getImaginary()));
}
}
}
但是,我在表达式 Data[k][l] = ((d.get(j) * p.getReal()), (d.get(j) * p.getImaginary()));
说 "The left-hand side of an assignment must be a variable" 时遇到错误。
请帮我解决这个问题。谢谢
不幸的是,它不像在 C++ 中那样使用复制构造函数或重载赋值运算符。
您必须显式调用复合体的构造函数,例如
Data[k][l] = new Complex(realValue, imaginaryVal);
当然,您需要使用复数的方法来将两个数相乘,因为 Java.
中没有任何其他运算符重载的概念所以,也许 Complex
class 可能有一些您可以使用的方法来代替运算符,例如
class Complex {
public static Complex mul(Complex c0, Complex c1) {
double r0=c.getRe(), r1=c1.getRe();
double i0=c.getIm(), i1=c1.getIm();
return new Complex(r0*r1-i0*i1, r0*i1+r1*i0);
}
public static Complex mulStore(Complex res, Complex c0, Complex c1) {
double r0=c.getRe(), r1=c1.getRe();
double i0=c.getIm(), i1=c1.getIm();
if(res==null) {
res=new Complex();
}
res.setRe(r0*r1-i0*i1);
res.setIm(r0*i1+r1*i0);
return res;
}
// equiv with this *= rhs;
public void mulAssign(Complex rhs) {
// perform the "this * rhs" multiplication and
// store the result in this.
Complex.mulStore(this, rhs, this);
}
}