Python calculates mean variance standard deviation

Project github address: bitcarmanlee easy-algorithm-interview-and-practice
welcome everyone to star, leave a message, and learn and progress together

1. Calculate the mean

import numpy as np

a = [5, 6, 16, 9]
print(np.mean(a))

final result

9.0

np.mean method can find the mean

2. Calculate the variance

var = np.var(a)
print(var)

Output result

18.5

If we simulate the process of calculating variance

var2 = [math.pow(x-np.mean(a), 2) for x in a]
print(np.mean(var2))

Output result

18.5

np.var calculates the overall variance, if you want to calculate the sample variance, that is, the denominator of the divisor is N-1, you can specify the ddof parameter

sample_var = np.var(a, ddof=1)
print(sample_var)

The output result is

24.666666666666668

3. Calculate the standard deviation

std = np.std(a)
std2 = np.std(a, ddof=1)
print(std)
print(std2)

The std function calculates the overall standard deviation. Like the var function, if ddof=1 is specified, the sample standard deviation is calculated.

Guess you like

Origin blog.csdn.net/bitcarmanlee/article/details/110471328