[Tex/LaTex] How to work around this TikZ bug: (\x)^2 and \x^2 produce different results in TikZ plot

debuggingpgf-2.10tikz-pgf

I have some files with TikZ graphics that have suddenly changed appearance since I upgraded to PGF-2.10. Here is a minimal example:

\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\pgfversion\par
\begin{tikzpicture}
\draw[blue] plot[domain=-1:1] (\x,{\x^2 + \x^3});
\draw[xshift=4cm,blue] plot[domain=-1:1] (\x,{(\x)^2 + (\x)^3});
\end{tikzpicture}
\end{document}

In PGF 2.00 I had this:

minimal example

while in 2.10 I have this:

minimal example

The one on the left in PGF 2.10 looks like the graph of y=x^3 but could also be y=x^3 + x|x|. This has been reported on sourceforge and discussed on the pgf-users mailing list. Although I haven't checked myself yet, the bug remains open and some of the commenters below report that problems still exist in the CVS version.

Geoffrey Jones notes the bug is in the 2.00 CVS version:

Hi Matthew, not an answer, just an FYI
that's too large for the comment box.
My compile of your code through pgf
v2.00 produces the result you see with
v2.10, above: alt text

I.e., the difference you observe seems
to pre-date v2.10.

There is a workaround by inserting parentheses. But since I have so many old lecture files I'd rather find a solution that doesn't involve rewriting my TikZ code. And I'm squeamish about using the CVS bleeding edge code even if it were fixed, since I don't want to introduce other problems. Ideally I'd like a simple patch that I can stick at the preamble, or just fix one file in the PGF distro.

Best Answer

The bug ticket has been rejected on 2013-07-12, with the following comment from Till Tantau:

This is not a bug. TeX does a pure textual replacement, so {\x^2} for \x being -2 gets replaced by {-2^2}, which correctly evaluates to -4 because, indeed, the power operator takes precedence over unary negation (as it should).

What you are looking for is {(\x)^2}, which works as expected.