这是我的代码。我想同时以矩阵形式迭代函数f(x)及其导数矩阵。我该怎么办?
import numpy as np
import sympy as sp
x=sp.Symbol('x')
k=[]
def m1(x):
return 4*x**2 + 8*x
def m2(x):
return 8*x**2 + 6*x
def m3(x):
return x**2 + 10*x
def m4(x):
return 10*x**2 + x
def dm1(x):
return sp.diff(m1(x),x)
def dm2(x):
return sp.diff(m2(x),x)
def dm3(x):
return sp.diff(m3(x),x)
def dm4(x):
return sp.diff(m4(x),x)
def f(x):
return([[m1(x),m2(x)],[m3(x),m4(x)]]) # function matrix
def k(x):
return ([[dm1(x),dm2(x)],[dm3(x),dm4(x)]]) # derivative matrix
答案 0 :(得分:0)
import numpy as np
import sympy as sp
x=sp.Symbol('x')
k=[]
tol = 1e-3
def m1(x):
return 4*x**2 + 8*x
def m2(x):
return 8*x**2 + 6*x
def m3(x):
return x**2 + 10*x
def m4(x):
return 10*x**2 + x
def dm1(val):
return m1(x).diff(x).subs(x,val)
def dm2(val):
return m2(x).diff(x).subs(x,val)
def dm3(val):
return m3(x).diff(x).subs(x,val)
def dm4(val):
return m4(x).diff(x).subs(x,val)
def f(x):
return [m1(x), m2(x), m3(x), m4(x)] # function matrix
def k(val):
return [dm1(val), dm2(val), dm3(val), dm4(val)] # derivative list
x_bar = 5.
x_results = []
for i in range(0,4):
h=1
x_temp = x_bar
print(x_temp)
while (abs(h) > tol):
h = -1.*f(x_temp)[i]/k(x_temp)[i]
print(h)
x_temp = x_temp + h
x_results.append(x_temp)
print(x_results)
print(f(x_results[0]))
编辑:上面的方法分别解决了每个函数的问题,而不是像线性地震反演那样解决所有1个变量的问题,下面的解决方法应该是正确的:
import numpy as np
import sympy as sp
x=sp.Symbol('x')
k=[]
tol = 1e-3
def m1(x):
return 4*x**2 + 8*x
def m2(x):
return 8*x**2 + 6*x
def m3(x):
return x**2 + 10*x
def m4(x):
return 10*x**2 + x
def dm1(val):
return m1(x).diff(x).subs(x,val)
def dm2(val):
return m2(x).diff(x).subs(x,val)
def dm3(val):
return m3(x).diff(x).subs(x,val)
def dm4(val):
return m4(x).diff(x).subs(x,val)
def f(x):
return [m1(x), m2(x), m3(x), m4(x)] # function matrix
def k(val):
return [dm1(val), dm2(val), dm3(val), dm4(val)] # derivative list
x_start = 5.
F = np.array(f(x_start))
dF = np.array(k(x_start))
dx = 1.
x_temp = x_start
while abs(dx) > tol:
make_square = np.dot(np.transpose(dF),dF)
print(make_square)
print(type(dF))
if make_square is not np.ndarray:
inverse = 1/make_square
#inverse = np.linalg.inv(make_square)
else:
inverse = np.linalg.inv(make_square)
#inverse = 1/make_square
inv_trans = np.dot(inverse,np.transpose(dF))
dx = -1.*np.dot(inv_trans, F)
print(dx)
x_temp = x_temp + dx
F = np.array(f(x_temp))
dF = np.array(k(x_temp))
print(x_temp)