5

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.

3
  • 1
    possibly helpful? tex.stackexchange.com/questions/291404/…
    – cmhughes
    Commented Nov 23, 2017 at 15:01
  • Thanks, I saw that earlier but couldn't figure it out. I've only been using latex for a short time and Im struggling to work out what to do.
    – John 545
    Commented Nov 23, 2017 at 15:08
  • Is this not possible in tikz?
    – John 545
    Commented Nov 23, 2017 at 20:03

1 Answer 1

6

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .