我在 python 中编写了一个递归函数来评估 interpolation method 的序列.
在这张图片中以图形方式解释:
f[x]=f(x)
和 f[x0,x1]= f[x1]-f[x0])/(x1 - x0)
所以当 f[x0,x1,...xn]=f[all_leastFirst,allbutLast]/xlast-xfirst
时。
就是这样,递归地。
我得到了以下代码:
xxs=[]
yys=[]
coeficientes = []
h = {}
r = 0.0
def a_j(xx,yy):
global r
if len(yy) == 1:
h[xx[0]] = yy[0]
return yy[0]
else:
r = (a_j(xx[1:],yy[1:]) - a_j(xx[:-1],yy[:-1])) / (xx-1]-xx[0])
h[''.join(str(i) for i in xx[::-1])]=r
coeficientes.append(r)
return ( r )
但需要获取一个数组作为输出,其中只有绿色圆圈中标记的数字。我迷失了如何在递归实现中只获得那些。
关于它们的一种常见模式是它们总是从 X_0
开始,因此我选择标记它们或使用字典可能会有所帮助。
预期结果为:
[1,1.71828,1.47625,.84553]
我正在获得:
[1, 2.71828, 7.3890599999999997, 20.085540000000002, 1.71828, 4.6707799999999997, 12.696480000000001, 1.4762499999999998, 4.0128500000000003, 0.84553333333333347]
对于另一个运行机智不同的参数,如果它被调用:
a_j([1,2,3,5][4,3.5,4,5.6])
应该输出:
[4,-0.5,0.5,-0.1]
我正在获得:
[4, 3.5, 4, 5.6, -0.5, 0.5, 0.5, 0.7999999999999998, 0.09999999999999994, -0.10000000000000002]
另一个例子:
a_j([-2,-1,0,1,2], [13,24,39,65,106])
将输出:
[13, 24, 39, 65, 106, 11, 15, 2, 26, 5, 1, 41, 7, 0, -1]
但输出应该是:
[13,11,2,1.167,-0.125]
我还设法编写了这个迭代实现,它已经正确:
diferencias = {}
coeficientes = []
def sublists_n(l, n):
subs = []
for i in range(len(l)-n+1):
subs.extend([l[i:i+n]])
return subs
def sublists(l):
subs = []
for i in range(len(l)-1,0,-1):
subs.extend(sublists_n(l,i))
subs.insert(0,l)
return subs[::-1]
def diferenciasDivididas(xx,yy,x):
combinaciones = sublists([i for i in range(len(xx))])
for c in combinaciones:
if len(c) == 1:
diferencias[str(c[0])]= float(yy[c[0]])
if c[0] == 0:
coeficientes.append(float(yy[c[0]]))
else:
c1 = diferencias.get(''.join(str(i) for i in c[1:]))
c2 = diferencias.get(''.join(str(i) for i in c[:-1]))
d = float(( c1 - c2 ) / ( xx[c[len(c)-1]] - xx[c[0]] ))
diferencias[''.join(str(i) for i in c)] = d
if c[0] == 0:
coeficientes.append(float(d))
我只想知道我错过了什么?
最佳答案
我对脚本做了一些修改。
array=[]
r='s'
s=0
def a_j(xx,yy):
global r,s
if r == 's':
s=xx[0]
r=0.0
if len(yy) == 1:
if xx[0]==s: array.append(yy[0])
return float(yy[0])
else:
r=( a_j(xx[1:],yy[1:]) - a_j(xx[:-1],yy[:-1])) / (xx[-1]-xx[0])
if xx[0]==s: array.append(r)
return float(r)
a_j([1,2,3,5],[4,3.5,4,5.6])
print array
输出: [4, -0.5, 0.5, -0.10000000000000002]
另外,您给出的第二个示例看起来不正确。 a_j([-2,-1,0,1,2], [13,24,39,65,106]) --> [13,11,4,7,-3]
上面的答案说第 3 个元素是 4。
3rd element means --> x(-2,-1,0) -> x(-1,0) - x(-2,-1)/(2)
-> x(0)-x(-1)/1 - x(-1)-x(-2)/(1) /(2)
->(39-24) - (24-13) /(2)
->15-11/(2)
->4/2 =2
如有错误请指正。
关于python - 修正牛顿差分插值法的递归python实现,在递归中获取部分返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22341426/