Polynomy功能随着参数的变化而变化 [英] Polynomy function with changing number of parameters
本文介绍了Polynomy功能随着参数的变化而变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以(在Python中)定义具有变化的参数量的函数的多项式类型?参数数量应根据我输入文件中的数据系列数量而改变。
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.
目前我有这样的东西:
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.
推荐答案
使用生成器表达式的一个更简单的版本
an even simpler version using a generator expression
def y(x, *args):
return sum(a * x ** i for i, a in enumerate(args))
和使用减少的Horner版本
and a Horner version using reduce
def horn(x, *args):
return reduce(lambda y, a: y * x + a, reversed(args))
这篇关于Polynomy功能随着参数的变化而变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文