问题
I want to simulate fault on a message (Eg: 1000010011 => 1010000011). Is there a way to implement this in Python? I tried the following, which works:
import random
a = "1011101101"
b = [el for el in a] # b = ['1', '0', '1', '1', '1', '0', '1', '1', '0', '1']
random.shuffle(b)
print b # b = ['0', '1', '1', '1', '0', '1', '1', '1', '1', '0']
random.shuffle(b, random.random)
print b # b = ['1', '1', '0', '1', '1', '0', '1', '0', '1', '1']
I would like my reordering to be Normally/Gaussian distributed. Eg:
import random
a = "1011101101"
b = [el for el in a] # b = ['1', '0', '1', '1', '1', '0', '1', '1', '0', '1']
random.shuffle(b,random.gauss(0.5,0.1))
print b # b = ['1', '0', '1', '1', '0', '0', '1', '1', '1', '1'] <= assume this is Gaussian distributed...
# OR
c = random.gauss(0.5,0.1)
random.shuffle(b,c)
print b # b = ['0', '0', '1', '1', '1', '0', '1', '1', '1', '1'] <= assume this is also Gaussian distributed...
However, this does not work, and I get the message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\random.py", line 287, in shuffle
j = int(random() * (i+1))
TypeError: 'float' object is not callable
Any suggestion/comment would be greatly appreciated.
Thanks
Note: I am only asking for re-ordering error here(Eg: 1000010011 => 1010000011). However, I am also planning on simulating burst-error(Eg: 1000010011 => 1011111011), single events(Eg: 1000010011 => 1000010011), etc.
Other related question: Python: binary string error simulation
回答1:
The second argument of random.shuffle
should be a callable, not a float. Try:
random.shuffle(b, lambda:random.gauss(0.5,0.1))
To cap in the interval from 0 to 1, you could use
random.shuffle(b, lambda: max(0.0, min(1.0, random.gauss(0.5,0.1))))
(Thanks @DSM)
If you're pedantic, the above capping actually includes 1.0, which would lead to an error in random.shuffle
. You should in fact replace 1.0 by the largest float smaller than 1.0.
回答2:
c = lambda: random.gauss(0.5,0.1)
来源:https://stackoverflow.com/questions/13706027/how-to-shuffle-a-list-with-gaussian-distribution