如何以给定的错误概率打印列表的二进制数(Python)

问题描述 投票:0回答:2

如果我有一个二进制数列表(0和1)。而且我需要以概率p(p = 1通道错误的概率)打印这些数字。

如果错误概率= 0.2(p = 0.8)且安全系数为101010101010,则解决方案将类似于101011101000 ...


Per = float(input("Introduzca probabilidad de error: "))
while Per > 1 or Per < 0:
    print("P.error ha de tener un valor comprendido entre 0 y 1/2")
    Per = float(input("Introduzca probabilidad de error: "))

q = 1 - Per
import random

entrada = int(input("Introduzca manualmente secuencia de bits: "),2)
bits = [int(x) for x in bin(entrada)[2:]]
python list printing binary probability
2个回答
0
投票

您可以遍历这些位,并且每个步骤都会生成一个介于0和1之间的随机值。如果您的随机值小于q,则将正确的位添加到新列表bits_con_error中。如果您的随机值大于q,则可以使用randint(0,1)

添加一个随机生成的1或0。
Per = float(input("Introduzca probabilidad de error: "))
while Per > 1 or Per < 0:
    print("P.error ha de tener un valor comprendido entre 0 y 1/2")
    Per = float(input("Introduzca probabilidad de error: "))

q = 1 - Per
import random

entrada = int(input("Introduzca manualmente secuencia de bits: "),2)
bits = [int(x) for x in bin(entrada)[2:]]

bits_con_error = []
for bit in bits:
    if random.random() < q:
        bits_con_error.append(bit)
    else:
        bits_con_error.append(random.randint(0, 1))
print(bits_con_error)

或者如果通道中的错误应翻转该位,而不是随机生成一个新位,则可以使用bits_con_error.append(int(not bit))


0
投票

尝试一下:

import random
tot = len(entrada)
approx= round(Per*tot)

temp = list(entrada)
entrada = list(entrada)
for i in random.sample(range(0,tot),approx):
  if entrada[i]=='1':
    entrada[i]='0'
  else:
    entrada[i]='1'

count = 0
for i in range(len(entrada)):
  if(temp[i]!=entrada[i]):
    count+=1

entrada =''.join(entrada)
print('modified entrada is : ',entrada)
print('error after modification is : ',round(count/len(entrada),3),' approximately..')

输出:

modified entrada is :  000111001011
error after modification is :  0.167  approximately..
© www.soinside.com 2019 - 2024. All rights reserved.