Search code examples
pythonsympypolynomials

How to create symbol polynomial from given array with sympy?


I am trying to calculate some polynomials given an input numerator and denominator polynomials as coefficient arrays.

How can I create my polynomials from these arrays?

E.g:

Inputs:

den= [2,3,4]
num= [1,3]

Output: (s+3)/(s^2+3*s+4)

I need to use symbols because I will further need to divide the results by other polynomials and perform further polynomial computations.

P.S Is sympy suitable for this? I would usually solve things like this in matlab but I want to expand my knowledge.


Solution

  • I think what you want is (s+3)/(2*s^2+3*s+4), there is a typo in your original expression. And in Python, ^ is not power, power is **.

    You just need a ordinary Python list comprehension:

    from sympy import poly
    from sympy.abc import s
    
    den_ = sum(co*s**i for i, co in enumerate(reversed(den)))
    num_ = sum(co*s**i for i, co in enumerate(reversed(num)))
    res = num_/den_