我能够找到牛顿方法的几个实现,例如,this link或maybe this one。
然而,大多数情况下,示例具有简单的函数,例如:x ^ 2-9 = 0或x ^ 3-x ^ 2-1 = 0。我正在寻找适用于:的东西
我的问题是,我迷失了如何使用此代码来解决我的问题。例如,我不确定如何在包含矩阵的F(x)上应用导数(dfdx)。另外,如果我应该在我的“def f(x)”上直接输入矩阵
我正在使用的代码:
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 x**2 - 9
def dfdx(x):
return 2*x
solution, no_iterations = Newton(f, dfdx, x=1000, eps=1.0e-6)
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!"
导出矩阵没有任何特殊规则 - 衍生物只是分别为每个元素计算。我建议在纸上评估$ [x1,x2]'* M * [x1,x2] $表达式,得到多项式矩阵,然后计算每个矩阵的导数。