【发布时间】:2018-11-05 06:34:17
【问题描述】:
在以下代码中,我在 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'
【问题讨论】:
-
你忘记了 return 函数中的任何内容...
-
感谢您指出这一点
-
@usr2564301 一旦修复了,我应该得到正确的输出吗?我的数组输出给了我一个 2x2
-
它将修复您遇到的错误。你的算法是否正确,我不知道。
-
好的,谢谢你的帮助!
标签: python newtons-method