python中的牛顿作图法
在下面的代码中,我用Python实现了Newton方法python中的牛顿作图法,python,newtons-method,Python,Newtons Method,在下面的代码中,我用Python实现了Newton方法 import math def Newton(f, dfdx, x, eps): f_value = f(x) iteration_counter = 0 while abs(f_value) > eps and iteration_counter < 100: try: x = x - float(f_value)/dfdx(x) except Z
import math
def Newton(f, dfdx, x, eps):
f_value = f(x)
iteration_counter = 0
while abs(f_value) > eps and iteration_counter < 100:
try:
x = x - float(f_value)/dfdx(x)
except ZeroDivisionError:
print ("Error! - derivative zero for x = ", x)
sys.exit(1) # Abort with error
f_value = f(x)
iteration_counter += 1
# Here, either a solution is found, or too many iterations
if abs(f_value) > eps:
iteration_counter = -1
return x, iteration_counter
def f(x):
return (math.cos(x)-math.sin(x))
def dfdx(x):
return (-math.sin(x)-math.cos(x))
solution, no_iterations = Newton(f, dfdx, x=1, eps=1.0e-14)
if no_iterations > 0: # Solution found
print ("Number of function calls: %d" % (1 + 2*no_iterations))
print ("A solution is: %f" % (solution))
else:
print ("Solution not found!")
但是,我得到以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-9378f4e2dbe3> in <module>()
1 import numpy as np
----> 2 np.array(list(Newton(f,dfdx, 1,10e-4)))
<ipython-input-19-40b67c2c3121> in Newton(f, dfdx, x, eps)
4 f_value = f(x)
5 iteration_counter = 0
----> 6 while abs(f_value) > eps and iteration_counter < 100:
7 try:
8 x = x - float(f_value)/dfdx(x)
TypeError: bad operand type for abs(): 'NoneType'
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
1作为np导入numpy
---->2 np.数组(列表(牛顿(f,dfdx,1,10e-4)))
单位为牛顿(f,dfdx,x,eps)
4 f_值=f(x)
5个计数器=0
---->6当abs(f_值)>eps和迭代_计数器<100时:
7尝试:
8 x=x-浮点(f_值)/dfdx(x)
TypeError:abs()的操作数类型错误:'NoneType'
我建议将每次迭代的每个值x和相应的输出f存储在两个各自的数组中,然后返回每个数组。如果您的函数是正确的(您应该知道它是否收敛),那么这应该很容易做到。从这里开始,绘制阵列
我是几个月前做的。你可以在这里看到我是如何处理的:
这里有几件事需要注意
1) 我没有检查你的函数是否正确收敛
2) 牛顿方法通常有一个非常大的步长,你通常不会因为它的收敛性得到任何很好的可视化效果。eps和迭代计数器<100的情况并不少见:
尝试:
x=x-浮点(f_值)/dfdx(x)
除零误差外:
打印(“错误!-x=,x的导数为零)
系统退出(1)#带错误中止
f_值=f(x)
xstore.append(x)
fstore.append(f_值)
迭代计数器+=1
#在这里,要么找到了解决方案,要么迭代太多
如果abs(f_值)>eps:
迭代_计数器=-1
返回x,迭代计数器,xstore,fstore
def f(x):
返回(math.cos(x)-math.sin(x))
def dfdx(x):
返回(-math.sin(x)-math.cos(x))
解,无迭代,xvalue,fvalue=Newton(f,dfdx,x=1,eps=1.0e-14)
如果没有迭代次数>0:#找到解决方案
打印(“函数调用数:%d”%(1+2*无迭代))
打印(“解决方案为:%f”%(解决方案))
其他:
打印(“未找到解决方案!”)
x=np.array([i代表xvalues中的i])
f=np.数组(fvalues)
图=plt.图()
plt.散射(x,f,label='Newton')
plt.legend()
您忘记返回函数中的任何内容…感谢您指出这一点out@usr2564301一旦这是固定的,我应该得到正确的输出?我的数组输出给了我一个2x2,它将修复你得到的错误。我不知道你的算法是否正确。好的,谢谢你的帮助!你能告诉我这是如何用我的代码完成的吗?我可以接受答案,谢谢你的编辑。这是显示绝对误差作为迭代次数函数的收敛图吗?现在我的代码只需要7次迭代就可以找到我的解决方案我相信这只是给出了答案,而不是绝对误差作为迭代次数的函数否,这只是绘制牛顿方法迭代的值(例如,x_1,x_2,x_3,等等,w/给定x对应的目标函数输出),您的代码只迭代3次。我不知道为什么您将函数调用的数量定义为
1+2*无迭代
。当你说“绝对误差是迭代次数的函数”时,我并没有理解你的意思。不管怎样,你应该了解如何能够可视化你试图输出的任何东西的输出的要点。那么,我如何确定迭代次数呢?
import numpy as np
np.array(list(Newton(f,dfdx, 1,10e-4)))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-9378f4e2dbe3> in <module>()
1 import numpy as np
----> 2 np.array(list(Newton(f,dfdx, 1,10e-4)))
<ipython-input-19-40b67c2c3121> in Newton(f, dfdx, x, eps)
4 f_value = f(x)
5 iteration_counter = 0
----> 6 while abs(f_value) > eps and iteration_counter < 100:
7 try:
8 x = x - float(f_value)/dfdx(x)
TypeError: bad operand type for abs(): 'NoneType'
import numpy as np
import math
import matplotlib.pyplot as plt
def Newton(f, dfdx, x, eps):
xstore=[]
fstore=[]
f_value = f(x)
iteration_counter = 0
while abs(f_value) > eps and iteration_counter < 100:
try:
x = x - float(f_value)/dfdx(x)
except ZeroDivisionError:
print ("Error! - derivative zero for x = ", x)
sys.exit(1) # Abort with error
f_value = f(x)
xstore.append(x)
fstore.append(f_value)
iteration_counter += 1
# Here, either a solution is found, or too many iterations
if abs(f_value) > eps:
iteration_counter = -1
return x, iteration_counter,xstore,fstore
def f(x):
return (math.cos(x)-math.sin(x))
def dfdx(x):
return (-math.sin(x)-math.cos(x))
solution, no_iterations,xvalues,fvalues = Newton(f, dfdx, x=1, eps=1.0e-14)
if no_iterations > 0: # Solution found
print ("Number of function calls: %d" % (1 + 2*no_iterations))
print ("A solution is: %f" % (solution))
else:
print ("Solution not found!")
x = np.array([i for i in xvalues])
f = np.array(fvalues)
fig = plt.figure()
plt.scatter(x,f,label='Newton')
plt.legend()