Saturday, February 21, 2015

py25. Gamma Distribution in Python

Like the Poisson and Exponential distribution, the Gamma distribution is also dependent on the exponential series.


Besides the calculation above, we can use the function scipy.stats.gamma.cdf

# ex25.py
from __future__ import print_function, division
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gamma
# shape, scale parameters
k,s = 7,2

def get_num(x,kv):
    xp = x/s
    coeff = np.exp(-xp)
    if kv == 0: return coeff
    cv = xp/np.arange(1,kv+1)
    return coeff*np.prod(cv)

def gamma_dis(x, calc):
    dis_calc = np.zeros(len(x))
    for i in range(len(x)):
        S = [get_num(x[i],kv) for kv in range(k)]
        dis_calc[i] = 1 - sum(S)
    dis_R = gamma.cdf(x, k, scale = s)
    if calc: return dis_calc
    else: return dis_R

main = ('Gamma Cumulative Distribution Function'
        '\nShape = 7, Scale = 2')
x = np.arange(40, step = .1)
plt.plot(x, gamma_dis(x,False),'r')
plt.xlabel('x')
plt.ylabel('P')
plt.title(main)
plt.plot(x, gamma_dis(x,True), 'b')
plt.show()

Output:

No comments:

Post a Comment