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

2024-05-15 03:44:12 发布

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

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

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

如何提高速度?

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


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  """)

Tags: npseqaanesumc2fts2
1条回答
网友
1楼 · 发布于 2024-05-15 03:44:12
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

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),axis=1), np.sum(np.sin(ta1),axis=1)
c2, s2 = np.sum(np.tan(ta2),axis=1), np.sum(np.sin(ta2),axis=1)
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
seq=np.arange(0,nf)
np.savetxt(as,np.c_[seq,ft,h,hp,1.0/ft])



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

相关问题 更多 >

    热门问题