%% 
%%  Ein Beispiel der DANTE-Edition
%%  
%%  2. Auflage
%% 
%%  Beispiel 15-04-82 auf Seite 813.
%% 
%%  Copyright (C) 2016 Herbert Voss
%% 
%%  It may be distributed and/or modified under the conditions
%%  of the LaTeX Project Public License, either version 1.3
%%  of this license or (at your option) any later version.
%% 
%%  See http://www.latex-project.org/lppl.txt for details.
%% 
%% 
%% ==== 
% Show page(s) 1
%% 
%% 
\documentclass[]{exaarticle}
\pagestyle{empty}
\setlength\textwidth{352.81416pt}
\usepackage[T1]{fontenc}
%StartShownPreambleCommands
\usepackage{pgfplots,luacode}   \pgfplotsset{width=7cm,compat=1.8}
\begin{luacode}
  function weierstrass(x0, x1, n, a, b, epsilon)
    local dx = (x1-x0)/n; x = x0
    local y, k, dy
    local out=assert(io.open("tmp.data","w")) -- external data file
    while (x <= x1) do
      y = 0;  k = 0
      repeat
        dy = math.pow(a,k) * math.cos(math.pow(b,k)*math.pi*x)
        y = y + dy;  k = k + 1
      until (math.abs(dy) < epsilon)
      out:write(x, " ", y, "\string\n")
      x = x + dx
    end
    out:close()
  end
\end{luacode}
%StopShownPreambleCommands
\begin{document}
\begin{tikzpicture}
  \directlua{weierstrass(-2,2,5000,0.3,5,1.e-12)}%
  \begin{axis}[axis lines=middle, domain=-2:2]
    \addplot [thin, line join=round] table {tmp.data};  %% read data
    \coordinate (legend) at (axis cs:0,2);
  \end{axis}
  \node at (legend){$\displaystyle f(x)=\sum_{n=0}^\infty a^n \cos(b^n\pi x)$};
\end{tikzpicture}
\end{document}
