Gist link to my code. The problem I'm having uses the class Polynomial, method multiply, lines 136-172.
Here is the method:
public Polynomial multiply(Polynomial right){
int size = right.length + length -1;
int i;
int r;
Complex productCoeff;
Complex coeffP = new Complex();
Complex coeffQ = new Complex();
Complex currentValue;
Polynomial temp = new Polynomial(size);
for (i = 0; i < length; i++)
{
for (r = 0; r < right.length; r++) {
coeffP = (retrieveAt(i));
coeffQ = (right.retrieveAt(r));
productCoeff = coeffP.multiplyComplex(coeffQ);
if (temp.retrieveAt(i+r) == null)
currentValue = productCoeff;
else
currentValue = (temp.retrieveAt(i+r));
currentValue = currentValue.addComplex(productCoeff);
temp.replaceAt(i+r, currentValue);
}
}
return temp;
}
I was given the class Polynomial and am trying to implement complex numbers for addition, subtraction, and multiplication. The class polynomial works by storing the coefficients into an array. [x^0, x^1, x^2, x^3 ...] I got the addition and subtraction to work with complex numbers, but I am having trouble getting the multiplication to work correctly.
My thought process for multiplying complex numbers: For each item that is being looped through in the first array, I want to loop through all the items in the second array and multiply. After each series of multiplication, I want to store this value into the temporary array. If the temporary array has a value at that location, I want to add the multiplied value to the value stored at that position in the temporary array. If there is no value at that location in the temporary array, I can simply replace it.
The method worked for regular polynomials, but when using complex numbers I am getting incorrect answers. For example:
((1+2i)+(3+4i)x) ((2+7i)+(4+3i)x)
should equal (-12+11i) + (-24+40i)x + (25i)x^2
but when I run the program my answer is (-24+22i) + (-26+51i)x + (50i)x^2
. So, it looks like some things are being doubled, but I can't figure out why.
Can anyone figure out why the multiplication is not correct?