[Tex/LaTex] How to use a summation in a tikz plot

plottikz-pgf

I need to plot this function using tikz, but I have no idea how to go about using the summation in tikz. If someone could help me I would really appreciate it.
Function
The code I have is this:

\documentclass{article}

\usepackage{pgfplots}
\usepackage{tikz}

\usepackage[paperwidth=20cm, paperheight=10cm, margin=0.0cm]{geometry}

\begin{document}
\hspace{-0.4cm}    
\begin{tikzpicture}[
  declare function={p(\k,\n) =((\n!*(\k*(\k-1)))/((\n^(\k))*((\n-(\k-
1))!)));}
                    ]
\begin{axis}[axis lines=middle, grid=both, width=20cm, height=10cm, grid 
style={line width=.2pt, draw=gray!10},major grid style={line 
width=.3pt,draw=gray!50},
            xlabel=$k$, ylabel=$y$, 
            ylabel style={anchor=south},
            xlabel style={anchor=west},
            ymax=1, xmax=21.5,
            domain=0:21.5, samples at={0,...,21},
                    ]
\addplot+ [blue, thick, mark size={1.6pt}, mark options={draw=blue, 
fill=white!75!cyan}] {p(x,20)};
\end{axis}
\end{tikzpicture}

\end{document}

This plots the function of x, but I don't know how to sum the function from k=2 to x+1.

Best Answer

You can use Lua to compute the sum. Then you have to typeset using LuaLaTeX of course.

\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\usepackage{luacode}
\begin{luacode*}
function factorial(n)
    assert(n >= 0, "Factorial is only valid for positive integers")
    if n == 0 then
        return 1
    end
    return n*factorial(n-1)
end

function p(x)
    assert(x == math.floor(x), "x must be an integer")
    res = 0
    for k = 2, x+1 do
        res = res + factorial(x)/factorial(x-(k-1)) * k*(k-1)/(x^k)
    end
    tex.sprint(res)
end
\end{luacode*}

\begin{document}

\begin{tikzpicture}[
  declare function={p(\n) = \directlua{p(\n)};}
  ]
  \begin{axis}[
    use fpu=false, % very important!
    xlabel=$x$, ylabel=$p(x)$,
    samples at={0,...,21},
    only marks,
    ]
    \addplot {p(x)};
  \end{axis}
\end{tikzpicture}

\end{document}

enter image description here