您可以使用索引获取索引值的网格:
I,J=np.indices(PSI.shape)
#All constants set to one
PSI2=np.sin(I+1-.5)*np.sin(J+1-.5)
print PSI-PSI2 # should be zero.
我用 ipython 做了一些计时:
import numpy as np
import math
A = 1
P = 1
DI = 1
DJ = 1
def a():
PSI=np.zeros((1025,1025))
for J in range(1025):
for I in range(1025):
PSI[I][J] = A*math.sin((float(I+1)-.5)*DI)*math.sin((float(J+1)-.5)*DJ)
%timeit a()
def b():
PSI=np.zeros((1025,1025))
for I,J in np.ndindex(*PSI.shape):
PSI[I,J] = A*math.sin((float(I+1)-.5)*DI)*math.sin((float(J+1)-.5)*DJ)
%timeit b()
def c():
I,J=np.indices((1025, 1025))
P2=A*np.sin((I+1-.5)*DI)*np.sin((J+1-.5)*DJ)
%timeit c()
def d():
PSI_i = np.sin((np.arange(1,1026)-0.5)*DI)
PSI_j = np.sin((np.arange(1,1026)-0.5)*DJ)
PSI = A*np.outer(PSI_i, PSI_j)
%timeit d()
结果在我的机器上一点也不奇怪:
1 loops, best of 3: 1.75 s per loop
1 loops, best of 3: 3.51 s per loop
10 loops, best of 3: 77.1 ms per loop
100 loops, best of 3: 7.16 ms per loop