我试图在我的代码中加速一个函数
我写的最初函数是:
def f(self):
temp = 0
for i in range(self.N):
for j in range(self.N):
a = self.Asolution[:, j]
b = self.Bsolution[:, i]
c = self.Matrix[j][i]
d = c*np.multiply(a, b)
temp += simps(d, self.time)
return temp
其中self.Asolution = odeint(...)
,与self.Bsolution
相同
self.Matrix
是一个大小为self.N x self.N
的平方矩阵,simps
是辛普森积分self.Asolution
和self.Bsolution
有维度(txn)
但是,我需要多次调用此函数,而且由于self.N
相当大,调用时间太长。在此之前,我决定尝试一下numpy内置函数,因为我主要处理矩阵乘法。我倾向于对所有东西使用for循环,这不是最明智的选择。。。因此,我对内置的numpy函数有点不熟悉。我将函数修改为:
def f(self):
d = np.dot(np.dot(self.Asolution, self.Matrix), self.Bsolution.transpose())
d = np.array(d)
temp = simps(d, self.time)
temp = sum(temp)
return temp
这是显着更快,但我没有得到同样的结果如上所述
我想我误解了np.dot的用法,或者我错过了矩阵相乘的方法。 我的主要目标是从第一个代码中删除double for循环,因为它需要永远。我错过了什么?提前感谢您的任何提示
编辑:
self.Asolution
和 self.Bsolution
有大小(t x N)-每列都是不同的位置,行表示位置随时间的变化
self.Matrix
具有大小(nxn)
让我们试试这个-
让我知道它是否有效
经过多次尝试和错误,我设法找到了一种比双for循环更快地获得相同结果的方法。我发布它只是为了完整性和结束问题
相关问题 更多 >
编程相关推荐