java - Polynomial Multiplication with Complex Numbers Class -
gist link code. the problem i'm having uses class polynomial, method multiply, lines 136-172.
here 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); (i = 0; < length; i++) { (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 given class polynomial , trying implement complex numbers addition, subtraction, , multiplication. class polynomial works storing coefficients array. [x^0, x^1, x^2, x^3 ...] got addition , subtraction work complex numbers, having trouble getting multiplication work correctly.
my thought process multiplying complex numbers: each item being looped through in first array, want loop through items in second array , multiply. after each series of multiplication, want store value temporary array. if temporary array has value @ location, want add multiplied value value stored @ position in temporary array. if there no value @ location in temporary array, can replace it.
the method worked regular polynomials, when using complex numbers getting incorrect answers. example:
((1+2i)+(3+4i)x) ((2+7i)+(4+3i)x) should equal (-12+11i) + (-24+40i)x + (25i)x^2 when run program answer (-24+22i) + (-26+51i)x + (50i)x^2. so, looks things being doubled, can't figure out why.
can figure out why multiplication not correct?
as saka1029 mentioned: code's indentation not match logical structure. if-else construct
if (temp.retrieveat(i+r) == null) currentvalue = productcoeff; else currentvalue = (temp.retrieveat(i+r)); currentvalue = currentvalue.addcomplex(productcoeff); will interpreted as
if (temp.retrieveat(i+r) == null) { currentvalue = productcoeff; } else { currentvalue = (temp.retrieveat(i+r)); } currentvalue = currentvalue.addcomplex(productcoeff); meaning last line executed on every iteration of for loop, no matter above condition yields. if looks pedantic, write braces avoid hard track errors this. see is ok if omit curly braces in java?. , if jon skeet it, should you!
Comments
Post a Comment