这是我使用while循环的牛顿方法的代码,z是一个复杂的参数:
def which_root_z4(z , n): # function which takes 2 arguments; z and n
fz = z ** 4 - 1 # defining f(z)
dfz = 4 * z ** 3 # defining the first derivative of f(z)
while n > 0: # this block will continue looping until n = 0
z = z - fz / dfz #T he Newton-Raphson formula
return which_root_z4(z, n-1) # after each iteration, the function begins again with the new value of z and n-1
return z
我需要对其进行修改,以便可以通过测试与根之一的距离是否小于0.25来检查函数是否将收敛。
我不知道该怎么做
方程的根是1,-1,i,i
谢谢
答案 0 :(得分:1)
您可以通过查看z的当前值与其先前值之间的差异来检查收敛性。这种差异只是您在每次迭代中添加的值,即fz / dfz。
我猜您需要在差值小于0.25时停止循环,然后代码如下:
def which_root_z4(z , n): # function which takes 2 arguments; z and n
fz = z ** 4 - 1 # defining f(z)
dfz = 4 * z ** 3 # defining the first derivative of f(z)
while n > 0: # this block will continue looping until n = 0
z = z - fz / dfz #T he Newton-Raphson formula
if abs(fz / dfz)<0.25: #This ends the loop when z's converged
break
return which_root_z4(z, n-1) # after each iteration, the function begins again with the new value of z and n-1
return z
您还可以打印fz / dfz的值以检查其是否确实达到收敛