import numpy as np
Not a bad idea to solve this one in pieces/two functions.
def mean(x):
= 0.0
s = np.size(x)
N for n in range(N):
+= x[n]
s return s / N
def var(x):
= 0.0
s = np.size(x)
N = mean(x)
m = 1 / N # minimizing division is a good idea, even if ineffective here
invN for n in range(N):
= x[n] - m
d += d * d # multiplication is faster than powers
s return s * invN
= np.random.default_rng()
rng = rng.normal(size = 100)
x np.isclose(np.var(x), var(x))
True