在以下代码中,我已经在Python中实现了Newtons方法。
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!")
但是,现在我希望在同一时间间隔上绘制收敛图。这将是绝对误差与迭代次数的函数。
我试图使每次迭代产生一个带有绝对误差和迭代的2元组。这是下面的代码,其中也包含我从中得到的错误,
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)
yield interation_counter, abs(f(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
def f(x):
(math.cos(x)-math.sin(x))
def dfdx(x):
(-math.sin(x)-math.cos(x))
为此,我尝试将结果放入数组中,以便可以绘制结果图
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'
答案 0 :(得分:3)
我建议将每个迭代的每个值x和对应的输出f存储在两个各自的数组中,然后返回每个数组。如果您的函数是正确的(您应该知道它是否收敛),那么这应该很容易做到。从那里,只需绘制阵列。
几个月前,我做到了。您可以在这里查看我的工作方式: How to tell if Newtons-Method Fails
因此,这里需要注意几件事。
1)我没有检查以确保您的函数正确收敛。
2)牛顿法通常具有非常大的步长,并且您通常无法获得其收敛的漂亮可视化效果。迭代次数少于10次的情况并不少见,而且它们通常也不遵循通向收敛点的平滑路径(再次,步长较大)。注意,对于我实现的代码,只有3次迭代。但这可能只是因为您的功能有误。坦白说,我不确定
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()