Reputation: 169
How can I replace x
in a polynomial by some other polynomial in Python? For example, I had p = poly1d([1,1,1])
, which is x^2+x+1
, now I want to replace x
by y^2
and get y^4+y^2+1
. It's like the composition of two functions.
Upvotes: 1
Views: 1940
Reputation: 25548
You can substitute polynomials into other polynomials in NumPy:
In [2]: p = np.poly1d([1,1,1]) # x^2 + x + 1
In [3]: y2 = np.poly1d([1,0,0]) # x^2
In [4]: p(y2)
Out[4]: poly1d([ 1., 0., 1., 0., 1.]) # x^4 + x^2 + 1
Upvotes: 4
Reputation: 39621
You can use numpy.polyval to compose polynomials using NumPy. For example:
import numpy as np
p1 = np.poly1d([1, 1, 1])
print (p1)
p2 = np.poly1d([1, 0, 0], variable = 'y')
print (p2)
p = np.polyval(p1, p2)
p = np.poly1d(p, variable = 'y')
print (p)
will print:
2
1 x + 1 x + 1
2
1 y
4 2
1 y + 1 y + 1
Upvotes: 3