我正在使用python进行根查找迭代。
我首先定义了F(x)。
def F(x):
return 0.01-0.4*x+x**2/(1+x**2)
我也定义了dFdx。
def dFdx(x):
return -0.4+2*x/((1+x**2)**2)
以下是我的寻根代码
def Testing_Root(x, F, dFdx):
# store the values of x_n in a list, xstore
# first, make an initial list with an initial guess x_0
xstore = [x]
# calculate differences in each iteration and store in a list, difference
# first, make an empty list
difference = []
print('n=0, x[0] =', x)
for i in range(50):
x = x - F(x)/dFdx(x)
xstore.append(x)
for j in range(50):
d = xstore[j+1] - xstore[j]
difference.append(d)
for k in range(50):
print('n=', k+1, 'x[', k+1, ']=', xstore[k+1], 'difference is', difference[k])
for j in range(k, 50):
if all(abs(difference[j]) < 0.000000000001):
break
break
return print('so the root is', round(x, 4), 'to 4dp')
当我将此根查找函数用于x = -0.1时
In [38]: Testing_Root(-0.1, F, dFdx)
n=0, x[0] = -0.1
n= 1 x[ 1 ]= 0.0004950332214986031 difference is 0.10049503322149861
so the root is 0.0268 to 4dp
在我的函数中,我想检查它是否收敛到根。另外,我不想打印所有迭代。如果所有k> =点的差值都小于0.000000000001,我希望它在某个点停止打印迭代。所以我在for循环中使用了if循环(“ for k在range(50)中:if all(abs(difference [j])<0.0000001):break'部分))。但是,它没有按我预期的那样工作。它在n = 1之后停止打印,但是当n = 2时的差异为0.02306141 ...,显然大于0.000000000001。为什么不起作用?我应该更改我的代码吗?
答案 0 :(得分:0)
三个简单的问题要解决:
all
设计为可用于 iterable (认为:“在列表中”)。通过将for
循环置于all
调用之外,您正在欺骗all
,使其失去力量。而是将整个感兴趣的列表传递到all
,并且完全不要循环。abs
和<
不能迭代!取而代之的是,使用Python强大的 list comprehension 来生成具有逐元素操作的列表。语法difference[k:]
表示从索引difference
到末尾k
的所有元素。break
循环中有一个流浪k
,每次循环都会在第一次迭代后中断循环。因此,您的k
循环应如下所示:
for k in range(50):
print('n=', k+1, 'x[', k+1, ']=', xstore[k+1], 'difference is', difference[k])
if all([abs(n)<0.000000000001 for n in difference[k:]]):
break
输出为:
n=0, x[0] = -0.1
n= 1 x[ 1 ]= 0.0004950332214986031 difference is 0.10049503322149861
n= 2 x[ 2 ]= 0.025061418498996398 difference is 0.024566385277497795
n= 3 x[ 3 ]= 0.0267848938218123 difference is 0.001723475322815901
n= 4 x[ 4 ]= 0.02679343238175541 difference is 8.538559943111618e-06
n= 5 x[ 5 ]= 0.026793432591266996 difference is 2.0951158516413493e-10
n= 6 x[ 6 ]= 0.026793432591266996 difference is 0.0
so the root is 0.0268 to 4dp