有一枚硬币,它的正反面概率是不一样的,假设概率为p,如何让其正反面概率变为一样的?
思路:
硬币只能出现正反两面,0代表正面,1代表反面,所以设0的概率为票,1的概率为1-p
import random
def core(p):
re_dict = {
'01': 0,
'10': 1
}
re_temp = []
while True:
for i in range(2):
if random.random() <= p:
re_temp.append('0')
else:
re_temp.append('1')
rand_result = re_dict.get("".join(re_temp))
if rand_result == None:
re_temp.clear()
continue
else:
return rand_result
# test code
timesOfZero = 0
timesOfOne = 0
p = round(random.random(), 2) # 随机生成范围为(0,1)的小数p 代表概率
print("生成的概率为:", p)
# 测试10万次
for i in range(100000):
if core(p) == 1:
timesOfOne += 1
else:
timesOfZero += 1
print("生成的0为{}次".format(timesOfZero))
print("生成的1为{}次".format(timesOfOne))