iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
♾️
Calculating Mean and Variance Blazing Fast with Recurrence Relations
Preface
I was planning to build an API to calculate the mean and variance from database information. At that time, I realized that while the computational complexity of mean and variance is O(n), it could be made faster by caching the current mean and variance, so I performed the calculations.
However, since the n for the application I'm considering is not that large, I decided to just use database functions for better maintainability, and the idea was scrapped.
This article is a tribute to commemorate that thought.
Mean
Variance
- Note that it is solved using the variance formula
- For
, input the mean calculated previously\bar{x}_n
Experimenting with Python to see from what point it becomes slow
Code used
import random
import time
def calc_without_cache(x: list):
mean_n = (1/len(x)) * sum(x)
var_n = (1/len(x)) * sum([ (x_ - mean_n)**2 for x_ in x ])
if __name__ == '__main__':
for i in range(1,11):
print("+---------------------------+")
print("n = 10^{}".format(i))
x = [random.randint(0, 100) for _ in range(10**i)]
start = time.time()
calc_without_cache(x)
end = time.time()
print(f'Without cache: {round(end - start, 4)}')
Experimental results
- Calculation starts getting slow from around
10^6
+---------------------------+
n = 10^1
Without cache: 0.0
+---------------------------+
n = 10^2
Without cache: 0.0
+---------------------------+
n = 10^3
Without cache: 0.0001
+---------------------------+
n = 10^4
Without cache: 0.0009
+---------------------------+
n = 10^5
Without cache: 0.0069
+---------------------------+
n = 10^6
Without cache: 0.0698
+---------------------------+
n = 10^7
Without cache: 0.6968
+---------------------------+
n = 10^8
Without cache: 8.5611
+---------------------------+
...
Discussion