Issue Details (XML | Word | Printable)

Key: JSCIENCE-3
Type: Bug Bug
Status: Open Open
Priority: Major Major
Assignee: Unassigned
Reporter: sbrisard
Votes: 0
Watchers: 0
Operations

If you were logged in you would be able to see more operations.
jscience

Error in multiplication of two Polynomials

Created: 01/Apr/11 11:51 AM   Updated: 01/Apr/11 11:51 AM
Component/s: None
Affects Version/s: None
Fix Version/s: None

Time Tracking:
Not Specified

File Attachments: 1. Java Source File DemoBug.java (1 kB) 01/Apr/11 11:51 AM - sbrisard

Environment:

Any


Tags:


 Description  « Hide

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]
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 non-zero 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)) { zero = coef; result._termToCoef.remove(t); // NOTE : Added this line } else { result._termToCoef.put(t, coef); }
}
}
if (result._termToCoef.size() == 0)
return Constant.valueOf(zero);
return result;
}



There are no comments yet on this issue.