牛顿';python中的s方法检查

牛顿';python中的s方法检查,python,while-loop,newtons-method,Python,While Loop,Newtons Method,这是我的牛顿法代码,使用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 lo

这是我的牛顿法代码,使用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


谢谢

您可以通过查看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
def which_root_z4(z,n):#接受2个参数的函数;z和n
fz=z**4-1#定义f(z)
dfz=4*z**3#定义f(z)的一阶导数
当n>0时:#此块将继续循环,直到n=0
z=z-fz/dfz#T牛顿-拉斐逊公式
如果abs(fz/dfz)