# numpy.poly1d () in Python

| | | | | | | | | | | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

The `numpy.poly1d()` function allows to define a polynomial function. It therefore makes it straightforward to use natural operations on polynomials.

It is a convenience class, used to encapsulate "natural‚" operations on polynomials so that said operations may take on their customary form in code.

Syntax: numpy.poly1d(arr, root, var)
Parameters :
arr : [array_like] The polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation.

root : [bool, optional] True means polynomial roots. Default is False.
var : variable like x, y, z that we need in polynomial [default is x].

Arguments :
c : Polynomial coefficient.
coef : Polynomial coefficient.
coefficients : Polynomial coefficient.
order : Order or degree of polynomial.
o : Order or degree of polynomial.
r : Polynomial root.
roots : Polynomial root.

Return: Polynomial and the operation applied

## Numpy poly1d Examples

### np.poly1d example #1

```def _break_points(num, den):
"""Extract break points over real axis and gains given these locations"""
# type: (np.poly1d, np.poly1d) -> (np.array, np.array)
dnum = num.deriv(m=1)
dden = den.deriv(m=1)
polynom = den * dnum - num * dden
real_break_pts = polynom.r
# don’t care about infinite break points
real_break_pts = real_break_pts[num(real_break_pts) != 0]
k_break = -den(real_break_pts) / num(real_break_pts)
idx = k_break >= 0   # only positives gains
k_break = k_break[idx]
real_break_pts = real_break_pts[idx]
if len(k_break) == 0:
k_break = 
real_break_pts = den.roots
return k_break, real_break_pts
```

### np.poly1d example #2

```def test_poly1d_math(self):
# here we use some simple coeffs to make calculations easier
p = np.poly1d([1., 2, 4])
q = np.poly1d([4., 2, 1])
assert_equal(p/q, (np.poly1d([0.25]), np.poly1d([1.5, 3.75])))
assert_equal(p.integ(), np.poly1d([1/3, 1., 4., 0.]))
assert_equal(p.integ(1), np.poly1d([1/3, 1., 4., 0.]))

p = np.poly1d([1., 2, 3])
q = np.poly1d([3., 2, 1])
assert_equal(p * q, np.poly1d([3., 8., 14., 8., 3.]))
assert_equal(p + q, np.poly1d([4., 4., 4.]))
assert_equal(p - q, np.poly1d([-2., 0., 2.]))
assert_equal(p ** 4, np.poly1d([1., 8., 36., 104., 214., 312., 324., 216., 81.]))
assert_equal(p(q), np.poly1d([9., 12., 16., 8., 6.]))
assert_equal(q(p), np.poly1d([3., 12., 32., 40., 34.]))
assert_equal(p.deriv(), np.poly1d([2., 2.]))
assert_equal(p.deriv(2), np.poly1d([2.]))
assert_equal(np.polydiv(np.poly1d([1, 0, -1]), np.poly1d([1, 1])),
(np.poly1d([1., -1.]), np.poly1d([0.])))
```

### np.poly1d example #3

```def test_poly1d_str_and_repr(self):
p = np.poly1d([1., 2, 3])
assert_equal(repr(p), ’poly1d([1., 2., 3.])’)
assert_equal(str(p),
’   2
’
’1 x + 2 x + 3’)

q = np.poly1d([3., 2, 1])
assert_equal(repr(q), ’poly1d([3., 2., 1.])’)
assert_equal(str(q),
’   2
’
’3 x + 2 x + 1’)

r = np.poly1d([1.89999 + 2j, -3j, -5.12345678, 2 + 1j])
assert_equal(str(r),
’            3      2
’
’(1.9 + 2j) x - 3j x - 5.123 x + (2 + 1j)’)

assert_equal(str(np.poly1d([-3, -2, -1])),
’    2
’
’-3 x - 2 x - 1’)
```

### np.poly1d example #4

```def data_analysis(e_ph, flux, method="least"):

if method == "least":
coeffs = np.polyfit(x=e_ph, y=flux, deg=11)
polynom = np.poly1d(coeffs)

x = np.linspace(e_ph, e_ph[-1], num=100)
pd = np.polyder(polynom, m=1)
indx = np.argmax(np.abs(pd(x)))
eph_c = x[indx]

pd2 = np.polyder(polynom, m=2)
p2_roots = np.roots(pd2)
p2_roots = p2_roots[p2_roots[:].imag == 0]
p2_roots = np.real(p2_roots)
Eph_fin = find_nearest(p2_roots,eph_c)
return Eph_fin, polynom

elif method == "new method":
pass

#plt.plot(Etotal, total, "ro")
#plt.plot(x, polynom(x))
```

### np.poly1d example #5

