Search code examples
pythonnumpyscipypolynomials

How to get a polynomial providing the exponential numbers for each term of the function?


I'm trying to write a polynomial. However, I have found scipy methods which give the polynomial format like x^4 + 2x^3 - x^2 + 3, from which the coefficients are [3, 0, -1, 2, 1], and the exponential by 4, 3, and 2.

Is there a way to manipulate the exponential through a given list of number? Something like, giving:

nj = [0.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0, 7.0, 8.0]

For example, I could calculate terms of a polynomial like coef*x^nj = 0 for a given unique coef.

Thank you!


Solution

  • If you have a NumPy array of coefficients coef, and a NumPy array of exponents nj, the value of the polynomial at x can be computed as

    coef.dot(x**nj)
    

    Example:

    coef = np.array([3.1, 0, -2, 5, 1.1])
    nj = np.array([0, 1, 2, 2, 5])   
    x = 1.23
    print(coef.dot(x**nj))   # 10.7355362527