如何用python求差商?
问题描述
假设有一个点集[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)
问题解答
回答1:大概是這樣:
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)=3f(2)=2f(2, 3)=(f(3)-f(2))/(3-2)=1.0f(2)=2f(1)=1f(1, 2)=(f(2)-f(1))/(2-1)=1.0f(1, 2, 3)=(f(2, 3)-f(1, 2))/(3-1)=0.0
我回答過的問題: Python-QA
相关文章: