1

Is it possible to plot a recursive function using pgfplots \addplot command?

I tried like this;

\documentclass{article}
\usepackage{pgfplots}

\pgfmathdeclarefunction{fac}{1}{
  \pgfmathparse{(#1<=1)+
                (#1>1)*#1*fac(#1-1)
  }
}

\begin{document}
fac(5) is \pgfmathparse{fac(5)}\pgfmathresult

\end{document}

But the result seems to be an infinite recursion, as the entire function is being evaluated.

Skeen
  • 143
  • 2
    if you define them properly yes. – percusse Nov 20 '16 at 21:29
  • @percusse: I've tried just getting a simple recursive fibonacci function to plot, but it like I'm triggering an infinite recursion whatever I do. Could you provide an example, say with the fibonacci function? – Skeen Nov 20 '16 at 21:31
  • It might be better if you add what you've tried so far in the form of a minimal working example (MWE) so it's easier to work out where you're going wrong and less effort to provide you with a working example. – Dai Bowen Nov 20 '16 at 22:03
  • @DaiBowen: Alike this? – Skeen Nov 20 '16 at 22:14
  • @Skeen The recursive function does not terminate. But even with a proper termination (ifthenelse, ...), there is the problem that the arguments are evaluated first. Thus there is an infinite recursion before the stop condition is evaluated. Thus, the recursive function needs to be defined at lower level. Unhappily, there are several different lower levels (e.g. standard, fpu, fixed point arithmetic, ...). Package pgfplots uses the numbers in the format of library fpu. – Heiko Oberdiek Nov 20 '16 at 23:00
  • @Skeen There is a closed form for Fibonacci numbers, so no need for recursion. – Henri Menke Nov 20 '16 at 23:09
  • @HenriMenke: Fibonacci was just the simple example case, not the function I actually want to plot. – Skeen Nov 20 '16 at 23:23
  • @HeikoOberdiek: I'm afraid I'm in no way familiar with the internal workings of pgfplots or how to define my function with fpu. Do you know of a 'Getting Started' guide or similar for this? – Skeen Nov 20 '16 at 23:27
  • @Skeen It is much easier to calculate the values externally. – Heiko Oberdiek Nov 21 '16 at 05:33

1 Answers1

1

I ended up following Heiko Oberdiek's suggestion of calculating the values externally (in this case by using luacode, within LuaLatex):

\documentclass{article}
\usepackage{pgfplots}
\usepackage{luacode}
\begin{document}
\begin{tikzpicture} 
\begin{axis}
\begin{luacode*}
function fib(n)
    local function inner(m)
        if m < 2 then
            return m
        end
        return inner(m-1) + inner(m-2)
    end
    return inner(n)
end

local points = "";
for i=0,15,1 do
    points = points .. " (" .. i .. "," .. fib(i) .. ")";
end

tex.print("\\addplot [mark=none] coordinates { " .. points .. "};");
\end{luacode*}
\end{axis} 
\end{tikzpicture}
\end{document}

Which yields this:

Result

Skeen
  • 143