0

I wrote this code in Matlab and I am looking for equivalent code in Python. Can someone help? The code is to generate N Points inside a rectangle of side LxL with Gaussian Distribution. The code was obtained from this link: gaussian_inside_rectangle

function ans = randn_rect( N, sigma, L )
ans = zeros(0,2);
while size(ans,1) < N,
   pts = sigma * randn( ceil(1.25*(N-size(ans,1))), 2 );    
   pts = pts(all(abs(pts)<L/2,2),:);
   ans = [ ans ; pts ];
end
ans = ans(1:N,:);
Community
  • 1
  • 1
sys
  • 103
  • 3

1 Answers1

1

So you want to sample N 2-dimensional points from a truncated normal distribution? Gladly, scipy comes with that one built-in.

This generates a N*2 numpy array points with random points:

from scipy.stats import truncnorm
import numpy as np

N = 1000
L = 5.0
mu = 4.0
sigma = 0.8

lower, upper = 0, L

X = truncnorm(
    (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)

points = np.reshape(X.rvs(2*N), (N, 2))

The code was adapted from this answer.

Community
  • 1
  • 1
Carsten
  • 17,991
  • 4
  • 48
  • 53
  • Thanks a lot, I run the code for N =10 and L = 100, I have obtaied these points: [[ 3.12334787 3.70831649] [ 3.58128416 5.73846664] [ 4.3797186 4.03120809] [ 5.30411406 4.4329382 ] [ 4.50553099 4.00487617] [ 2.77175744 4.44342638] [ 4.18085468 3.42912618] [ 3.64834852 3.32652222] [ 4.19270372 4.1313387 ] [ 4.65842432 2.40781954]] all the values are arround 4 even if L is 100 ?? – sys Apr 07 '14 at 15:10
  • If you didn't change `mu`, then yes, your values should be centered around 4. The array you've posted looks good. – Carsten Apr 07 '14 at 15:54
  • Then, I should set mu to 100 – sys Apr 07 '14 at 15:55
  • I mean that the values are not ditributed all over the area of 100x100. Points are all very close to point(4,4) – sys Apr 07 '14 at 16:01
  • Why would they distributed all over the area? The distribution in the example has a standard deviation of 0.8. It appears that you don't really know what a normal (Gaussian) distribution is. You should read up on that first. – Carsten Apr 07 '14 at 16:20