0

I am trying to write a basic algorithm to evaluate a fourth order polynomial using Python. The code is below, and I am not sure what I am doing wrong. I came up with this code and I am not sure if it is enough to do the trick:

x = int(raw_input(":"))
def eval_poly(x):
    if abs(x) > 0:
        return 35x**4-17x**3+5x**2+41x-29
print eval_poly(x) 

The error that I get says that 35x**4 is an invalid syntax and the polynomial that I am trying to evaluate is as follows:

35x^4 - 17x^3 + 5x^2 + 41x -29 
alexwlchan
  • 5,699
  • 7
  • 38
  • 49
sanster9292
  • 1,146
  • 2
  • 9
  • 25
  • 1
    Why do you need the `if abs(x) > 0` line? The function returns `None` if you feed in x=0, but it’s valid to evaluate the polynomial at 0. – alexwlchan Jan 28 '15 at 07:08

4 Answers4

2

Although we write (35 x) in mathematics to implicitly mean (35 * x), the Python interpreter can’t work this out. You need to tell it 35 * (x ** 4) explicitly.

So you modify the function to include

return 35 * (x ** 4) - 17 * (x ** 3) + 5 * (x ** 2) + 41 * x - 29

(The parentheses aren’t strictly necessary, because Python will get the right order of operations without them, but I think they aid readability.)


It’s worth saying: the error gets thrown when Python tries to evaluate the expression 35x, but it doesn’t know how to interpret this. It starts with a digit, hence not a variable (variables have to start with a non-digit character), but contains an alphabet character, hence not a number. It’s not just that it doesn’t know what this expression means, it’s that 35x is impossible for Python to parse.

Community
  • 1
  • 1
alexwlchan
  • 5,699
  • 7
  • 38
  • 49
1
35*(x**4) - 17*(x**3) + 5*(x**2) + 41*x - 29
0

You left the multiplication:

35*x**4-17*x**3+5*x**2+41*x-29
PeterMmm
  • 24,152
  • 13
  • 73
  • 111
0

You need to explicitly perform multiplication as below. ie. 7x becomes 7*x.

Otherwise it looks good...

x = int(raw_input(":"))
def eval_poly(x):
    if abs(x) > 0:
        return 35*x**4-17*x**3+5*x**2+41*x-29
print eval_poly(x) 
Andrew Guy
  • 9,310
  • 3
  • 28
  • 40