# 在 Python 中計算方差

Lakshay Kapoor 2023年1月30日

## 在 Python 中使用統計模組的 `variance()` 函式計算方差

`variance()` 函式是 Python 統計模組的函式之一。該模組用於提供對數值資料執行統計操作（如均值、中位數、標準差等）的函式。

``````import statistics

list = [12, 14, 10, 6, 23, 31]
print("List : " + str(list))

var = statistics.variance(list)
print("Variance of the given list: " + str(var))
``````

``````List : [12, 14, 10, 6, 23, 31]
Variance of the given list: 86
``````

## 在 Python 中使用 NumPy 庫的 `var()` 函式計算方差

NumPy 庫的 `var()` 函式還可以計算給定陣列列表中元素的方差。

``````import numpy as np

arr = [12, 43, 24, 17, 32]

print("Array : ", arr)
print("Variance of array : ", np.var(arr))
``````

``````Array :  [12, 43, 24, 17, 32]
Variance of array :  121.04
``````

## 在 Python 中使用 `sum()` 函式和列表推導計算方差

`sum()` 函式總結了一個可迭代物件的所有元素，如列表、元組等。

`sum()` 函式和列表推導可以幫助計算列表的方差。

``````list = [12, 43, 24, 17, 32]
average = sum(list) / len(list)
var = sum((x - average) ** 2 for x in list) / len(list)
print(var)
``````

``````121.04
``````

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.