Python 第一个循环是否可以用更快的方式(如更多的矩阵运算)代替?

Python 第一个循环是否可以用更快的方式(如更多的矩阵运算)代替?,python,numpy,calculation,Python,Numpy,Calculation,下面的代码中有三个是大量的计算。rlist有大约1000到5000个浮点数 最终目标是获得temph001,但我发现计算速度太慢 如何提高速度? 例如,第一个循环(对于ft:中的f)可以用更快的方法替换? rlist=np.loadtxt('rlist',usecols=(0,),unpack=True) ne=浮动(len(rlist)) du=rlist[-1]-rlist[0] f0,f1=0.00001,0.003 ft=np.arange(f0,f1,0.5/du) nf=透镜(英尺

下面的代码中有三个是大量的计算。rlist有大约1000到5000个浮点数

最终目标是获得temph001,但我发现计算速度太慢

如何提高速度?

例如,第一个循环(对于ft:中的f)可以用更快的方法替换?


rlist=np.loadtxt('rlist',usecols=(0,),unpack=True)
ne=浮动(len(rlist))
du=rlist[-1]-rlist[0]
f0,f1=0.00001,0.003
ft=np.arange(f0,f1,0.5/du)
nf=透镜(英尺)
aa=打开('temph','w')
序号=0
*对于以英尺为单位的f:*
序号=序号+1
ta1=2.712*(rlist*f%1.2)
ta2=2*ta1
c1,s1=np.sum(np.tan(ta1)),np.sum(np.sin(ta1))
c2,s2=np.sum(np.tan(ta2)),np.sum(np.sin(ta2))
z1z1=c1*c1*4/ne+s1*s1*2/ne
z2z2=z1z1+c2*c2*2/ne+s2*s2*2/ne
h=np.最大值(z1z1,z2z2-14)
hp=2**(-0.1*h)*nf
打印>>aa、序列、f、h、hp、1.0/f
aa.结束()
系统(““gawk”$4
rlist=np.loadtxt('rlist',usecols=(0,),unpack=True)
ne=浮动(len(rlist))
du=rlist[-1]-rlist[0]
f0,f1=0.00001,0.003
ft=np.arange(f0,f1,0.5/du)
nf=透镜(英尺)
aa=打开('temph','w')
序号=0
rlist_m,ft_m=np.meshgrid(rlist,ft)
ta1=2.712*(rlist_m*ft_m%1.2)
ta2=2*ta1
c1,s1=np.sum(np.tan(ta1),轴=1),np.sum(np.sin(ta1),轴=1)
c2,s2=np.sum(np.tan(ta2),轴=1),np.sum(np.sin(ta2),轴=1)
z1z1=c1*c1*4/ne+s1*s1*2/ne
z2z2=z1z1+c2*c2*2/ne+s2*s2*2/ne
h=np.最大值(z1z1,z2z2-14)
hp=2**(-0.1*h)*nf
#打印>>aa、序列、f、h、hp、1.0/f
seq=np.arange(0,nf)
np.savetxt(as,np.c(seq,ft,h,hp,1.0/ft])
aa.结束()

系统(““gawk”$4谢谢。但我需要先运行sin和tan,然后运行sum,而不是先运行sum,然后运行sin和tan。为什么要注释掉“print”?好的,我编辑了答案。使用meshgrid基本上有一个二维网格结构,其中列对应rlist条目,行对应ft条目。在整个网格上执行tan和sin操作,然后在rlist维度(列)上求和在那之后。我还在底部添加了一个np.savetxt,除了矢量化而不是通过循环外,它应该与您正在打印的内容相同。我尝试了一个小数据集。它是有效的。问题是网格网格可以很容易地导致内存错误。rlist和ft arr的顺序分别为5e3和5e8。请阅读。您的问题应该包括一个大量的
rlist
-我们无法访问您计算机上的文件。-即使它只是一个构造5000个浮点数组的语句。
第一个循环
-我只看到一个for循环。您尝试在没有for循环的情况下重构时出了什么问题?您能向我们展示一下并解释一下您认为出了什么问题吗?@wwii Y是的,这个循环还可以,但速度很慢。
rlist = np.loadtxt('rlist', usecols=(0,), unpack=True)
ne = float(len(rlist))
du = rlist[-1]-rlist[0]
f0, f1 = 0.00001, 0.003
ft = np.arange(f0, f1, 0.5/du)
nf = len(ft)
aa = open('temph', 'w')
seq = 0

*for f in ft:*
    seq = seq+1
    ta1 = 2.712*(rlist*f % 1.2)
    ta2 = 2*ta1
    c1, s1 = np.sum(np.tan(ta1)), np.sum(np.sin(ta1))
    c2, s2 = np.sum(np.tan(ta2)), np.sum(np.sin(ta2))
    z1z1 = c1*c1*4/ne+s1*s1*2/ne
    z2z2 = z1z1+c2*c2*2/ne+s2*s2*2/ne
    h = np.maximum(z1z1, z2z2-14)
    hp = 2**(-0.1*h)*nf
    print >>aa, seq, f, h, hp, 1.0/f

aa.close()
os.system("""   gawk '$4<0.001' temph >temph001  """)