计算(实验)抛头概率

Calculating (experimental) probability of head toss

我想通过随机生成 0 或 1 来计算抛硬币正面朝上的实验概率,并将 'h' 分配给 0,将 't' 分配给 1 到 n。翻转次数为100.

import random

array_ht = []

flip_count = 0

while flip_count != 100:
    n = random.randint(0,1)
    if n == 0:
        n = "h"
    elif n == 1:
        n = "t"
    flip_count += 1
    array_ht.append(n)

for x in array_ht:
    h_count = 0
    if x == "h":
        h_count += 1

    print(h_count + "%")

for 循环遍历 array_ht 的每个对象,如果找到“h”,则将头部翻转次数加 1。但是代码不起作用,只打印“1% 0% 1% 0% 0% ...”

实际应该发生的是,例如,如果生成的序列是“0,1,1,0,0,0,1,1,1”,那么 array_ht = [h,t,t,h ,h,h,t,t,t] 并且要打印的概率是 (4/9*100=) 44.444444%.

实际上我们不需要将 'h' 或 't' 分配给 n,我们可以只查找 0 的数量,但早些时候我也想打印 array_ht。

这有帮助吗?这会以 % 百分比格式计算 ht 的概率。

解释:

import random

tosses = []

# Getting A List With 100, 0s and 1s in it
for i in range(100):
    tosses.append(random.randint(0, 1))

# Indexing Every 0 for a `h` and every 1 for a `t`
for i in range(len(tosses)):
    if tosses[i] == 0:
        tosses[i] = "h"
    else:
        tosses[i] = "t"

# Getting Count Of How Many Times Heads Or Tails Was In The List
freq_h = tosses.count('h')
freq_t = tosses.count('t')


# Calculating The Probablity (freq/total_outcomes) (x100 optional if want to calculate in percentage use x100)
prob_h = (freq_h/len(tosses))*100
prob_t = (freq_t/len(tosses))*100

# Adding A `%` sign to the numbers and round them up
percent_h = str(round(prob_h)) + "%"
percent_t = str(round(prob_t)) + "%"

# The Final Result
print("Probablity Heads:", percent_h)
print("Probablity Tails:", percent_t)

编辑: 先前解决方案的大大缩短的版本(快速而肮脏)

import random
tosses = []
for i in range(100):
    tosses.append(random.randint(0, 1))
for i in range(len(tosses)):
    if tosses[i] == 0:
        tosses[i] = "h"
    else:
        tosses[i] = "t" 

print("Probablity Heads:", str(round((tosses.count('h')/len(tosses))*100)) + "%")
print("Probablity Tails:", str(round((tosses.count('t')/len(tosses))*100)) + "%")

您的问题的简单解决方案是将 h_count = 0 移出 for 循环。但除此之外,您的整个代码都可以简化:

import random

tosses = ["ht"[random.randint(0, 1)] for i in range(100)] # we can use string indexing to convert "h" and "t" to 0 an 1, respectively.

print(f"{(tosses.count('h') / len(tosses)) * 100}%")

您的代码打印 1% 0% 1% 1% 的原因是因为您在 for 循环中放置了 print 语句和 h_count 变量,因此每次迭代时它都会重新初始化超过 array_ht

for x in array_ht:
    h_count = 0
    if x == "h":
        h_count += 1

    print(h_count + "%")

所以如果你对你的程序做一个干燥的 运行,它的作用如下:

array_ht中取出一个元素然后将h_count初始化为0 如果元素 = "h",它会在 h_count

中加 1

然后打印 h_count 一次迭代结束,返回开始,

array_ht中的下一个元素并重新初始化h_count为0 然后又是同样的事情

这是我制作的版本:

import random

def toss(num):
    array = [random.randint(0,1) for x in range(num)]
    return array.count(0), array.count(1)


outcomes = toss(1000)
heads = outcomes[0]
tails = outcomes[1]

print(f"Probability of Heads: {heads/sum(outcomes)*100}%")
print(f"Probability of Tails: {tails/sum(outcomes)*100}%")