简体   繁体   中英

Why is my gaussian np.array not symmetric?

I am trying to write a function that returns an np.array of size nx x ny that contains a centered gaussian distribution with mean mu and sd sig . It works in principle like below but the problem is that the result is not completely symmetric. This is not a problem for larger nx x ny but for smaller ones it is obvious that something is not quite right in my implementation ...

For:

create2dGaussian (1, 1, 5, 5)

It outputs:

[[ 0.   0.2  0.3  0.1  0. ]
 [ 0.2  0.9  1.   0.5  0. ]
 [ 0.3  1.   1.   0.6  0. ]
 [ 0.1  0.5  0.6  0.2  0. ]
 [ 0.   0.   0.   0.   0. ]]

... which is not symmetric. For larger nx and ny a 3d plot looks perfectly fine/smooth but why are the detailed numerics not correct and how can I fix it?

import numpy as np


def create2dGaussian (mu, sigma, nx, ny):
    x, y = np.meshgrid(np.linspace(-nx/2, +nx/2+1,nx), np.linspace(-ny/2, +ny/2+1,ny))
    d = np.sqrt(x*x+y*y)
    g = np.exp(-((d-mu)**2 / ( 2.0 * sigma**2 )))


    np.set_printoptions(precision=1, suppress=True)
    print(g.shape)
    print(g)
    return g

----- EDIT -----

While the below described solution works for the problem mentioned in the headline (non-symmetric distribution) this code has also some other issues that are discussed here .

Numpy's linspace is inclusive of both edges by default, unlike range , you don't need to add one to the right side. I'd also recommend only dividing by floats, just to be safe:

x, y = np.meshgrid(np.linspace(-nx/2.0, +nx/2.0,nx), np.linspace(-ny/2.0, +ny/2.0,ny))

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