牛顿法检查 python
Newton's method check in python
所以这是我使用 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
你也可以打印fz/dfz的值来检查它是否确实达到了收敛
所以这是我使用 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
你也可以打印fz/dfz的值来检查它是否确实达到了收敛