python - 如何计算python输出的均值、众数、方差、标准差等?

标签 python random simulation python-3.5 montecarlo

我有一个基于概率的简单游戏,每天我们抛硬币,如果我们正面朝上,我们就赢,我们得到 20 美元,如果我们抛硬币,我们反面朝上,那么我们输掉 19 美元,最后每月(28 天)的一天,我们会看到我们损失了多少或赚了多少。

def coin_tossing_game():
    random_numbers = [random.randint(0, 1) for x in range(500)] #generate 500 random numbers
    for x in random_numbers:
        if x == 0: #if we get heads
            return 20 #we win $20
        elif x == 1: #if we get tails
            return -19 #we lose $19


for a in range(1, 28): #for each day of the month
    print(coin_tossing_game())

这将返回输出 20 20 -19 -19 -19 -19 -19 20 -19 20 -19 20 -19 20 20 -19 -19 20 20 -19 -19 -19 20 20 20 -19 -19 -19 20 20

这个输出正是我所期望的。我想找到输出和其他描述性统计数据的总和,如均值、众数、中位数、标准差、置信区间等。我不得不将这些数据复制并粘贴到 excel 中以进行此数据分析。我希望有一种方法可以在 python 中快速轻松地完成此操作。

最佳答案

你在问如何。最直接可用的是以 statistics 库的形式构建到 Python 中。但同样,你似乎想知道如何做到这一点。下面的代码展示了我近 50 年来一直没有必要去做的基础知识。

首先,修改您的代码,使其捕获向量中的样本。在我的代码中,它称为 sample

代码的第一部分只是简单地练习了 Python 库。那里没有汗水。

代码的第二部分展示了如何累加样本中值的总和,以及它们与平均值的偏差的平方和。我留给您来解决如何在这些统计数据的通常假设下计算样本方差、样本标准差和置信区间。对样本进行排序和重命名后,我计算了最大值和最小值(对于某些分布的估计很有用)。最后,我从排序后的样本中计算出中位数。我把中位数的计算留给你。

import random

def coin_tossing_game():
    random_numbers = [random.randint(0, 1) for x in range(500)] #generate 500 random numbers
    for x in random_numbers:
        if x == 0: #if we get heads
            return 20 #we win $20
        elif x == 1: #if we get tails
            return -19 #we lose $19

sample = []
for a in range(1, 28): #for each day of the month
    #~ print(coin_tossing_game())
    sample.append(coin_tossing_game())

## the easy way

import statistics

print (statistics.mean(sample))
print (statistics.median(sample))
print (statistics.mode(sample))
print (statistics.stdev(sample))
print (statistics.variance(sample))

## the hard way

sample.sort()
orderedSample = sample
N = len(sample)
minSample = orderedSample[0]
maxSample = orderedSample[-1]
sumX = 0
for x in sample:
    sumX += x
mean = sumX / N

sumDeviates2 = 0
for x in sample:
    sumDeviates2 += ( x-mean )**2

k = N//2
if N%2==0:
    mode = 0.5* (orderedSample[k]+orderedSample[k-1])
else:
    mode = orderedSample[k]

关于python - 如何计算python输出的均值、众数、方差、标准差等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42177007/

相关文章:

python - 有没有办法让我们在discord.py中一次获取多个命令的剩余冷却时间?

Java:限制在小区域内的基于泊松的点过程

data-visualization - Python 复制 Java Web 应用程序?

javascript - 输入类型="file"javascript点击模拟

python - Django 根据值从查询集中获取不同的结果

python - 无法在 MacOS 上安装 pyicu

php - 发送python html邮件看不到邮件的内容

JavaScript 有偏见的结果?

random - 生成具有已知均值和方差的随机数

php - 避免在 Kohana 3 的 MySQL 查询中使用 RAND()