Search code examples
pythonsympytaylor-series

Getting n'th order coefficient from series expansion in Sympy


I have a polynomial defined using numpy's poly1d:

import numpy as np

p = np.poly1d([-1.37970733e+07,  8.02055768e+07, -1.98442743e+08,  2.70981281e+08,
       -2.20611918e+08,  1.07019785e+08, -2.85873914e+07,  3.24251782e+06])

I then do a series expansion of this polynomial about a point I call radMax = 0.80868373. Here is how I do the series expansion:

from sympy import series, Symbol, Poly
x = Symbol('x')
polyExpand = p(x).series(x,radMax,3)/(p(radMax)/0.0523772)

This gives me the expansion I want, and I want the coefficient of the 2nd order term. If you run the above code, you will see that this coefficient is "0.2843162879664". I would like to extract this coefficient.


Solution

  • If you would like to address the coefficients by terms:

    from sympy import sympify
    print(polyExpand.as_coefficients_dict()[sympify(f"(x - {radMax}) ** 2")])
    

    If you would like to get the coefficients by indices:

    coeffs = list(polyExpand.as_coefficients_dict().values())
    print(coeffs[2]) # order n = 2
    

    These will correctly output -0.284316287966400. You forgot about the minus.