Reputation: 697
i am trying to convert a matlab code in numpy for calculating bit error rate a piece of code is making problem for me this is the matlab code i wanted to convert
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(variance)
python code SNR=arange(6,23,1)
BER=zeros(len(SNR))
print(BER)
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(variance)
answer of variance should be 0.063 bt in python it gives 0.01 plzz help
Upvotes: 2
Views: 564
Reputation: 879471
SNR is of dtype int32
be default. Dividing an int
by an int
gives you an int
(or raises a ZeroDivisionError
) in Python2. So
SNR[ii]/10
gives you the wrong result:
In [15]: SNR
Out[15]: array([ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22])
In [16]: SNR/10
Out[16]: array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2])
To fix, either put
from __future__ import division
at the beginning of the python code (before the import statements), or else use
variance = Es*10**(-SNR[ii]/10.0)
With this change, the end result is 0.063095734448
.
Note: In Python3, int
divided by int
will return a float by default.
For better performance when using NumPy, you will want to replace Python loops with operations on whole NumPy arrays when possible. Your code would be written like this:
import numpy as np
SNR = np.arange(6, 23)
BER = np.zeros(len(SNR))
print(BER)
Es = 10
variance = Es * 10 ** (-SNR / 10.0)
std_dev = np.sqrt(variance / 2)
noise = (np.random.randn(len(SNR)) + 1j * np.random.randn(len(SNR))) * std_dev
S_noisy = SNR + noise
print(variance[-1])
Upvotes: 3