How can I calculate the variance of a list in python?

前端 未结 7 852
醉酒成梦
醉酒成梦 2020-12-29 04:58

If I have a list like this:

results=[-14.82381293, -0.29423447, -13.56067979, -1.6288903, -0.31632439,
          0.53459687, -1.34069996, -1.61042692, -4.032         


        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 05:12

    Numpy is indeed the most elegant and fast way to do it.

    I think the actual question was about how to access the individual elements of a list to do such a calculation yourself, so below an example:

    results=[-14.82381293, -0.29423447, -13.56067979, -1.6288903, -0.31632439,
          0.53459687, -1.34069996, -1.61042692, -4.03220519, -0.24332097]
    
    import numpy as np
    print 'numpy variance: ', np.var(results)
    
    
    # without numpy by hand  
    
    # there are two ways of calculating the variance 
    #   - 1. direct as central 2nd order moment (https://en.wikipedia.org/wiki/Moment_(mathematics))divided by the length of the vector
    #   - 2. "mean of square minus square of mean" (see https://en.wikipedia.org/wiki/Variance)
    
    # calculate mean
    n= len(results)
    sum=0
    for i in range(n):
        sum = sum+ results[i]
    
    
    mean=sum/n
    print 'mean: ', mean
    
    #  calculate the central moment
    sum2=0
    for i in range(n):
        sum2=sum2+ (results[i]-mean)**2
    
    myvar1=sum2/n
    print "my variance1: ", myvar1
    
    # calculate the mean of square minus square of mean
    sum3=0
    for i in range(n):
        sum3=sum3+ results[i]**2
    
    myvar2 = sum3/n - mean**2
    print "my variance2: ", myvar2
    

    gives you:

    numpy variance:  28.8223642606
    mean:  -3.731599805
    my variance1:  28.8223642606
    my variance2:  28.8223642606
    

提交回复
热议问题