January 23, 2012

Log-normal Distributions: reconciling MATLAB and Python

MATLAB users are familiar with the log-normal functions for calculating a pdf/cdf at a given point. The MATLAB syntax is lognpdf(x,mean,sigma) and logncdf(x,mean,sigma) for the pdf and cdf values respectively. Python users will find that the lognorm.pdf and lognorm.cdf functions in the scipy.stats library follow a different set of conventions, and consequently will give different outputs for the same pair of inputs (Python's can be transformed to get the same outputs as MATLAB). Here I have some simple values that generate pdf/cdf values for scalar inputs following the MATLAB conventions.

Information relating how to transform the MATLAB inputs so that Python and MATLAB give the same output are given in the lognorm.pdf/cdf doc-strings.

First for the pdf function...

import scipy as sp
def lognpdf(x,mean,sig):
    if x<0 or not sp.isfinite(x):
        pdf = 0
        a   = 1./(x*sig*sp.sqrt(2*sp.pi))
        pdf =  a*sp.exp(-(sp.log(x)-mean)**2/(2.*sig**2)) 
    return pdf

and then the cdf function.

import scipy as sp
import math
def logncdf(x,mean,sig):
    if x<0:
        cdf  = 0.
    elif sp.isposinf(x):
        cdf  = 1.
        z    = (sp.log(x)-mean)/float(sig)
        cdf  = .5*(math.erfc(-z/sp.sqrt(2)))
    return cdf

You'll find that these give the same results as MATLAB.

No comments:

Post a Comment