marriam nayyer
marriam nayyer

Reputation: 697

Matlab random vs np.randn

i am trying a piece of code in python its giving wrong result.i just want to confirm that np.randn function is same as Matlab randn plzz helppp

S=[ 3.+3.j  1.-3.j -3.+1.j  1.+3.j  1.-1.j]
SNR=arange(6,23,1)

BER=zeros(len(SNR))  
Es=10


for ii in arange(0,len(SNR)):

  variance=Es*(10**(-SNR[ii]/10))
  std_dev=cmath.sqrt(variance/2)
  noise=(np.random.randn(len(S))+cmath.sqrt(-1)*np.random.randn(len(S))) *std_dev
  S_noisy=S+noise


print(noise)

matlab code

SNR=6:22;
display(SNR)
display(length(SNR))
BER=zeros(1,length(SNR));

display(BER)
display(length(BER))
Es=10;


for ii=1:length(SNR)
   variance=Es*10^(-SNR(ii)/10);
   std_dev=sqrt(variance/2);
   noise=(randn(1,length(S))+sqrt(-1)*randn(1,length(S)))*std_dev;
   S_noisy=S+noise;


end

display(noise)

result should be

 [0.1150 + 0.1889i  -0.0756 + 0.2055i   0.1862 + 0.0094i   0.1174 - 0.2288i

0.4456 - 0.0659i]

Upvotes: 1

Views: 3171

Answers (1)

unutbu
unutbu

Reputation: 879191

NumPy's np.random.randn returns samples from a standard normal distribution. The result won't be the same from run to run. You could get reproducible results by setting the seed:

np.random.seed(123)

But this will not necessarily produce the same result as the one you are getting from Matlab. Matlab uses its own random number generator, and as far as I know, there is no way to synchronize Matlab's random numbers with NumPy's.

If you want the exact same results, save the random numbers generated by Matlab into a file, then load those numbers into NumPy.

Upvotes: 4

Related Questions