在以下代码中,我已经在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!")
但是,现在我希望在同一时间间隔上绘制收敛图。这将是绝对误差,它是间隔[0,1]上迭代次数的函数。表示在x轴上的迭代次数,在y轴上具有相应的绝对误差
我试图使每次迭代产生一个带有绝对误差和迭代的2元组。这是我下面的代码,以及输出和图形。我的输出正确吗?该图应该看起来像这样吗?非常感谢所有帮助!我的代码中的迭代次数为3
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 iteration_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
return x, iteration_counter
def f(x):
return (math.cos(x)-math.sin(x))
def dfdx(x):
return (-math.sin(x)-math.cos(x))
import numpy as np
np.array(list(Newton(f,dfdx, 1,10e-4)))
产生以下输出:
array([[0.00000000e+00, 4.74646213e-03],
[1.00000000e+00, 1.78222779e-08]])
最后:
import numpy as np
import matplotlib.pyplot as plt
data = np.array(list(Newton(f,dfdx, 1, 10e-14)))
plt.plot(data[:,0], data[:,1])
plt.yscale('log')
plt.show()
产生图形:
答案 0 :(得分:1)
Newton
函数不应同时屈服并返回这就是我要做的:
import math
import sys
import numpy as np
import matplotlib.pyplot as plt
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 iteration_counter, x, 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
def f(x):
return x ** 2 - 1.34
def dfdx(x):
return 2 * x
data = np.array(list(newton(f, dfdx, 10, 10e-14)))
# plt.plot(data[:, 0], data[:, 1]) # x-axis: iteration, y-axis: x values
plt.plot(data[:, 0], data[:, 2]) # x-axis: iteration, y-axis: f(x) values
plt.yscale('log')
plt.show()