问题
is it possible (in Python) to define a polynomial type of function that has changing amount of parameters? Number of parameters should change according to number of data series that I have in my input file.
Currently I have something like this:
def y(x, a0, x2, x3, x4):
y = a0 + a1*x + a2*x**2 + a3*x**3
return y
I could of course set parameters of higher order to zero by extra parameter but would there be some better way.
回答1:
You can loop over the arguments and evaluate the polynomial using Horners method, which is very efficient.
def y(x, *args):
y = 0
for a in reversed(args):
y = y*x+a
return y
You can find a heap more details about variable numbers of arguments in this question.
回答2:
an even simpler version using a generator expression
def y(x, *args):
return sum(a * x ** i for i, a in enumerate(args))
and a Horner version using reduce
def horn(x, *args):
return reduce(lambda y, a: y * x + a, reversed(args))
回答3:
def y(x, *args):
y = 0
i = 0
for a in args:
y += a * x ** i
i += 1
return y
print y(2, 1, 2) # 2 * 2 ^ 0 + 2 * 2 ^ 1 = 5
回答4:
In this particular case it would be much cleaner to provide polynomial as a single argument, namely a list of coefficients:
def eval_poly(x, poly):
....
eval_poly(10, [1, 2, 3]) # evaluate (1 + 2x + 3x^2)(10)
This way you can handle polynomials like ordinary values, for example:
def add_poly(p1, p2):
"""Add two polynomials together"""
...
p1 = [1,2,3]
p2 = [4,5,6]
print eval_poly(10, add_poly(p1, p2))
回答5:
If you're working with data files and evaluating polynomials, you could probably benefit from using numpy, which also includes numpy.polyval for evaluating polynomials.
来源:https://stackoverflow.com/questions/12050007/polynomy-function-with-changing-number-of-parameters