Ticket #7197: trac_7197_basic_stats_part5.patch

File trac_7197_basic_stats_part5.patch, 1.9 KB (added by amhou, 12 years ago)
  • sage/stats/all.py

    # HG changeset patch
    # User Andrew Hou <amhou@uw.edu>
    # Date 1258052851 28800
    # Node ID c7e86a36719bc08e47f716ca04c85d825e7e04d0
    # Parent  bbf5f88f04e9bd4aefd7d16e09b72b2328d6ce96
    Moving average function added
    
    diff -r bbf5f88f04e9 -r c7e86a36719b sage/stats/all.py
    a b  
    11from r import (ttest)
    2 from basic_stats import (mean, mode, std, variance, median)
     2from basic_stats import (mean, mode, std, variance, median, moving_average)
    33
    44import hmm.all as hmm
    55
  • sage/stats/basic_stats.py

    diff -r bbf5f88f04e9 -r c7e86a36719b sage/stats/basic_stats.py
    a b  
    286286        upper = values[len(values)/2]
    287287        return (lower + upper)/ZZ(2)
    288288
     289def moving_average(v, bins=1):
     290    """
     291    Provides the moving average of a list
    289292
     293    The moving average of a list is often used to smooth out noisy
     294    data. Given a selected number of bins, the original list will be
     295    cut up into that number of bins. Then, the mean of each bin is
     296    calculated, and appended into a new list.
     297
     298    If 'v' is empty, we define the entries of the moving average to be NaN.
     299
     300    INPUT:
     301 
     302        - v -- a list
     303
     304        - bins -- number of bins, default set to 1
     305
     306    OUTPUT:
     307
     308        - a list
     309 
     310    EXAMPLES::
     311
     312        sage: moving_average([1..10],4)
     313        [3/2, 4, 13/2, 9]
     314        sage: moving_average([])
     315        [NaN]
     316        sage: moving_average([pi, e, I, sqrt(2), 3/5], 2)
     317        [1/2*pi + 1/2*e, 1/3*sqrt(2) + 1/3*I + 1/5]
     318                                                                                    """
     319    x = []   
     320    j = 0
     321    bin_size = len(v)/bins
     322
     323    for i in range(bins):
     324        tmp = []
     325        for k in range(j,j+bin_size):
     326            tmp.append(v[k])
     327        x.append(mean(tmp))
     328        j += bin_size
     329    return x