```def _systopoly1d(sys):
"""Extract numerator and denominator polynomails for a system"""
# Allow inputs from the signal processing toolbox
if (isinstance(sys, scipy.signal.lti)):
nump = sys.num
denp = sys.den

else:
# Convert to a transfer function, if needed
sys = _convert_to_transfer_function(sys)

# Make sure we have a SISO system
if (sys.inputs > 1 or sys.outputs > 1):
raise ControlMIMONotImplemented()

# Start by extracting the numerator and denominator from system object
nump = sys.num
denp = sys.den

# Check to see if num, den are already polynomials; otherwise convert
if (not isinstance(nump, poly1d)):
nump = poly1d(nump)

if (not isinstance(denp, poly1d)):
denp = poly1d(denp)

return (nump, denp)
```

### np.poly1d example #6

```def quadraticInterpolation(valueList2d, numDegrees, n,
startTime=None, endTime=None):
’’’
Generates a series of points on a smooth curve that cross the given points

numDegrees - the degrees of the fitted polynomial
- the curve gets weird if this value is too high for the input
n - number of points to output
startTime/endTime/n - n points will be generated at evenly spaced
intervals between startTime and endTime
’’’
_numpyCheck()

x, y = zip(*valueList2d)

if startTime is None:
startTime = x
if endTime is None:
endTime = x[-1]

polyFunc = np.poly1d(np.polyfit(x, y, numDegrees))

newX = np.linspace(startTime, endTime, n)

retList = [(n, polyFunc(n)) for n in newX]

return retList
```

### np.poly1d example #7

```def fit_y(self, X, Y, x1, x2):
len(X) != 0
# if X only include one point, the function will get line y=Y
if np.sum(X == X) == len(X):
return Y, Y
p = np.poly1d(np.polyfit(X, Y, 1))
return p(x1), p(x2)
```

### np.poly1d example #8

```def remove_linear_BG_XAS_preedge(
xmcd_data, scanparams, process_parameters=None, process_number=-1
):
"""Should remove a linear bg based on the preedge average"""
preedge_spectrum = get_preedge_spectrum(process_parameters, xmcd_data)

preedge_poly = np.poly1d(
np.polyfit(preedge_spectrum["Energy"], preedge_spectrum["XAS"], 1)
)

xas_bg = preedge_poly(xmcd_data["Energy"])

for xas in ["XAS+", "XAS-", "XAS"]:
xmcd_data[xas] -= xas_bg

return (xmcd_data, {"xas_bg_poly_coeffs": " ".join(map(str, preedge_poly.coeffs))})
```

### np.poly1d example #9

```def fit_y(self, X, Y, x1, x2):
len(X) != 0
# if X only include one point, the function will get line y=Y
if np.sum(X == X) == len(X):
return Y, Y
p = np.poly1d(np.polyfit(X, Y, 1))
return p(x1), p(x2)
```

### np.poly1d example #10

```def __init__(self, roots, weights=None, hn=1.0, kn=1.0, wfunc=None, limits=None, monic=0,eval_func=None):
np.poly1d.__init__(self, roots, r=1)
equiv_weights = [weights[k] / wfunc(roots[k]) for k in range(len(roots))]
self.__dict__[’weights’] = np.array(list(zip(roots,weights,equiv_weights)))
self.__dict__[’weight_func’] = wfunc
self.__dict__[’limits’] = limits
mu = sqrt(hn)
if monic:
evf = eval_func
if evf:
eval_func = lambda x: evf(x)/kn
mu = mu / abs(kn)
kn = 1.0
self.__dict__[’normcoef’] = mu
self.__dict__[’coeffs’] *= kn

# Note: eval_func will be discarded on arithmetic
self.__dict__[’_eval_func’] = eval_func
```

👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from numpy.poly1d () in Python, check other array Python module-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:

Jan Williams

Prague | 2023-03-25

Simply put and clear. Thank you for sharing. numpy.poly1d () in Python and other issues with array Python module was always my weak point 😁. I am just not quite sure it is the best method

Marie Krasiko

Milan | 2023-03-25

COM PHP module is always a bit confusing 😭 numpy.poly1d () in Python is not the only problem I encountered. I just hope that will not emerge anymore

Olivia Jackson

London | 2023-03-25

Maybe there are another answers? What numpy.poly1d () in Python exactly means?. I am just not quite sure it is the best method

## Shop Learn programming in R: courses

\$FREE Best Python online courses for 2022

\$FREE Best laptop for Fortnite

\$399+ Best laptop for Excel

\$ Best laptop for Solidworks

\$399+ Best laptop for Roblox

\$399+ Best computer for crypto mining

\$499+ Best laptop for Sims 4

\$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

PythonStackOverflow

Check if one list is a subset of another in Python

PythonStackOverflow

How to specify multiple return types using type-hints

PythonStackOverflow

Printing words vertically in Python

PythonStackOverflow

Python Extract words from a given string

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

PythonStackOverflow

Python os.path.join () method

PythonStackOverflow

Flake8: Ignore specific warning for entire file

## Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries