我是python的初学者,而我完全了解算法。 我需要你的帮助,我希望你帮助我解决以下问题。我只能说,请帮助我。对我来说,对这个问题给出消极或积极的印记并不重要,只需帮助我PLZ。
在下面的代码中我遇到了一个问题:
让我解释一下:使用m=(ss-h)
的代码中间的datafile.txt
一词最初是:m=(u[i]-h)
我将u[i]
替换为ss
}。现在,如果我想将z[i]
替换为aa
以删除for循环并避免data_file.txt
导入,我该怎么办?
如果我只是将此代码中的z[i]
替换为aa
,则会出现错误:
ValueError: setting an array element with a sequence.
我搜索过这个错误,我发现ODE需要一维数组。据我所知,aa
是二维数组。
现在我谈到了我的问题。我想要的一件事是调用m[1]
,代码会自动aa[1]
和ss[1]
,m[1]=(ss[1]-M-h)
和aa[1]
进入h
}以及其他m
。
0.01 32.95388698
0.012 33.87900347
0.014 33.84214074
0.016 34.11856704
0.019 34.59344598
0.023 34.93902653
0.026 35.25209633
0.031 35.74850165
0.037 36.06978761
0.043 36.43457047
代码是:
from math import *
import numpy as np
from scipy.integrate import quad
from scipy.integrate import odeint
z,u=np.genfromtxt('Datafile.txt',unpack=True)
aa=np.array([0.01,0.012,0.014,0.016,0.019,0.023,0.026,0.031,0.037,0.043])
ss=np.array([32.95388698,33.87900347,33.84214074,34.11856704,34.59344598,
34.93902653,35.25209633,35.74850165,36.06978761,36.43457047])
Cov= [[21282,-10840,1918,451,946,614,785,686,581,233],
[0,28155,-2217,1702,74,322,380,273,424,487],
[0,0,6162,-1593,1463,419,715,580,664,465],
[0,0,0,5235,-722,776,588,591,583,403],
[0,0,0,0,7303,-508,1026,514,596,315],
[0,0,0,0,0,3150,-249,800,431,358],
[0,0,0,0,0,0,3729,-88,730,321],
[0,0,0,0,0,0,0,3222,-143,568],
[0,0,0,0,0,0,0,0,3225,-508],
[0,0,0,0,0,0,0,0,0,5646]]
def ant(z,O_m,O_D):
return 1/sqrt(((1+z)**2)*(1+O_m*z)-z*(2+z)*O_D)
def HDE(y,z):
a=1/(1+z)
p=log(alpha+beta*a)
pd=beta*a/(alpha+beta*a)
dydz = -((C**2-y)*((pd/p)*(y-2)-(pd**3)/(p**2)+(pd**2)/p+1.5*(y*(b+1)-1))/(1-(pd**2)/(p**2)+2*pd/p-0.5*(C**2+y)))*(1/(1+z))
return dydz
b=0.01
M=4
C=0.5
O_m=0.23
alpha=1
beta=2
for i in range (len(z)):
y0=1-O_m
z0=0
z1=z[i]
y = odeint(HDE,y0,[z0,z1])
O_D=y[-1,0]
q=quad(ant,0,z[i],args=(O_m,O_D))[0]
h=5*log10((1+z[i])*(299000/70)*q)+25 # Here is the main problem of my code
# h and q must work with aa instead of z[i]
fl=(ss-h)
l1=[[fl[0],fl[1],fl[2],fl[3],fl[4],fl[5],fl[6],fl[7],fl[8],fl[9]]]
l2=[[fl[0]],[fl[1]],[fl[2]],[fl[3]],[fl[4]],[fl[5]],[fl[6]],[fl[7]],[fl[8]],[fl[9]]]
mm=np.dot(l2,Cov)
zz=np.dot(mm,l2)
hh=np.linalg.det(zz) #calculation of determinant
print (hh)
感谢您的帮助和关注
答案 0 :(得分:0)
对于矩阵的组件,您可以使用以下结构: 很清楚,不需要任何解释。
第二段分别选择每个组件并在矩阵中正确使用它。
def new_calculation(n):
yn = odeint(HDE,y0,[z0,xx[n]])
yyn=yn[-1,0]
O_Dn=1-O_m-(1/(2*rc*yyn))
q=quad(ant,0,xx[n],args=(O_m,O_Dn))[0]
h=log10((1+xx[n])*(299000/70)*q)+25
fn=(ss[n]-h)
return fn
f_list = []
for i in range(2): # the value '2' reflects matrix size
f_list.append(new_calculation(i))
rdag=[f_list]
rmat=[[f] for f in f_list]
mm=np.dot(rdag,Cov)
zz=np.dot(mm,rmat)
hh=np.linalg.det(zz)