Search code examples
pythonnumpypolynomials

Evaluate polynomials by reading it from a file


I would like to read and evaluate a polynomial from a txt file that is given in the following format,

3x^3-4x^1+5

  • So the above equation should be evaulated by the program as follows,

Coefficients: [3,0,-4,5]

So far I could able to parse the string and created two different lists that store coefficients and the degrees as follows,

Coefficients: [3,-4,5] --> They are the coeffs of x^3, x^1, and x^0

Degrees: [3,1]

However I could not evaluate (i.e. P(1) = 3(1^3)-4(1^1)+5 = 4) the polynomial with these extracted values. I would like to use numpy, yet the formats do not match.

Can anyone help me how can I obtain the required format for utilizing numpy?

Thanks.


Solution

  • Assuming you can put the constant term (coefficient of x^0) in your deg list, then you can do this:

    coeffs = [3,-4,5]
    degs = [3,1,0]
    _coeffs = [0]*(max(degs)+1)
    for i,deg in enumerate(degs):
        _coeffs[deg] = coeffs[i]
    
    p = np.poly1d(_coeffs[::-1])
    

    Then:

    p(1)
    4
    

    That is, you just need to create a list of coefficients in which the coefficient appears at the index of the degree.