以下是我尝试牛顿迭代法的代码,问题出现在矩阵求逆时给我的报错
弄了好久也不知道怎么回事
报错
numpy.core._exceptions._UFuncInputCastingError: Cannot cast ufunc 'inv' input from dtype('O') to dtype('float64') with casting rule 'same_kind'
from sympy import symbols,diff
import numpy as np
def matrixf(f):
return np.array([diff((f),x),diff((f),y)]).reshape(2,1)
def jcobe(f,arr):
return np.array([diff(f[0][0],x).evalf(subs={x:arr[0][0],y:arr[1][0]}),diff(f[0][0],y).evalf(subs={x:arr[0][0],y:arr[1][0]}),
diff(f[1][0],x).evalf(subs={x:arr[0][0],y:arr[1][0]}),diff(f[1][0],y).evalf(subs={x:arr[0][0],y:arr[1][0]})]).reshape(2,2)
x,y=symbols('x y')
f=lambda x,y:x*x+y*y-2*x
f=x*x+y*y-2*x
s=matrixf(f)
x0=np.array([0,0]).reshape(2,1)
j=jcobe(s,x0)
x1=x0-np.dot(np.linalg.inv(j),s)
print(x1)