1

I need to use probability and cumulative density functions in a Python application I'm programming. SciPy offers both, but it seems too hefty of a dependency for just those two functions. PDF seems easy enough to implement without SciPy. (From the docs:)

The probability density function for norm is:

norm.pdf(x) = exp(-x**2/2)/sqrt(2*pi)

Is there a way to get CDF as well without using SciPy?

Shep
  • 7,990
  • 8
  • 49
  • 71
Theron Luhn
  • 3,974
  • 4
  • 37
  • 49

2 Answers2

4

See this post:

from math import *
def erfcc(x):
    """Complementary error function."""
    z = abs(x)
    t = 1. / (1. + 0.5*z)
    r = t * exp(-z*z-1.26551223+t*(1.00002368+t*(.37409196+
        t*(.09678418+t*(-.18628806+t*(.27886807+
        t*(-1.13520398+t*(1.48851587+t*(-.82215223+
        t*.17087277)))))))))
    if (x >= 0.):
        return r
    else:
        return 2. - r

def ncdf(x):
    return 1. - 0.5*erfcc(x/(2**0.5))
Community
  • 1
  • 1
Charles Menguy
  • 40,830
  • 17
  • 95
  • 117
3

You're looking for the "error function", see the math module. It has no closed form representation in terms of elementary functions.

Note that math.erf(x) was introduced in python 2.7. If you're using an earlier version, you'll have to make due with an approximation.

Community
  • 1
  • 1
Shep
  • 7,990
  • 8
  • 49
  • 71