-1

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.

odd
  • 131
  • 1
  • 3
  • 9
  • 1
    Welcome to stack overflow. Unfortunately your question is too broad. Stack oveflow is no a code-writing service, it helps you solving specific problems. Read [ask] and refine your question. – Johan Oct 30 '17 at 09:33

3 Answers3

1

Instead of parsing the file as two separate lists, merge them into a single one. Then use polyval from numpy:

import numpy as np

p = [3,0,-4,5]
np.polyval(p,1)

Gives you 4 as a result.

Shaido
  • 27,497
  • 23
  • 70
  • 73
1

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.

xnx
  • 24,509
  • 11
  • 70
  • 109
0

This is without using numpy:-

function eval_poly(coef,degree,value_of_x):
    num = 0
    while num < len(coef)-1:
        answer = coef[num]*value_of_x^degree[num]
        num += 1
    answer += coef[-1]
    return answer
Abhijeetk431
  • 847
  • 1
  • 8
  • 18