from numpy import pi, exp, power, dot, rank
from numpy.linalg import inv, det

def mvnd(x, mu, S):
    """
    Calculate multivariate normal distribution of vector X, given mu (mean of
    elements in vector X) and S (covariance matrix).

    Based on the following formula:
    http://upload.wikimedia.org/math/a/0/a/a0ad9db46854c4a616ce6959095cf21d.png
    """
    return exp((2 * pi) ** rank(x)) * power(det(S), -.5) \
            * exp(-.5 * dot(dot((x - mu).T, inv(S)), (x - mu)))

#mean = [0,0]
#cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis
#
#import matplotlib.pyplot as plt
#import numpy as np
#x,y = np.random.multivariate_normal(mean,cov,5000).T
##mvnd(x, mean, cov)
#plt.plot(x,y,'x'); plt.axis('equal'); plt.show()

