1

I would like to use pgfplots to create a figure where I plot curves that have a recursive formula. I tried a very simple case that uses the declare function command to see whether this is possible, and I can't compile (TeX capacity exceeded). Is it even possible to do this?

\documentclass{standalone}

\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}[
  declare function={test(\p)=ifthenelse(\p>1, test(\p-1), 0.5);},
]
    \begin{axis}[]
    % use TeX as calculator:
    \addplot [mark=none] {x};
    \addplot [mark=none] {test(0)};
    \end{axis}
\end{tikzpicture}

\end{document}
  • 1
    There is a closing ) missing.... try declare function={test(\p)=ifthenelse(\p>1, test(\p-1), 0.5);} – user121799 Aug 22 '18 at 14:37
  • 1
    Indeed, but that didn't help. – aaragon Aug 22 '18 at 14:38
  • You're right. I think it is not possible to do it like this but it is possible to do it with tikzmath, see p. 640 of the pgfmanual. – user121799 Aug 22 '18 at 14:41
  • What I liked about declare function is the simplicity. By the way, what version of the pdfmanual? I look at page 640 in v2.10 and there's nothing related to this. – aaragon Aug 22 '18 at 14:46
  • 1
    Are you really still using 2.10? Because version 3 is out for quite some time. Maybe your manual will not contain the mentioned section. – TeXnician Aug 22 '18 at 14:53
2

As marmot already stated in the comment below the question you can use the tikzmath library to declare recursive functions. Instead of declare function you simply use evaluate and than you have to use a little bit different syntax. But I think with the Fibonacci example from the pgfmanual (section 56.1 on page 640 of v3.0.1a) you will be able to modify it to your needs.

% used PGFPlots v1.16
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
    \usetikzlibrary{math}
\begin{document}
\begin{tikzpicture}[
    evaluate={
        % (copied from the pgfmanual)
        % Adapted from http://www.cs.northwestern.edu/academics/courses/110/html/fib_rec.html
        function fibonacci(\n) {
            if \n == 0 then {
                return 0;
            } else {
                return fibonacci2(\n, 0, 1);
            };
        };
        function fibonacci2(\n, \p, \q) {
            if \n == 1 then {
                return \q;
            } else {
                return fibonacci2(\n-1, \q, \p+\q);
            };
        };
    },
]
    \begin{axis}
        \addplot+ [domain=0:10,samples=11] {fibonacci(x)};
    \end{axis}
\end{tikzpicture}
\end{document}

image showing the result of above code

  • When I try to use this exact code it seems that the compiler can't understand the data being sent to the plot (i.e. wrong units, missing number). I'm using overleaf and was limited to 1.15, not sure if that could be the issue. – Caharpuka Dec 25 '18 at 22:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.