bryan tetris
bryan tetris

Reputation: 133

Calculate a polynomial

I want to calculate a polynomial on x value. I tried to write a function that takes as argument an array of integer and integer x the function will returns the value of the polynomial in x.

def pol(L, x):
    P = None
    for i in L:
        P = L[0] * (x ** 0) + L[1] * (x ** 1) + L[2] * (x ** 2)
    return P

L = [0, 2, 4]
x = 3
print(pol(L, x))

I also tried

def pol(L, x):
    P = None
    for i in L:
        j = 0
        P = sum(i * (x ** j))
        j += 0
    return P

L = [0, 2, 4]
x = 3
print(pol(L, x))

It will return 42 for this example. I don't know how to increment. Thanks

Upvotes: 1

Views: 528

Answers (1)

Daniel Lenz
Daniel Lenz

Reputation: 3857

Building up on your attempts, one straightforward way to get the polynomial would be the following:

def poly(p, x):
    val = 0
    for i, pp in enumerate(p):
        val += pp * x**i

    return val

There are faster and more elegant ways to do this, though. I'd strongly encourage you to use numpy.polyval() for efficiency.

Note that for the numpy implementation, p[0] is the highest order polynomial while for the example shown here, p[0] is the lowest order!

p = [0, 2, 4]
x = 3

poly(p, x)
>> 42

import numpy as np
poly(p, x) == np.polyval(p[::-1], x)
>> True

Upvotes: 2

Related Questions