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

前端 未结 7 822
醉酒成梦
醉酒成梦 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条回答
  • 2020-12-29 05:22

    The correct answer is to use one of the packages like NumPy, but if you want to roll your own, and you want to do incrementally, there is a good algorithm that has higher accuracy. See this link https://www.johndcook.com/blog/standard_deviation/

    I ported my perl implementation to Python. Please point out issues in the comments.

    Mklast = 0
    Mk = 0
    Sk = 0
    k  = 0 
    
    for xi in results:
      k = k +1
      Mk = Mklast + (xi - Mklast) / k
      Sk = Sk + (xi - Mklast) * ( xi - Mk)
      Mklast = Mk
    
    var = Sk / (k -1)
    print var
    

    Answer is

    >>> print var
    32.0248491784
    
    0 讨论(0)
提交回复
热议问题