问 题
假设有一个点集[x0, x1, x2, ..., xn],对应的函数值为[y0, y1, y2, ..., yn],怎样求差商(1至n阶)。
k阶差商计算公式
f(x0, x1, ..., xk) = (f(x1, x2, ..., xk) - f(x0, x1, ... x(k-1))) / (xk - x0)
举个例子,一阶差商:
f(x0, x1) = (f(x1) - f(x0)) / (x1 - x0)
f(x1, x2) = (f(x2) - f(x1)) / (x2 - x1)
二阶差商:
f(x0, x1, x2) = (f(x1, x2) - f(x0, x1)) / (x2 - x1)
解决方案
大概是這樣:
fmap = {1:1, 2:2, 3:3}
def f(*x):
if len(x)==1:
rc = fmap[x[0]]
print('f({})={}'.format(x[0], rc))
return rc
rc = (f(*x[1:])-f(*x[:-1]))/(x[-1]-x[0])
template = 'f({})=(f({})-f({}))/({}-{})={}'
print(template.format(', '.join([str(i) for i in x]),
', '.join([str(i) for i in x[1:]]),
', '.join([str(i) for i in x[:-1]]),
x[-1], x[0],
rc))
return rc
f(1, 2, 3)
結果:
f(3)=3
f(2)=2
f(2, 3)=(f(3)-f(2))/(3-2)=1.0
f(2)=2
f(1)=1
f(1, 2)=(f(2)-f(1))/(2-1)=1.0
f(1, 2, 3)=(f(2, 3)-f(1, 2))/(3-1)=0.0
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注与百万开发者在一起