如何用python计算输出的平均值、模式、方差、标准差等?

2024-10-01 04:45:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的基于概率的游戏,每天我们掷硬币,如果我们得到正面,我们赢,我们得到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 -十九 -十九 -十九 -十九 -十九 20 -十九 20 -十九 20 -十九 20 20 -十九 -十九 20 20 -十九 -十九 -十九 20 20 20 -十九 -十九 -十九 20 20个

这个输出正是我所期望的。我想找到输出和其他描述性统计数据的总和,如平均值、模式、中位数、标准差、置信区间等。我必须将这些数据复制并粘贴到excel中进行数据分析。我希望有一种方法可以很容易地用python快速地完成这项工作。在


Tags: ingame游戏forgetreturnifrange
3条回答

你在问如何。最直接可用的是以统计信息库的形式构建到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]

使用scipy stats模块并使用modal作为模式,使用scipy.stats.mstats.median_cihs作为中值,使用{}作为平均值。您还可以使用statistics模块并使用mean()median()和{}函数。在

是的,有:安装numpy和scipy。{{cd2>{cd2>{cd3}使用。在

Scipy还包含scipy.stats模块,该模块提供各种常见的显著性测试。在

相关问题 更多 >