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