具有参数数量变化的多项式功能

时间:2012-08-21 07:19:04

标签: python function dynamic parameters

是否可以(在Python中)定义具有参数变化量的多项式函数?参数数量应根据我输入文件中的数据系列数量而变化。

目前我有这样的事情:

def y(x, a0, x2, x3, x4):
    y = a0 + a1*x + a2*x**2 + a3*x**3
    return y

我当然可以通过额外的参数将更高阶的参数设置为零,但是会有更好的方法。

5 个答案:

答案 0 :(得分:3)

您可以使用Horners method遍历参数并评估多项式,这非常有效。

def y(x, *args):
  y = 0
  for a in reversed(args):
    y = y*x+a
  return y

您可以在此question中找到有关变量数量参数的更多详细信息。

答案 1 :(得分:3)

使用生成器表达式的更简单的版本

def y(x, *args):
  return sum(a * x ** i for i, a in enumerate(args))

和使用reduce的Horner版本

def horn(x, *args):
    return reduce(lambda y, a: y * x + a, reversed(args))

答案 2 :(得分:1)

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

答案 3 :(得分:0)

在这种特殊情况下,将多项式作为单个参数提供更清晰,即系数列表:

 def eval_poly(x, poly):
     ....

 eval_poly(10, [1, 2, 3]) # evaluate (1 + 2x + 3x^2)(10)

通过这种方式,您可以像普通值一样处理多项式,例如:

 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))

答案 4 :(得分:0)

如果您正在使用数据文件并评估多项式,那么您可能会因使用numpy而受益,{{1}}还包括用于评估多项式的​​numpy.polyval