加快一个程序的速度,该程序可以计算巨大数组中邻居的平均值 [英] Speed up a program that calculate the average of the neighbors in a huge array
问题描述
我的程序速度有问题.我想在一个巨大的数组中计算四个邻居的平均值.这是我的代码的一部分.您有任何想法如何更改最后一行吗?还是应该使用另一个数组?
I have a problem with the speed of my program. I want to calculate the average of four neighbors in a huge array. Here is a part of my code. Do you have any ideas how to change the last line? Or should I use another array?
for a in np.arange(100000):
for x in np.arange(size):
for y in np.arange(size):
if unchangeableflag[x*size+y] == 0:
vnew[x*size+y] = (v[(x+1)*size+y] + v[(x-1)*size+y] + v[x*size+y+1] + v[x*size+y-1]) / 4.0
推荐答案
您根本不需要循环.假设v
,vnew
和unchangeableflag
是具有size*size
条目的一维数组,则可以
You would not need the loop at all. Assuming v
, vnew
and unchangeableflag
are 1-d arrays with size*size
entries, you can do
v = v.reshape(size, size)
vnew = vnew.reshape(size, size)
unchangeableflag = unchangeableflag.reshape(size, size)
average = v[1:-1, 2:]
average += v[1:-1, :-2]
average += v[2:, 1:-1]
average += v[-2:, 1:-1]
average /= 4.0
vnew[1:-1, 1:-1][unchangeableflag[1:-1, 1:-1] == 0] = average
但是您实际上想实现什么?这看起来令人怀疑,就像您可以使用离散Laplacian的某些应用程序一样.
But what are you actually trying to achieve? This looks suspiciously like you could get away with some application of the discrete Laplacian.
(请注意,这假定v
包含浮点数.如果'v'的dtype
是sime整数类型,则需要进行一些修改.)
(Note that this assumes that v
contains floating point numbers. If the dtype
of `v´ is sime integral type, you need a slight modification.)
这篇关于加快一个程序的速度,该程序可以计算巨大数组中邻居的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!