Calculating Distribution Median from Cumulative Distribution Function

Viewed 259

I have a density function defined as below:

def f(x):
   if 0<=x<=1:
      return 0.5
   elif 1<x<=3:
      return 0.25
   else:
      return 0.0

I vectorized the density function:

f = np.vectorize(f)

Then I have defined the X array

X = np.arange(-10,10,0.001)

Finally, the CDF:

def CDF(x):
   return quad(f, -np.inf,x)
CDF = np.vectorize(CDF)
CDF_calculated,err=CDF(X)

Now I want to calculate the

median = np.round(X[np.where(CDF_calculated==0.5)][0])

Is what I wrote here correct?

1 Answers

If the function is a priory known, I would use its analytical integral. For median computation, I would use something like bisection method (as the function is not smooth)

import numpy as np
from scipy.optimize import bisect

def f(x):
   if 0<=x<=1:
      return 0.5
   elif 1<x<=3:
      return 0.25
   else:
      return 0.0

  
def cdf(x):
    if 0<=x<=1:
        return 0.5*x
    elif 1<x<=3:
        return 0.5 + 0.25*(x-1)
    elif x<0:
        return 0.0
    else:
        return 1


f = np.vectorize(f)
cdf = np.vectorize(cdf)

fbisect = lambda v: cdf(v) - 0.5

median = bisect(fbisect,0,3)
print(median)
Related