How do I convert a simplex polynomial to a list?

I'm trying to use sympy to automate my polynomial fit problem. For example, let's say that I am defining 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; 

      

So p4 (x): [xa, xb] → R. Then I can 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 symbolically compute the polynomial coefficients 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 real conditions, they are substitutions, the full condition will be c0 = 0.5

saying that the function p4 at the point xa has a value of 0.5. In any case, the final system of equations 4 to be linear a0

, a1

, a2

, a3

and a4

.

My question is how to assemble matrix A:

A = Matrix([c0[1], c0[2], c0[3], c0[4], 0.5], [.... 

      

to solve the system using sympy.solve_linear_system

?

For example, the calculated one c0

looks like this:

In [2]: c0 
Out[2]: a0 + a1*xa + a2*xa**2 + a3*xa**3 + a4*xa**4

      

and Matrix expects for an equation c0 = 0.5

, a list like this

[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 coefficients and arguments?

Edit : I found out how to get polynomials represented as lists

c0ArgList = list(c0.args)
c3ArgList = list(c3.args)

      

but they are unsorted relative 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]

      

making it impossible to apply conditions. How can I sort them in relation to n in 'xa ^ n'?

+3


source to share


1 answer


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 resol_linear_system yourself. You can simply pass in a set of equations to be solved for the solution in the list (and possibly specify which subset of characters you want to solve) and it will return the answer.

>>> solve([Eq(x+y,2), Eq(x**2, 4)])
[{x: -2, y: 4}, {x: 2, y: 0}]

      

+7


source







All Articles