问题描述
我想模拟一条消息的错误(例如:1000010011 => 1010000011).有没有一种方法可以在Python中实现呢?我尝试了以下可行的方法:
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.
谢谢
注意:我只在这里要求重新排序错误(例如:1000010011 => 1010000011).但是,我还计划模拟突发错误(例如:1000010011 => 1011111011),单个事件(例如:1000010011 => 1000010011),等等.
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.
其他相关问题: Python:二进制字符串错误模拟
推荐答案
random.shuffle
的第二个参数应该是可调用的,而不是浮点数.试试:
The second argument of random.shuffle
should be a callable, not a float. Try:
random.shuffle(b, lambda:random.gauss(0.5,0.1))
要设置介于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))))
(感谢@DSM)
如果您是学徒,则上述上限实际上包括1.0,这将导致random.shuffle
中的错误.实际上,您应该用小于1.0的最大浮点数代替1.0.
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.
这篇关于如何使用高斯分布对列表进行混洗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!