在Python中不用包计算标准差?

q43xntqr  于 2023-01-22  发布在  Python
关注(0)|答案(5)|浏览(148)

我正在尝试弄清楚如何创建一个脚本来计算一个文件的标准差。作为一个例子,假设我用一个值的列表对一个csv进行了DLed。我想通过运行一个python程序来找到这些值的SD。我们在这里没有使用numpy!

f87krz0w

f87krz0w1#

如果允许使用标准库,

import math

xs = [0.5,0.7,0.3,0.2]     # values (must be floats!)
mean = sum(xs) / len(xs)   # mean
var  = sum(pow(x-mean,2) for x in xs) / len(xs)  # variance
std  = math.sqrt(var)  # standard deviation

如果不是,你需要手工近似sqrt。例如,你可以使用二进制搜索或Newton's Method。下面是wikipedia page的实现方法

i5desfxk

i5desfxk2#

在Python 3.4及更高版本中,有一个名为statistics的包,其中包含标准差(pstdev)和其他函数
下面是如何使用它的示例:

import statistics

data = [1, 1, 2.5, 6.5, 7.3, 8, 9.2]

print(statistics.pstdev(data))
# 3.2159043543498815
3bygqnnd

3bygqnnd3#

from math import sqrt
 n= [11, 8, 8, 3, 4, 4, 5, 6, 6, 7, 8] 

 mean =sum(n)/len(n)
 SUM= 0
 for i in n :
     SUM +=(i-mean)**2


 stdeV = sqrt(SUM/(len(n)-1)) 
 print(stdeV)
mwecs4sa

mwecs4sa4#

filename = "C:\Users\mmb0368\Desktop\input.txt"
file = open("C:\Users\mmb0368\Desktop\input.txt","rb")

n = file.readlines()

num_list = map(lambda n: n.rstrip("\n"), n)
num_list = [int(x) for x in num_list]
mean = sum(num_list)/len(num_list)
print mean, max(num_list), min(num_list)

for snDev in num_list:

    snDev = mean**(1.0/2)
print snDev
8wtpewkr

8wtpewkr5#

from math import sqrt

def getAverage(mylist):
    return sum(mylist)/len(mylist)

def getStandardDeviation(mylist):
    ls=[]
    for i in mylist:
        ls.append((i - getAverage(mylist))**2)
    return sqrt( sum(ls) / (len(mylist) - 1) )

mylist = [1,5,10]

getAverage(mylist=mylist)
# 5.333333333333333

getStandardDeviation(mylist=mylist)
# 4.509249752822894

相关问题