def MultiDimNewtRaph(f,x0,dx=1e-6,args=(),ytol=1e-5,w=1.0,JustOneStep=False):
"""
A Newton-Raphson solver where the Jacobian is always re-evaluated rather than
re-using the information as in the fsolve method of scipy.optimize
"""
#Convert to numpy array, force type conversion to float
x=np.array(x0,dtype=np.float)
error=999
J=np.zeros((len(x),len(x)))
#If a float is passed in for dx, convert to a numpy-like list the same shape
#as x
if isinstance(dx,int):
dx=dx*np.ones_like(float(x))
elif isinstance(dx,float):
dx=dx*np.ones_like(x)
r0=array(f(x,*args))
while abs(error)>ytol:
#Build the Jacobian matrix by columns
for i in range(len(x)):
epsilon=np.zeros_like(x)
epsilon[i]=dx[i]
J[:,i]=(array(f(x+epsilon,*args))-r0)/epsilon[i]
v=np.dot(-inv(J),r0)
x=x+w*v
#Calculate the residual vector at the new step
r0=f(x,*args)
error = np.max(np.abs(r0))
#Just do one step and stop
if JustOneStep==True:
return x
return x
评论列表
文章目录