我试图创建一个函数,对多个变量(dx=-Jinv^-1*F)进行Newton-Raphson根查找,但它不会在循环中连续迭代(即输出不会成为下一次迭代的下一个输入)。有人看到这个问题吗
另外,我试图在不使用任何内置矩阵函数的情况下对其进行编码,这样这些解决方案就不适用于这里
# Multivariable Root Finding via Newton Raphson
# import necessary functions
import numpy as np
# define array function for f1 and f2
x = np.arange(-3,3,.01)
def f1(x):
return 2*(x[0]**3) - 6*(x[0]*(x[1]**2)) - 1
def f2(x):
return -2*(x[1]**3) + 6*(x[1]*(x[0]**2)) + 3
# define matrix F(x) 2x1
def F(x_vec):
return [f1(x_vec),f2(x_vec)]
#print(F([2,3]))
# Create Inverse Jacobian 2x2
# InvJacobian Upper Left
def JUL(x):
return (6*x[0]**2 - 6*x[1]**2)/((6*x[0]**2 - 6*x[1]**2)**2 + 144*(x[0]**2)*(x[1]**2))
# InvJacobian Upper Right
def JUR(x):
return (12*x[0]*x[1])/((6*x[0]**2 - 6*x[1]**2)**2 + 144*(x[0]**2)*(x[1]**2))
# InvJacobian Lower Left
def JLL(x):
return (-12*x[0]*x[1])/((6*x[0]**2 - 6*x[1]**2)**2 + 144*(x[0]**2)*(x[1]**2))
# InvJacobian Lower Left
def JLR(x):
return (6*x[0]**2 - 6*x[1]**2)/((6*x[0]**2 - 6*x[1]**2)**2 + 144*(x[0]**2)*(x[1]**2))
# Combine all Jacobian into Matrix
def Jinv(x_vec):
return [JUL(x_vec),JUR(x_vec),JLL(x_vec),JLR(x_vec)]
# Create Newton Raphson Functon
def rf_newton2d(F_system, Jinv_system, x_vec0, tol, maxiter):
# let ou be the starting array x_vec0
ou = x_vec0
i = 0
err = 10**-4
# F*Jinv should output a 2x1 matrix
while err > tol and i <= maxiter:
F_system = F(ou)
Jinv_system = Jinv(ou)
# w is the [0] position of the 2x1 output matrix
w = F_system[0]*Jinv_system[0] + F_system[1]*Jinv_system[1]
# z is the [1] position of the 2x1 output
z = F_system[0]*Jinv_system[2] + F_system[1]*Jinv_system[3]
# u is the output matrix of F*Jinv
u = [w,z]
# out is the new array involving u + ou
out = [ou[0] + u[0],ou[1] +u[1]]
#define nu as out
nu = out
# let nu be the ou for the next iteration
ou = nu
#run continuous iterations
i += 1
return nu
print(rf_newton2d(F([x_vec0]),Jinv([x_vec0]),[2,3],10**-5, 5))
函数中的
return
语句立即停止函数并继续运行调用函数的主代码。在我看来while
循环中的return
语句不应该在while
循环中在最后一行中有函数
F([x_vec0])
,这意味着在函数F
中有变量x_vec = [x_vec0]
。然后将此变量传递给函数f1
,因此在f1
,x = [x_vec0]
内。在x[1]
中可以找到f1
。问题是x
永远不会有第二个条目。如果x_vec0 = [0,1]
(或其他一些数组对象,如np.ndarray
),则[x_vec0] = [[0,1]]
,即[x_vec0][0] = [0,1]
和[x_vec0][1]
不存在我从回溯中获得了所有信息(显然我必须为
x_vec0
创造一个值):如果不知道牛顿-拉斐逊根的数学,我就无法提出修正是什么
相关问题 更多 >
编程相关推荐