Reputation: 96
I am trying to write a function that can replicate the numpy function, np.polyval()
here is my current code:
def eval(poly, x):
result = 0
for i in poly:
y = (x ** (len(poly) - poly.index(i)-1))
result += y
return result
poly
is supposed be a list formatted for the numpy.poly1d function
but the problem with this code, is when x
is equal to a negative number
can someone help me with this code?
Upvotes: 0
Views: 545
Reputation: 117
Hey I found this snippet of code to work similar to np.polyval() function:
def poly(polynomial: list,value: int):
final = 0
for i in range(len(polynomial)):
final += (value**i)*polynomial[(-1*i)-1]
return final
Explanation using an example: poly([1,-5,5],-3)
range(len(polynomial))
returns 0,1,2 per iteration. those are also the powers we need for the quadratic equation. The (value**i)*polynomial[(-1*i)-1]
expression takes our value (in this case -3) and gives it the value of i (i.e (-3)^0,(-3)^1,(-3)^2). and then multiplies it with polynomial[(-1*i)-1]
th index of the list provided. (-1 when i=0;-2 when i=1 and -3 when i=2).
Finally it adds all of this together and returns a value.
Upvotes: 1
Reputation: 3380
Have you tried math.pow
function ?
import math
def func(poly, x):
result=0
i=1
for p in poly:
result += p*math.pow(x, len(poly)-i)
i+=1
return result
This is from numpy.polyval
page:
If p is of length N, this function returns the value:
p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]
Upvotes: 0