python - 计算条件概率 Python

标签 python probability

我正在尝试使用分层树结构计算结果的概率 enter image description here

The top is computer Computer A, the next 2 are Computer B & C, and the last 4 are Computer BD, BE, and CD, CE. I am trying to find the probability that if computer A gets infected with a virus what is the probability that B or C gets infected with a virus. And if B or C gets infected what is the probability that BD, BE, CD, CE gets infected with a virus

我想进行 100 次试验来找到答案。我是在 python 上做概率的新手。然而,这是我到目前为止的代码:

import random, time

#prob that computers will get virus
CompA = 0.50
CompB = .25 
CompC = .25
CompBD = .125
CompBE= .125
CompCD= .125
CompCE= .125



def generate():
    x = random.random()
    if x =< CompA: #Computer A has virus
       prob_compa= sum(generate() for i in range(100)) #prob that Comp A has virus  in a 100 rounds
       print (prob_compa/100 + 'percent chance of getting virus')

        try:
            if CompB<.125:
                 prob_compa sum(generate() for i in range(100)) #prob that Comp B has virus  in a 100 rounds
                print (prob_compa/100 + 'percent chance of getting virus')
                 elif CompB<.125:
                 prob_compa= sum(generate() for i in range(100)) #prob that Comp C is sick  in a 100 rounds
       print (prob_compa/100 + 'percent chance of getting virus')

      #I continue this method for the rest of the tree

有没有更好、更简单的方法让我得到结果? 随机均匀???

最佳答案

据我了解,这就是您想要实现的目标:

#python_test2.py
import random, time

virus_probabilities= { "CompA" : 0.50, "CompB" : .25, "CompC" : .25, "CompBD" : .125,
                   "CompBE" : .125, "CompCD" : .125, "CompCE" : .125}

def check_probability(computer_name, n_repetitions = 100):
    prob_comp, repetitions = 0, 0
    p_computer = virus_probabilities[computer_name]
    while repetitions < n_repetitions:
     x = random.random()
     if x <= p_computer:
          prob_comp += 1
     repetitions += 1
    print ("{0} % chance of getting virus on {1}".format(round(prob_comp/100.0, 2), computer_name))

for key in virus_probabilities:
     check_probability(key, 1000)

当我从控制台运行该文件时,我得到:

mabe@ubuntu:~/Desktop $ python test_2.py
2.49 % chance of getting virus on CompB
2.6 % chance of getting virus on CompC
5.07 % chance of getting virus on CompA
1.38 % chance of getting virus on CompBE
1.16 % chance of getting virus on CompBD
1.18 % chance of getting virus on CompCD
1.36 % chance of getting virus on CompCE

关于python - 计算条件概率 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34666035/

相关文章:

python - 属性错误 : 'decimal.Decimal' object has no attribute 'decode'

Python 正则表达式 - 提取每个表格单元格内容

python - scipy:如何使用 weibull_min.pdf?

javascript - 根据不同的概率获取数组的随机项?

r - 在 R 中创建具有给定概率的随机条目的矩阵

python - Django:使用动态字段加载表单

python - 内存中图像到 Zip 文件

python - ` d3 = {**d1, **d2}` 和 `d4 = dict(**d1, **d2)` 之间的区别?

testing - 根据发现的错误数量预测错误总数

C "Battleship"程序在 10k+ 次迭代后的非统计输出