Details

Type: Bug

Status: Open

Priority: Major

Resolution: Unresolved

Affects Version/s: None

Fix Version/s: None

Component/s: Mathematics

Labels:None
Description
Multiplication of two polynomials sometimes gives the wrong answer (see example attached). This is due to an error in the code for Polynomial.times. The output of the example is given below
p = [1]a² + [2]ab + [1]b²
q = [1]a5 + [5]a4b + [10]a³b²
p.times(q) = [1]a7 + [3]a6b + [11]a5b² + [15]a4b³ + [10]a³b4
q.times(p) = [1]a7 + [3]a6b + [1]a5b² + [15]a4b³ + [10]a³b4
p.times(q) is wrong, while q.times(p) is correct. During calculation of p.times(q), the coefficient of a5b2 goes to 0 = 10+(10). It should then either be set to zero in the _termToCoef entry set, or be removed from this entry set, until it is again nonzero in further iterations. I chose the second option (removal), and the correct code looks like this
public Polynomial<R> times(Polynomial<R> that) {
Polynomial<R> result = Polynomial.newInstance();
R zero = null;
for (Map.Entry<Term, R> entry1 : this._termToCoef.entrySet()) {
Term t1 = entry1.getKey();
R c1 = entry1.getValue();
for (Map.Entry<Term, R> entry2 : that._termToCoef.entrySet()) {
Term t2 = entry2.getKey();
R c2 = entry2.getValue();
Term t = t1.times(t2);
R c = c1.times(c2);
R prev = result.getCoefficient(t);
R coef = (prev != null) ? prev.plus(c) : c;
if (isZero(coef))
else
{ result._termToCoef.put(t, coef); }}
}
if (result._termToCoef.size() == 0)
return Constant.valueOf(zero);
return result;
}
Here is a patch for this issue.