Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the inverse of the normal cumulative distribution function in python?

How do I calculate the inverse of the cumulative distribution function (CDF) of the normal distribution in Python?

Which library should I use? Possibly scipy?

like image 222
Yueyoum Avatar asked Dec 17 '13 05:12

Yueyoum


People also ask

How do you find the inverse of a cumulative normal distribution?

x = norminv( p , mu ) returns the inverse of the normal cdf with mean mu and the unit standard deviation, evaluated at the probability values in p . x = norminv( p , mu , sigma ) returns the inverse of the normal cdf with mean mu and standard deviation sigma , evaluated at the probability values in p .

What is CDF function in Python?

A cumulative distribution function (CDF) tells us the probability that a random variable takes on a value less than or equal to some value. This tutorial explains how to calculate and plot values for the normal CDF in Python.


2 Answers

NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy, you can compute this with the ppf method of the scipy.stats.norm object. The acronym ppf stands for percent point function, which is another name for the quantile function.

In [20]: from scipy.stats import norm  In [21]: norm.ppf(0.95) Out[21]: 1.6448536269514722 

Check that it is the inverse of the CDF:

In [34]: norm.cdf(norm.ppf(0.95)) Out[34]: 0.94999999999999996 

By default, norm.ppf uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc and scale arguments, respectively.

In [35]: norm.ppf(0.95, loc=10, scale=2) Out[35]: 13.289707253902945 

If you look at the source code for scipy.stats.norm, you'll find that the ppf method ultimately calls scipy.special.ndtri. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:

In [43]: from scipy.special import ndtri  In [44]: ndtri(0.95) Out[44]: 1.6448536269514722 
like image 56
Warren Weckesser Avatar answered Sep 18 '22 14:09

Warren Weckesser


Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the inverse cumulative distribution function (inv_cdf - inverse of the cdf), also known as the quantile function or the percent-point function for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist  NormalDist(mu=10, sigma=2).inv_cdf(0.95) # 13.289707253902943 

Which can be simplified for the standard normal distribution (mu = 0 and sigma = 1):

NormalDist().inv_cdf(0.95) # 1.6448536269514715 
like image 20
Xavier Guihot Avatar answered Sep 22 '22 14:09

Xavier Guihot