F Python的求解结果与MATLAB不匹配

2024-05-19 02:50:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python复制MATLAB代码,作为其中的一部分,我需要解非线性方程

最初我尝试使用fsolve方法,结果与MATLAB结果不匹配。后来我也尝试使用optimize.root,但结果与MATLAB不一样

我想知道如何在Python中优化结果。这是我的代码:

def fun(x,A,theta_1,theta_2,depth,dh,g_e,incl):
    F=np.zeros(shape=(2))
    F[0]=x[0]*np.exp(t_1*depth)+x[1]*np.exp(t_2*depth*math.cos(math.radians(incl)))+g_e*math.cos(math.radians(incl))
    F[1]=(((1+t_1/A)*x[1]*np.exp(t_1*depth))+((1+t_2/A)*x[1]*np.exp(t_2*depth))+(g_e*dh*math.cos(math.radians(incl))))

    return F


n=10

depth=2000
dx = depth/0.3048 
t_1= 0.001063321803317305 
t_2=-0.000485917956755497
incl_1=np.zeros(30)
incl_2=np.linspace(0,30,30)
incl_3=np.linspace(30,80,40)
incl_main=[*incl_1,*incl_2,*incl_3]
g=0.025

A=0.0008948453688318264
deltah=depth/n
mn=np.zeros(shape=(n,2))
x0=np.array([0,0])
for i in range(n-1,0,-1):
   mn[i]=(optimize.fsolve (fun,x0,(A,t_1,t_2,depth,deltah,g,incl_main[i])))

print(mn)

MATLAB results

Python results

function F=root2d(x,A,theta_1,theta_2,depth,dh,g_e,incl)

F=[x(1)*exp(theta_1*depth)+x(2)*exp(theta_2*depth)+g_e*cosd(incl)*dh;
  (1+theta_1/A)*x(1)*exp(theta_1*depth)+ 
   (1+theta_2/A)*x(2)*exp(theta_2*depth)+g_e*dh*cosd(incl)];

在这里,函数应与文件名root2d一起保存

n=10;
depth=2000;
deltah=depth/n;
depth = depth/0.3048 ;
c0 = [0,0];
A=0.0008948453688318264
incl=[zeros(1,30) linspace(0,30,30)  linspace(30,80,40)];
a=zeros(n,2);
theta_1= 0.001063321803317305 ;
theta_2=-0.000485917956755497;
g_e=0.025

for i=n:-1:1
 a(i,:) =fsolve(@(x)root2d(x,A,theta_1,theta_2,depth,deltah,g_e,incl(i)),c0);

end    

Tags: npzerosmathcosdhdepthmatlabmn

热门问题