user01 - 7 months ago 30

Java Question

I am new to java and not sure how to deal with complex numbers in java. I am writing a code for my project. I have used Euler's identity, exp(i*theeta) = cos(theeta)+i*Sin(theeta) to find exp(i*2*pi*f). I have to multiply this resulting complex number with another number from an array "d". Here is what I have done

`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()));

}

}

}

I am, however, getting an error on the expression

`Data[k][l] = ((d.get(j) * p.getReal()), (d.get(j) * p.getImaginary()));`

Please help me resolve this issue. Thanks

Answer

Unfortunately, it doesn't work like in C++ with the copy constructors or overloaded assignment operators.

You'll have to explicitly call the constructor for your complex, like in

```
Data[k][l] = new Complex(realValue, imaginaryVal);
```

Of course, you'll need use methods of the complex to multiply two numbers, because there's no notion of any other operator overload in Java.

So, perhaps the `Complex`

class might have some method which you might be able to use instead of the operators, like

```
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);
}
}
```