基本统计值计算,使用random库生成随机数100个[1,100]的整数,同时借用math库进行了简单的计算,对生成的一组随机数求平均值,标准差,中位数,离差,离差方,总体方差,样本方差,样本标准差。
计算公式如下:
程序代码如下:
from math import *
from random import *
def getNum():#样本
nums=[]
for s in range(100):
nums.append(randint(1,100))
return nums
def mean(numbers):#平均值
a=sum(getNum())
return a/len(numbers)
def licha(numbers,mean):#离差
licha1=[]
for num in numbers:
x=num-mean
x=round(x,3)
licha1.append(x)
return licha1
def lichaf(numb):#离差方
lichaf1=[]
for num in numb:
y=num*num
y=round(y,2)
lichaf1.append(y)
return lichaf1
def dev(numbers,mean):#总体方差
sdev=0.0
for num in numbers:
sdev=sdev+(num-mean)**2
return sqrt(sdev/len(numbers))
def bzf(per):#总体标准差
return sqrt(per)
def ybdev(numbers,mean):#样本方差
sdex=0.0
for num in numbers:
sdex=sdex+(num-mean)**2
return sqrt(sdex/(len(numbers)-1))
def ybbzf(der):#样本标准差
return sqrt(der)
n=getNum()
print("样本:{}".format(n))
m=mean(n)
print("平均值:{}".format(m))
h=licha(n,m)
print("离差:{}".format(h))
k=lichaf(h)
print("离差方:{}".format(k))
f=dev(n,m)
print("总体方差:{:.2f}".format(f))
z1=bzf(f)
print("总体标准差:{:.2f}".format(z1))
p=ybdev(n,m)
print("样本方差:{:.2f}".format(p))
z=ybbzf(p)
print("样本标准差:{:.2f}".format(z))
程序运行结果如下: