使用 Sympy 创建和绘制连续均匀分布的 PDF 和 CDF

问题描述

使用 Sympy:

如何定义连续均匀分布的 PDF 和 CDF 并生成 pdf 和 cdf 的图?

解决方法

  1. 这是一个很好的方法:

     # import libaries
     import sympy as sp
     from sympy.stats import Uniform,density,cdf
    
     # define necessary symbols
     a,b,x = sp.symbols('a b x')
    
     # define the pdf of the cont uniform distribution
     f = 1 / (b - a)
     cont_uniform_pdf = sp.Piecewise((f,((b >= x) & (a <= x))),(0,True))
    
     # define the cdf of the cont uniform distribution
     F = (x - a) / (b - a)
     cont_uniform_cdf = sp.Piecewise((0,a > x),(F,x<b),(1,True))
    
     # choose the a and b parameter of the distribution
     a_value = 1
     b_value = 5
    
     # use .subs() to fill in the chosen parameters in the pdf and cdf
     pdf_plot = sp.plot(
         cont_uniform_pdf.subs({'a': a_value,'b': b_value}),title=f'pdf of $U \sim ({a_value},{b_value})$',xlim=(0,6),size=(5.,2.),show=False,)
    
     cdf_plot = sp.plot(
         cont_uniform_cdf.subs({'a': a_value,title=f'cdf of $U \sim ({a_value},)
    
     # use a plotgrid to display both plots below eachother
     plot_grid = sp.plotting.PlotGrid(2,1,pdf_plot,cdf_plot,show=False)
     plot_grid.show()
    

    sympy plot continuous uniform distribution


  1. 或者,您可以使用 sympy 的 stats 部分创建连续分布。这导致相同的情节:

     # create the uniform distribution
     X = Uniform('x',a,b)
    
     # use density() to create the pdf and subs to fill in the chosen parameter values for a and b
     pdf_plot = sp.plot(
         (density(X)(x)).subs({'a': a_value,)
    
     # use cdf() to create the pdf and subs to fill in the chosen parameter values for a and b
     cdf_plot = sp.plot(
         (cdf(X)(x)).subs({'a': a_value,ylabel='F(x)',show=False)
     plot_grid.show()
    

  1. 最后,您还可以决定使用自己喜欢的绘图库。在这种情况下,使用 sp.lambdify() 将 sympy 类或函数转换为常规 python 函数:

    import holoviews as hv
    hv.extension('bokeh')
    
    # use sp.lambdify() to convert your sympy function to a regular python function
    fx = sp.lambdify(x,cont_uniform_pdf.subs({a: a_value,b: b_value}))
    Fx = sp.lambdify(x,cont_uniform_cdf.subs({a: a_value,b: b_value}))
    
    x_values = np.linspace(0,6,num=1000)
    
    # create plots in this case using holoviews as the plotting library
    pdf_plot = hv.Curve(zip(x_values,fx(x_values)),label='cont uniform PDF')
    cdf_plot = hv.Curve(zip(x_values,Fx(x_values)),label='cont uniform CDF')
    
    pdf_plot + cdf_plot
    

plotting continuous uniform using holoviews

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...