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.

  • 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
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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