[Tex/LaTex] declare function vs pgfmathdeclarefunction


I would like to create an image to compare the difference between the gaussian distribution and the Student's t distribution for small n values.

From my searches in SE I took the definition of the gaussian pdf from Bell Curve/Gaussian Function/Normal Distribution in TikZ/PGF and the example to plot the t distribution from Student t-distribution with TikZ. In the latter, the functions "gamma" and "student" are declared locally. I intend to use this function a few times, so I would like to declare the functions globally. As you can see in the MWE, I tried to do this by using the functions from the tixzpicture declaration and copied them with minor modifications (variables) into the \pgfmathdeclarefunction command copied from the gaussian distribution.

However, if I comile the MWE using the tikzpicture declaration everything is fine, if I uncomment the functions in the preamble and commend the tikzpicture declaration I get no image at all.

My code:



%   \pgfmathparse{2.506628274631*sqrt(1/#1)+ 0.20888568*(1/#1)^(1.5)+ 0.00870357*(1/#1)^(2.5)- (174.2106599*(1/#1)^(3.5))/25920- (715.6423511*(1/#1)^(4.5))/1244160)*exp((-ln(1/#1)-1)*#1}
%   \pgfmathparse{gamma((#2+1)/2.)/(sqrt(#2*pi) *gamma(#2/2.)) *((1+(#1*#1)/#2)^(-(#2+1)/2.))}


    declare function={gamma(\z)=
    2.506628274631*sqrt(1/\z)+ 0.20888568*(1/\z)^(1.5)+ 0.00870357*(1/\z)^(2.5)- (174.2106599*(1/\z)^(3.5))/25920- (715.6423511*(1/\z)^(4.5))/1244160)*exp((-ln(1/\z)-1)*\z;},
    declare function={student(\x,\n)= gamma((\n+1)/2.)/(sqrt(\n*pi) *gamma(\n/2.)) *((1+(\x*\x)/\n)^(-(\n+1)/2.));}

    axis lines=left,
\addplot [thick, smooth, domain=-6:6] {student(x,5)};
\addplot [thick, smooth, domain=-6:6] {gauss(x,0,1)};

Any hint about what happens here would be fine…

Best Answer

I don't know how to properly use \pgfmathdeclarefunction, but for me the following works:

\tikzset{declare function={bellshape(\x,\mu,\sigma)=exp(-(\x-\mu)^2/(2*\sigma^2));}}
\tikzset{declare function={normal(\x,\mu,\sigma)=1/(2.5066283*\sigma)*bellshape(\x,\mu,\sigma);}}
\tikzset{declare function={gamma(\z)= (2.506628274631*sqrt(1/\z) + 0.20888568*(1/\z)^(1.5) + 0.00870357*(1/\z)^(2.5) - (174.2106599*(1/\z)^(3.5))/25920 - (715.6423511*(1/\z)^(4.5))/1244160)*exp((-ln(1/\z)-1)*\z);}}
\tikzset{declare function={tpdf(\x,\nu) = gamma(0.5*(\nu+1))/(sqrt(3.1415927*\nu)*gamma(\nu/2))*(1+\x^2/\nu)^(-(\nu+1)/2);}}

Basically, with \tikzset you can set the same options globally that you would otherwise set locally in square brackets.