PGFPlots – How to Plot a Summation of Cosine Wave Using LuaTeX and luaCode

lualuacodeluatexpgfplotsplot

I need to draw a wave that is the summation of these cosine waves

enter image description here

This is my attempt in LuaLaTeX:

\documentclass{article}

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

\usepackage{luacode}
\begin{luacode*}

function p(x)
    assert(x == math.floor(x), "x must be an integer")
    res = 0
    for W = 0, 4000 do
        res = res + (1/2) * (1 + math.cos(2*math.pi*x*W))
    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}

The shape of the graph I expect held a central absolute maximum, with local maximums that decrease as the central maximum moves away

enter image description here

The graph show nothing

Best Answer

I'm still not one of the cool kidz who use LuaLaTeX these days. This solution will be done in plain LaTeX, i.e. pdflatex.

I used the tikzmath library of TikZ, no PGFPlots needed. Also, I don't know whether you really needed the 1+ in the summation, since it will only shift the graph up, but customise the following as you wish. Maybe \n = 6.

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{math}

\begin{document}

\begin{tikzpicture}[scale=.5]
    \tikzmath{
        function f(\x, \n) {
            %\y = \n+1;
            \y = 0;
            for \i in {0,...,\n} {
                \y = \y + cos(deg(2 * pi * \x) * \i);
            };
            \y = \y / 2;
            return \y;
        };
    }
    \draw[->] (-5,0) -- (5,0) node[below] {\(x\)};
    \draw[->] (0,-1) -- (0,4) node[left] {\(p(x)\)};
    \draw[domain=-4:4, samples=201, smooth] plot (\x, {f(\x,6)});
\end{tikzpicture}

\end{document}

enter image description here


Answer to comment: This should actually work, you only need to add use fpu=false, as you said (see also this question).

\documentclass[convert]{standalone}

\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{math}

\begin{document}

\begin{tikzpicture}[scale=.5]
    \tikzmath{
        function f(\x, \n) {
            %\y = \n+1;
            \y = 0;
            for \i in {0,...,\n} {
                \y = \y + cos(deg(2 * pi * \x) * \i);
            };
            \y = \y / 2;
            return \y;
        };
    }
    \begin{axis}[use fpu=false]
        \addplot[domain=-4:4, samples=201] {f(x,6)};
    \end{axis}
\end{tikzpicture}

\end{document}

enter image description here