简体   繁体   中英

Faster way to fill 2d numpy array with these noise parameters? Currently looping over each element

Is there a faster way to populate a 2d numpy array using the same algorithm (pnoise3 with the same input arguments, notably, i/scale j/scale) seen here? self.world is the np array and it is pretty large (2048,1024) to be traversing like this.

for i in range(self.height):
    for j in range(self.width):

        self.world[i][j] = noise.pnoise3(i/self.noise['scale'], 
                                        j/self.noise['scale'], 
                                        SEED,
                                        octaves = self.noise['octaves'], 
                                        persistence = self.noise['persistence'], 
                                        lacunarity = self.noise['lacunarity'], 
                                        repeatx= self.width, 
                                        repeaty= self.height, 
                                        base= 0)

After learning about boolean indexing I was able to get rid of this nested for loop elsewhere in my program and was amazed at how much more efficient it was. Is there any room for improvement above?

I thought about doing something like self.world[self.world is not None] = noise.pnoise3(arg, arg, etc...) but that cannot accommodate for the incrementing i and j values. And would setting it to a function output mean every value is the same anyways? I also thought about make a separate array and then combining them but I still cannot figure out how to reproduce the incrementing i and j values in that scenario.

Also, as an aside, I used self.world[self.world is not None] as an example of a boolean index that would return true for everything but I imagine this is not the best way to do what I want. Is there an obvious alternative I am missing?

If pnoise is perlin noise then there are numpy vectorized implementations. Here is one .

As it is I do not think you can do it faster. Numpy is fast when it can do the inner loop in C. That is the case for built in numpy functions like np.sin.

Here you have a vector operation where the operation is a python function.

However it could be possible to re-implement the noise function so that it internally uses numpy vectorized functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM