Las funciones definidas con un bucle (\foreach) hacen que la imagen tikz se aleje mucho

Las funciones definidas con un bucle (\foreach) hacen que la imagen tikz se aleje mucho

En el siguiente MWE, la imagen de tikz está fuera del periódico. Cuando reemplazo 10 por un número mayor, las imágenes van aún más hacia la derecha. Alguna idea ?

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}

\pgfmathdeclarefunction{myfunction}{1}{
    \let\x\pgfmathresult
    \pgfmathsetmacro\ret{0}
    \foreach \i in {1,...,10}{
        \pgfmathsetmacro\ret{\ret + \x^\i}
        \xdef\ret{\ret}
    }
    \pgfmathparse{\ret}
}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[axis lines=middle, domain=-1:1]
        \addplot[domain=-1:1, blue, samples=10] {myfunction(x)};
    \end{axis}
\end{tikzpicture}

\end{document}

Respuesta1

Como se menciona en el comentario, agregue signos de porcentaje. (En este caso, uno de los signos de porcentaje se puede omitir sin ningún daño debido a las reglas de TeX, pero en este caso particular está bien tenerlos todos también).

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}

\pgfmathdeclarefunction{myfunction}{1}{%
    \let\x\pgfmathresult
    \pgfmathsetmacro\ret{0}%
    \foreach \i in {1,...,10}{%
        \pgfmathsetmacro\ret{\ret + \x^\i}%
        \xdef\ret{\ret}%
    }%
    \pgfmathparse{\ret}%
}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[axis lines=middle, domain=-1:1]
        \addplot[domain=-1:1, blue, samples=10] {myfunction(x)};
    \end{axis}
\end{tikzpicture}

\end{document}

Alternativamente use la sintaxis expl3, pero esto ignoratodos los espaciosy realiza algunos otros cambios, así que asegúrese de saber lo que hace.

\ExplSyntaxOn
\pgfmathdeclarefunction{myfunction}{1}{
    \let\x\pgfmathresult
    \pgfmathsetmacro\ret{0}
    \foreach \i in {1,...,10}{
        \pgfmathsetmacro\ret{\ret + \x^\i}
        \xdef\ret{\ret}
    }
    \pgfmathparse{\ret}
}
\ExplSyntaxOff

información relacionada