# [Numpy-tickets] [NumPy] #387: Small polynomial bug (with patch suggestion)

NumPy numpy-tickets at scipy.net
Wed Nov 22 07:41:06 CST 2006

```#387: Small polynomial bug (with patch suggestion)
----------------------+-----------------------------------------------------
Reporter:  clovisgo  |       Owner:  somebody
Type:  defect    |      Status:  new
Priority:  normal    |   Milestone:  1.0 Release
Component:  Other     |     Version:
Severity:  normal    |    Keywords:
----------------------+-----------------------------------------------------
{{{
Subject: Small bug in polynomial
There seems to exist a small bug in the numpy.polynomial functions:
Consider the following script:

################################
import numpy
poly1 = numpy.poly1d([1.0])
poly2 = numpy.poly1d([1.0, 1.0])
poly3 = numpy.poly1d([2.0,1.0])
print "Poly1 is"
print poly1
print type(poly1)
print "Poly2 is"
print poly2
print type(poly2)
print "Poly3 is"
print poly3
print type(poly3)
print "Poly1+Poly2 = "
print auxvar
print type(auxvar)
print "Poly2+Poly3 = "
print auxvar
print type(auxvar)
################################

Raw output is given below:

Poly1 is
1
<class 'numpy.lib.polynomial.poly1d'>
Poly2 is
1 x + 1
<class 'numpy.lib.polynomial.poly1d '>
Poly3 is
2 x + 1
<class 'numpy.lib.polynomial.poly1d'>
Poly1+Poly2 =
1 x + 2
<class 'numpy.lib.polynomial.poly1d'>
Poly2+Poly3 =
[ 3.  2.]
<type 'numpy.ndarray'>

################################
The result shoud be:
3 x + 2
and the type should be
<class 'numpy.lib.polynomial.poly1d'>
and not:
<type ' numpy.ndarray'>

The same problem exists with polysub.
The solution seems to be simple. The original
code for the polyadd function (with line numbers) is:

2       """Adds two polynomials represented as sequences
3       """
4       truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
5       a1 = atleast_1d(a1)
6       a2 = atleast_1d(a2)
7       diff = len(a2) - len(a1)
8       if diff == 0:
9           return a1 + a2
10       elif diff > 0:
11          zr = NX.zeros(diff, a1.dtype)
12          val = NX.concatenate((zr, a1)) + a2
13       else:
14          zr = NX.zeros(abs(diff), a2.dtype)
15          val = a1 + NX.concatenate((zr, a2))
16      if truepoly:
17          val = poly1d(val)
18      return val

In order to correct the problem is sufficient
to replace the original line #9 by:

9        val = a1 + a2

If this change is made, the return value
will be an array (if input variables are
arrays) or a poly1d (if one of the input
variables are polynomials).

A similar change should be made for the polysub function.
Clovis
}}}

--
Ticket URL: <http://projects.scipy.org/scipy/numpy/ticket/387>
NumPy <http://projects.scipy.org/scipy/numpy>
The fundamental package needed for scientific computing with Python.
```