超几何分布的 PDF

超几何分布的 PDF

我希望绘制超几何分布的 pdf,并且我一直使用lua和 的结合pgfplots。但是,当我将密度函数与二项式系数公式一起使用时,会出现错误。

我怎样才能使这两个声明兼容?(有或没有 Lua;参见下面的代码)。提前谢谢!

\documentclass{article}
\usepackage[margin=1cm]{geometry} % just for this example
\usepackage{pgfplots}
\usepackage{fontspec,luacode,luatexbase}
\begin{luacode}
   -- 'mchoose' is patterned after the posting in http://stackoverflow.com/a/15302448.
   function mchoose( n, k )
     if (k == 0 or k == n) then
       return 1 
     else 
       return (n * mchoose(n - 1, k - 1)) / k 
     end
   end

   -- print an arbitrary length integer as formatted string
   function fwrite(z) 
      tex.sprint ( string.format("%.0f",z) )
   end

   -- the pdf used for the dist. in lua...
   -- hypergeometric pdf
   --   function hypergeo(n11, n1_, n_1, n)
   --       return math.exp(math.lbinom(n1_, n11) + math.lbinom(n-n1_, n_1-n11) - math.lbinom(n, n_1));
   --   end

\end{luacode}

\newcommand{\mchoose}[2]{%
    \directlua{fwrite ( mchoose ( 
               "\luatexluaescapestring{#1}",
               "\luatexluaescapestring{#2}" ) )
    }}


\begin{document}

\begin{tikzpicture}
\begin{axis}[
  no markers, domain=-1:10, samples=100,
  axis lines*=left, xlabel=$x$, ylabel=$f(x)$,
  every axis y label/.style={at=(current axis.above origin),anchor=south},
  every axis x label/.style={at=(current axis.right of origin),anchor=west},
  height=5cm, width=12cm,
  enlargelimits=false, clip=false, axis on top,
  ]


\pgfmathdeclarefunction{hyper}{4}{%
  \pgfmathparse{($\mchoose{#3}{#1}$)+($\mchoose{#4-#2}{#3-#1}$)-($\mchoose{#4}{#3}$)}%
% or?
%  \pgfmathparse{(mchoose{#3}{#1})+(mchoose{#4-#2}{#3-#1})-(mchoose{#4}{#3})}%
}

\addplot [very thick,cyan!50!black] {hyper(4, 10, 42, 16)};


\end{axis}
\end{tikzpicture}

\end{document}

答案1

该函数可以直接在 PGFPlots 中声明和评估,而无需 lua。

您可以使用以下函数声明二项式系数

declare function={binomcoeff(\n,\k)=\n!/(\k!*(\n-\k)!);}

然后在超几何分布概率质量函数的声明中使用它:

declare function={
    hypergeompmf(\N,\K,\n,\k)=binomcoeff(\K,\k)*binomcoeff(\N-\K, \n-\k)/binomcoeff(\N,\n);
}

\documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}[
    declare function={binomcoeff(\n,\k)=\n!/(\k!*(\n-\k)!);},
    declare function={
        hypergeompmf(\N,\K,\n,\k)=binomcoeff(\K,\k)*binomcoeff(\N-\K, \n-\k)/binomcoeff(\N,\n);
    }
]
\begin{axis}[
    samples at={0,...,20},
    ycomb,
    yticklabel style={
        /pgf/number format/fixed,
        /pgf/number format/fixed zerofill,
        /pgf/number format/precision=2
    },
    every axis legend/.append style={at={(0.5,1.1)}, anchor=south}
]
\addplot [mark=*, cyan] {hypergeompmf(80,25,20,x)}; \addlegendentry{$N=80, K=30, n=25$}
\end{axis}
\end{tikzpicture}
\end{document}

相关内容