根据累积分布函数计算分布中值



我有一个定义如下的密度函数:

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

我矢量化了密度函数:

f = np.vectorize(f)

然后我定义了X阵列

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

最后,CDF:

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

现在我想计算

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

我在这里写的对吗?

如果函数是已知的先验,我会使用它的分析积分。对于中值计算,我会使用类似平分法的方法(因为函数不平滑(

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)

最新更新