-1

Evaluate a polynomial given a value for x. The input is a list of coefficients and value for x . The output is the polynomial sum evaluated at x.

3 Answers3

1

This is an option that does not use any exponentiation operator:

def pol_eval(a, x):
    result = 0
    # for every n in 0..len(a)-1
    for n, a_n in enumerate(a):
        # compute x^n
        x_power_n = 1
        for i in range(n):
            x_power_n *= x
        # add a_n * x^n to the final result
        result += a_n * x_power_n
    return result

Example:

a = [1,2,0,3] # coefficients
x = 1.5
print(pol_eval(a, x)) # 14.125
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
  • I started with this: "p = [int(x) for x in input().split()] x = int(input()) n = len(poly)" –  Apr 02 '20 at 14:11
  • @M_C Are you sure you want to do this `x = int(input())`? This is converting your text into an integer, so for example you can't input a value like 1.5 for x. You should do `x=float(input())`, and then call my function `pol_eval(p, x)`. Same thing for the coefficients: use `float`, not `int`! – Riccardo Bucco Apr 02 '20 at 14:15
  • I did, but it's not printing the answer –  Apr 02 '20 at 14:21
  • @M_C If you don't provide me more details I can't help you. Update your question please. – Riccardo Bucco Apr 02 '20 at 14:22
  • This is what I did** p = [float(x) for x in input().split()] x = float(input()) n = len(poly) def pol_eval(p, x): result = 0 for n, p_n in enumerate(p): x_power_n = 1 for i in range(n): x_power_n *= x result += p_n * x_power_n return result print (pol_eval(p, x)) –  Apr 02 '20 at 14:31
  • When I run it, after inputting the coefficients in p and the value of x, it just disappeared, not showing the answer –  Apr 02 '20 at 14:40
1

You can use recursion, think about how you can write out a polynomial. You can reference Horner's method on wikipedia.

def evaluate_poly(x, coefficients):
    if len(coefficients) == 1:
        return coefficients[0]
    return coefficients[0] + evaluate_poly(x, coefficients[1:])*x

a = [1, 2, 0, 3]
x = 1.5
print(evaluate_poly(x, a)) # 14.125
ec2604
  • 501
  • 3
  • 11
0

You can do it in a loop where you accumulate the products of coefficients with a progressively increasing power of x obtained by multiplying by x on each iteration:

a      = [1,2,0,3]
x      = 1.5

result = 0
xPower = 1
for coeff in a:
    result += coeff * xPower
    xPower *= x

print(result) # 14.125 = 1 + 2x + 0x^2 + 3x^3 = 1 + 3 + 0 + 10.125

Note that this can be further simplified by going backwards in the coefficients list and mutiplying the previous result by x before adding the coefficient:

result = 0
for coeff in reversed(a):
    result = coeff + result * x
Alain T.
  • 40,517
  • 4
  • 31
  • 51