5

How can I calculate the cumulative distribution function of a normal distribution in python without using scipy?

I'm specifically referring to this function:

from scipy.stats import norm
norm.cdf(1.96)

I have a Django app running on Heroku and getting scipy up and running on Heroku is quite a pain. Since I only need this one function from scipy, I'm hoping I can use an alternative. I'm already using numpy and pandas, but I can't find the function in there. Are there any alternative packages I can use or even implement it myself?

2

2 Answers 2

9

Just use math.erf:

import math

def normal_cdf(x):
    "cdf for standard normal"
    q = math.erf(x / math.sqrt(2.0))
    return (1.0 + q) / 2.0

Edit to show comparison with scipy:

scipy.stats.norm.cdf(1.96)
# 0.9750021048517795

normal_cdf(1.96)
# 0.9750021048517796
Sign up to request clarification or add additional context in comments.

Comments

3

This question seems to be a duplicate of How to calculate cumulative normal distribution in Python where there are many alternatives to scipy listed.

I wanted to highlight the answer of Xavier Guihot https://stackoverflow.com/users/9297144/xavier-guihot which shows that from python3.8 the normal is now a built in:

from statistics import NormalDist

NormalDist(mu=0, sigma=1).cdf(1.96)
# 0.9750021048517796

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.