手動計算標準差
在影片中,我們談到離散程度的度量,並指出標準差是最常用的指標。熟悉這個概念非常重要,因為面試官很可能在流程一開始,就透過程式作業或概念性問題考你這一題。
在這裡,你將透過「手動計算標準差」來模擬這個情境,也就是不使用像 std() 這類現成函式來得到結果。
本練習屬於課程
用 Python 練習統計面試題
練習說明
- 不使用
mean()函式,計算已為你定義好的nums串列的平均數。 - 使用你算出的
variance值搭配math.sqrt()函式取得標準差,並印出結果。 - 透過前面提到的
np.std()函式印出實際的標準差,檢查你的作答。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a sample list
import math
nums = [1, 2, 3, 4, 5]
# Compute the mean of the list
mean = ____
# Compute the variance and print the std of the list
variance = sum(pow(x - mean, 2) for x in nums) / len(nums)
std = ____
print(____)
# Compute and print the actual result from numpy
real_std = np.array(____).std()
print(____)