I'm trying to use sympy to automatize a solution of a polynomial fitting problem. For example, say that I define a polynomial function:
#!/usr/bin/python
from sympy import *
x, xa, xb, a0, a1, a2, a3 , a4 = symbols(('x', 'xa', 'xb', 'a0', 'a1', 'a2', 'a3', 'a4'))
def p4(x):
return a0 + a1 * x + a2 * x**2 + a3 * x**3 + a4 * x**4;
Such that p4(x) : [xa, xb] -> R. I can then compute its symbolic derivative like this:
y = p4(x)
ydiff = diff(y, x)
and then impose some conditions on the derivative and the function, to compute the polynomial coefficients symbolically, like this:
c0 = y.subs(x, xa)
c1 = y.subs(x, xb)
c2 = ydiff.subs(x, xa)
c3 = ydiff.subs(x, xb)
c4 = ydiff.subs(x, (xa + xb) * 0.5)
These are not in fact conditions, they are substitutions, a full condition would be c0 = 0.5
, saying that the function p4 at xa has a value of 0.5. In any case, the final system of 4 equations will be linear for a0
, a1
, a2
, a3
and a4
.
My question is, how to assemble the matrix A:
A = Matrix([c0[1], c0[2], c0[3], c0[4], 0.5], [....
to solve the system with sympy.solve_linear_system
?
For example, the computed c0
looks like this:
In [2]: c0
Out[2]: a0 + a1*xa + a2*xa**2 + a3*xa**3 + a4*xa**4
and the Matrix expects for c0 = 0.5
equation, a list like this one
[a0, a1*xa, a2*xa**2, a2*xa**3, a4*xa**4, 0.5]
is there a function in sympy that can convert a polynomial to a list of both the coefficients and the arguments?
Edit: I have found out how to get the polynomials represented as lists
c0ArgList = list(c0.args)
c3ArgList = list(c3.args)
but they are unsorted with respect to xa^n:
c0ArgList
Out[92]: [a1*xa, a2*xa**2, a4*xa**4, a0, a3*xa**3]
In [93]: c3ArgList
Out[93]: [a1*xa, a2*xa**2, a4*xa**4, a0, a3*xa**3]
which makes it impossible to apply the conditions. How can I sort them with respect to n in 'xa^n'?
To get all the coefficients use the all_coeffs method:
>>> Poly(1+x**2*2+5*x**4).all_coeffs()
[5, 0, 2, 0, 1]
And you don't need to call solve_linear_system yourself. You can just pass the set of equations that need to be solved to solve in a list (and optionally tell what subset of symbols you want to solve for) and it will return the answer.
>>> solve([Eq(x+y,2), Eq(x**2, 4)])
[{x: -2, y: 4}, {x: 2, y: 0}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With