speeds = [86,87,88,86,87,85,86]
# Calculate the mean of the values in your list
mean_speeds = sum(speeds) / len(speeds)
# Calculate the variance of the values in your list
# This is 1/N * sum((x - mean(X))^2)
var_speeds = sum((x - mean_speeds) ** 2 for x in speeds) / len(speeds)
# Take the square root of variance to get standard deviation
sd_speeds = var_speeds ** 0.5
>>> sd_speeds
0.9035079029052513
The problem in your code is the reuse of array and return in the middle of the loop
def get_std_dev(array):
# get mu
mean = get_mean(array) <-- this is 86.4
# (x[i] - mu)**2
for i in array:
array = (i - mean) ** 2 <-- this is almost 0
return array <-- this is the value returned
Now let us look at the algorithm you are using. Note that there are two std deviation formulas that are commonly used. There are various arguments as to which one is correct.
sqrt(sum((x - mean)^2) / n)
or
sqrt(sum((x - mean)^2) / (n -1))
For big values of n, the first formula is used since the -1 is insignificant. The first formula can be reduced to
sqrt(sum(x^2) /n - mean^2)
So how would you do this in python?
def std_dev1(array):
n = len(array)
mean = sum(array) / n
sumsq = sum(v * v for v in array)
return (sumsq / n - mean * mean) ** 0.5
Hi,
I'm trying to learn Python, below is code I'm running, the first part is the one that I'm trying to calculate myself, the other ones are stdev from statistics and std form numpy, that I'm running for control.
from functools import reduce from numpy import std from statistics import stdev import math values = [448.0, 826.7, 313.6, 2212.0, 2771.3, 2240.0, 2021.95, 4039.0] mean = (reduce ( lambda x, y: x+ y, values))/len(values) std_math = sum((v - mean)**2 for v in values)/len(values) std_math = sqrt(std_math) print(std_math) print(std(values)) print(stdev(values))
Output: 1189.8444963884722 1189.8444963884724 1271.997271149785
My question is why stdev has such a dif value for the other two? Shouldn't all 3 have the same final value?
PS: for the mean I know I could just do sum( )/len( ), but I was practicing the reduce/lambda func.
Thanks!