【问题标题】:Could the first loop be replaced by a faster way like more matrix operations?第一个循环可以用更快的方式代替,比如更多的矩阵运算吗?
【发布时间】:2021-01-07 02:21:39
【问题描述】:

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

最终目标是获取temph001,但是我发现计算太慢了。

如何提高速度?

例如,第一个循环(for f in ft:)可以用更快的方法代替?


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

【问题讨论】:

  • 请阅读minimal reproducible example。您的问题应包括rlist 的示例 - 我们无权访问您计算机上的文件。 - 即使它只是一个构造 5000 个浮点数的数组的语句。
  • the first loop - 我只看到一个 for 循环。您尝试在没有 for 循环的情况下进行重构时出了什么问题?您能否向我们展示并解释您认为出了什么问题?
  • @wwii 是的。那个循环没问题,但速度很慢。

标签: python numpy calculation


【解决方案1】:
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  """)
 ```

【讨论】:

  • 谢谢。但我需要先运行 sin 和 tan,然后运行 ​​sum,而不是先运行 sum,然后运行 ​​sin 和 tan。为什么要注释掉“打印”?
  • 好的,我编辑了答案。使用 meshgrid 基本上具有 2d 网格结构,其中列对应于 rlist 条目,行对应于 ft 条目。在整个网格上执行直到 tan 和 sin 的操作,然后在 rlist 维度(列)上求和。我还在底部添加了一个 np.savetxt ,它应该与您打印的内容相同,除了矢量化而不是通过循环。
  • 我尝试了一个小数据集。有用。问题是meshgrid很容易导致memoryError。 rlist 和 ft arr 的顺序分别为 5e3 和 5e8。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 2014-11-22
  • 1970-01-01
  • 2019-06-27
  • 2019-06-12
相关资源
最近更新 更多