Skip to content

Instantly share code, notes, and snippets.

@mathandy
Created April 20, 2020 03:44
Show Gist options
  • Save mathandy/dde71d4ae5870ac67164df8002ac2429 to your computer and use it in GitHub Desktop.
Save mathandy/dde71d4ae5870ac67164df8002ac2429 to your computer and use it in GitHub Desktop.
# probably about right
def variance(samples):
mean = sum(samples) / len(samples)
return sum((x - mean)**2 for x in samples) / len(samples)
# probably too short
def var(s):
m = sum(s) / len(s)
return sum((x - m)**2 for x in s) / len(s)
# probably too long
def compute_variance_of_samples(list_of_samples):
mean_of_list_of_samples = sum(list_of_samples) / len(list_of_samples)
return sum((x - mean_of_list_of_samples)**2
for x in list_of_samples) / len(list_of_samples)
# with nice documentation
# Note: this function may be a bit too simple to include such verbose
# documentation for, that said, it doesn't hurt
def variance(samples):
"""Compute the (uncorrected) sample variance of `samples`.
Args:
samples (iterable): a 1-d iterable of values to compute the
variance of.
Returns:
The standard deviation.
"""
mean = sum(samples) / len(samples)
return sum((x - mean)**2 for x in samples) / len(samples)
if __name__ == '__main__':
import numpy as np
l = np.random.rand(100)
print(l.var())
print(variance(l))
print(compute_variance_of_samples(l))
print(var(l))
print("Remember to check the undocumented version of `variance` too.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment