2

Can someone explain me why the function binom (in red) does not work for x=-6 and x=+6 (compare with the correct plot (in gray)) ?

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.7}
\begin{document}

\begin{tikzpicture} [declare function={binom(\N,\m)=\N! / (2^\N) / ((\N+\m)/2)! / ((\N-\m)/2)!;}] \begin{axis}[ ymin=0, ymax=0.4, xmin=-6.5, xmax=6.6, axis lines=left, x label style={at={(axis description cs:1,0.1)},anchor=north}, y label style={at={(axis description cs:-0.15,1)},rotate = -90, anchor=north}, samples at={-6,-4,...,6}, xtick={-6,-5,...,6}, yticklabel style={ /pgf/number format/fixed, /pgf/number format/fixed zerofill, /pgf/number format/precision=2}, ybar=0pt, bar width=1, bar shift=0pt] \addplot [fill=red!25] {binom(6,x)}; \addplot [fill=gray!25,bar width=.5] plot coordinates {(-6,1/2^6) (-4,{6!/2^6/5!/1!}) (-2,{6!/2^6/4!/2!}) (0,{6!/2^6/3!/3!}) (2,{6!/2^6/4!/2!}) (4,{6!/2^6/5!/1!}) (6,{6!/2^6/6!/0!})}; \end{axis} \end{tikzpicture} \end{document}

enter image description here

  • Does this answer help you: https://tex.stackexchange.com/a/198575/118712 – Markus G. Apr 19 '21 at 16:58
  • @Markus G. Not really. My binom function is for a random walk with equal probabilities (p=1-p=0.5). The function is correct. For 6 steps: when I develop it by hand (gray plot), it is OK; but when I use the formulae (red plot), there is a problem for x=+6 and x=-6. I really don't understand why. – user4624500 Apr 19 '21 at 21:22

1 Answers1

3

This is a rounding error:

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.7}
\begin{document}

\begin{tikzpicture} \begin{axis}[ ymin=0, axis lines=left, samples at={0}, ybar=0pt, bar width=1, bar shift=0pt] \addplot [fill=red!25] plot coordinates {(0,{6!/5!})};
\addplot [fill=gray!25,bar width=.5] plot coordinates {(0,{(12/2)!/5!})}; \end{axis} \end{tikzpicture} \end{document}

enter image description here

You can work around this by replacing ((\N+\m)/2) with round((\N+\m)/2) (so just adding round in front of the first parenthesis —and same for the - one).

Archange
  • 1,368