Changeset 2015


Ignore:
Timestamp:
Nov 10, 2005, 1:22:03 PM (18 years ago)
Author:
ole
Message:

Added basic statistical operations

File:
1 edited

Legend:

Unmodified
Added
Removed
  • inundation/utilities/numerical_tools.py

    r1910 r2015  
    33
    44"""
     5
     6import Numeric
     7
     8def mean(x):
     9    """Mean value of a vector
     10    """
     11    return(float(Numeric.sum(x))/len(x))
     12
     13
     14def cov(x, y=None):
     15    """Covariance of vectors x and y.
     16
     17    If y is None: return cov(x, x)
     18    """
     19   
     20    if y is None:
     21        y = x
     22
     23    assert(len(x)==len(y))
     24    N = len(x)
     25 
     26    cx = x - mean(x) 
     27    cy = y - mean(y) 
     28
     29    p = Numeric.innerproduct(cx,cy)/N
     30    return(p)
     31
     32
     33def err(x, y=0, n=2):
     34    """Relative error of ||x-y|| to ||y||
     35       n = 2:    Two norm
     36       n = None: Max norm
     37
     38       If denominator evaluates to zero, absolute error is returned
     39    """
     40
     41    if n == 2:
     42        err = norm(x-y)
     43        try:
     44            err = err/norm(y)
     45        except:
     46            pass
     47
     48    else:
     49        err = max(abs(x-y))
     50        try:
     51            err = err/max(abs(y))   
     52        except:
     53            pass
     54         
     55    return err
     56 
     57
     58def norm(x):
     59    """2-norm of x
     60    """
     61 
     62    y = Numeric.ravel(x)
     63    p = Numeric.sqrt(Numeric.innerproduct(y,y))
     64    return p
     65   
     66 
     67def corr(x, y=None):
     68    """Correlation of x and y
     69    If y is None return autocorrelation of x
     70    """
     71
     72    from math import sqrt
     73    if y is None:
     74        y = x
     75
     76    varx = cov(x)
     77    vary = cov(y)
     78
     79    if varx == 0 or vary == 0:
     80        C = 0
     81    else: 
     82        C = cov(x,y)/sqrt(varx * vary)   
     83
     84    return(C)
     85
    586
    687       
     
    34115            return array(A).astype(typecode)
    35116
     117
     118
Note: See TracChangeset for help on using the changeset viewer.