在2D阵列上评估solve_ivp解决方案



我正在用scipy.integrate.solve_ivpdense_output=True解决一个初值问题。这应该产生一个插值多项式,它可以帮助我评估解域内任意点的解。

我想在2D阵列上评估解决方案。我本来希望能马上完成,但这似乎不可能:

res = solve_ivp(... , dense_output = True)
res.sol(a_2d_array)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如果我先展平数组,我就能做到:a_2d_array.ravel()。。。但在评估后,我必须再次恢复形状。有更好(或更有效(的方法吗?

当您需要重塑数组时,不要担心效率。它们很快,因为阵列数据不被复制(正常情况下(。

压扁:

>>> a = np.random.random((1000, 1000))
>>> shape = a.shape
>>> b = a.ravel()
>>> b.shape
(1000000,)
>>> b.base is a
True
>>> b = a.reshape(-1)
>>> b.shape
(1000000,)
>>> b.base is a
True

恢复原始形状:

>>> c = b.reshape(shape)
>>> c.shape
(1000, 1000)
>>> c.base is a
True
>>> b.shape = shape
>>> b.shape
(1000, 1000)
>>> b.base is a
True

一些时间安排:

>>> %timeit b = a.ravel()
128 ns ± 0.57 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> %timeit b = a.reshape(-1)
421 ns ± 59.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> %timeit c = b.reshape(shape)
189 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> %timeit b.shape = shape
152 ns ± 0.529 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

相关内容

最新更新