Search code examples
pythonpython-3.xintegralprobability-density

Is there a shortcut to calculate integrals for different types of probability density functions?


In a case like this,

from scipy.integrate import quad
import numpy as np

exponential_distribution = lambda x, lam: lam*np.exp(-lam*x)
result = quad(exponential_distribution, 0.25, 0.75, args=0.1)[0]

I'm imagining something like that

from magic_library import integrate_distribution

result = integrate_distribution(distribution='exponential', parameter=[0.1], a=0.25, b=0.75)

Solution

  • You can use the already defined distributions in scipy.stats for most of you purposes. For the case of an exponential distribution, you can create an instance of the distribution with frozen parameters (i.e. lam). That object has methods you can call to manage the integration such as cdf, the cumulative distribution function for the exponential distribution.

    Integration from x0 to x1 is then just the difference between the values of the cdf at those two points. For the expon class, the scale parameter is equivalent to 1/lam in your example function.

    from scipy import stats
    
    lam = 0.1
    exponential_distribution = stats.expon(scale=1/lam)
    
    exponential_distribution.cdf(0.75) - exponential_distribution.cdf(0.25)
    # returns:
    0.04756642569977977
    

    We can compare this to the method you used for integration and see it gives the same answer.

    from scipy.integrate import quad
    import numpy as np
    
    exponential_distribution = lambda x, lam: lam*np.exp(-lam*x)
    quad(exponential_distribution, 0.25, 0.75, args=0.1)[0]
    # returns:
    0.04756642569977978