3 回答

TA貢獻1798條經(jīng)驗 獲得超7個贊
只需像這樣使用statisticspython 提供的模塊:
import statistics
import random
# creating sample data
lst = []
for x in range(0, 5):
n = random.randint(1, 10)
lst.append(n) # also don't add semicolons after lines of code, that's not proper formatting
# Prints standard deviation
print("Standard Deviation of sample is:", statistics.stdev(lst))
如果您不想使用內(nèi)置函數(shù),請嘗試:
# Find the mean
total = 0
for num in lst:
total += num
mean = total/len(lst)
# Subtract mean from each value and square
new_lst = []
new_sum = 0
for item in lst:
square_diff = (item - mean)**2
new_lst.append(square_diff)
# Find the average of all the values
new_lst_sum = 0
for item in new_lst:
new_lst_sum += item
# print results
standard_dev = float(new_lst_sum/len(new_lst))
print("Your standard deviation is:", standard_dev)
這代碼更繁重且效率更低,但您可以清楚地看到邏輯。

TA貢獻1776條經(jīng)驗 獲得超12個贊
您最新版本的代碼中的錯誤應該s /= len(ranList)-1是s /= len(ranList). 有幾件事需要考慮。首先,不要為測試隨機生成列表,而是使用硬編碼列表以便于驗證。其次,考慮在函數(shù)中創(chuàng)建第二個內(nèi)部列表,這樣您就不會破壞傳入的列表。
一個解決方案是
import math
def stDev(lst):
xbar = sum(lst)/len(lst)
mlst = [(v-xbar)**2 for v in lst]
s = sum(mlst)/len(mlst)
return math.sqrt(s)
test = [1, 7, 4, 1, 10]
result = stDev(test)
print(test, result)

TA貢獻1785條經(jīng)驗 獲得超4個贊
您應該檢查代碼中的兩個特定行。第一個是這樣的:
s /= sum(ranList)-1
為了計算標準偏差,您需要將總和除以 N-1。相反,您將它除以 sum-1。len(list)
建議使用返回列表長度的函數(shù)。
第二個是這樣的:
數(shù)學.sqrt(s)
標準差公式需要返回變量的平方根s
。實際上,該函數(shù)math.sqrt(float)
返回參數(shù)的根,但不會將最終結(jié)果放入?yún)?shù)中。因此,您還應該將返回值分配給s
.
添加回答
舉報