Polynomy function with changing number of parameters

不羁的心 提交于 2019-12-11 01:59:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!