jscience
  1. jscience
  2. JSCIENCE-152

Error in multiplication of two Polynomials

    Details

    • Type: Bug Bug
    • Status: Open
    • Priority: Major 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]
      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;
      }

      1. DemoBug.java
        1 kB
        sbrisard
      2. jscience-152.patch.diff
        0.5 kB
        celestin

        Activity

        Hide
        celestin added a comment -

        Here is a patch for this issue.

        Show
        celestin added a comment - Here is a patch for this issue.

          People

          • Assignee:
            Unassigned
            Reporter:
            sbrisard
          • Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

            • Created:
              Updated: