I'm trying to plot an illustration of the fixed point method in which a function is evaluated repeatedly in a loop. The result should be a staircase or spiral plot on top of the plot of the function itself. I've read here about the use of \edef inside a foreach loop. The following MWE should show what I'm trying to do, but it seems to only perform a single iteration.
Notes:
- the loop variable isn't used inside the loop.
- perhaps it's an illusion that only single iteration is performed and the real issue is that
\xprevand\xnextaren not updated at each pass through the loop. I tried placing the updates inside the\edef, but that gives an undefined control sequence error. - I also tried
\pgfplotsinvokeforeachinstead of\foreach, but only obtained other errors.
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\pgfmathdeclarefunction{g}{1}{\pgfmathparse{#1^2 - 2}}
\begin{tikzpicture}
\begin{axis} [
xmin = -2.5, xmax = 2.5, ymin = -3, ymax = 3,
axis x line = center, axis y line = center,
domain=-2.5:2.5, samples=300,
]
\addplot[ultra thick] {g(x)}; % graph of g
\addplot[thin] {x}; % diagonal
\def\xstart{-0.75}
\pgfmathsetmacro{\xprev}{\xstart};
\pgfmathsetmacro{\xnext}{g(\xprev)};
\draw[thick, blue] (\xstart, 0) -- (\xstart, \xnext) -- (\xnext, \xnext);
\foreach \i in {1, 2, 3}{
\pgfmathsetmacro{\xprev}{\xnext}
\pgfmathsetmacro{\xnext}{g(\xprev)} % x <- g(x)
\edef\plotoneiter{%
\noexpand%
\draw[thick, blue] ({\xprev}, {\xprev}) -- ({\xprev}, {\xnext}) -- ({\xnext}, {\xnext});
}\plotoneiter%
}
\end{axis}
\end{tikzpicture}
\end{document}
Thanks in advance for any hints!
EDIT: Here is a quick sketch of what I'm trying to achieve:







