14

(\x)^2 will plot correct parabola, while \x^2 will have negative x branch upside down. Why () are required for this formula to work?

\documentclass[10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\usetikzlibrary{shapes.misc}

\begin{document}
\begin{figure}[!htb]
    \begin{tikzpicture}
        \draw[very thin,color=gray] (-4.1,-4.1) grid (4.1,4.1);
        \draw[->] (-4.2,0) -- (4.2,0) node[right] {$x$};
        \draw[->] (0,-4.2) -- (0,4.2) node[above] {$f(x)$};

        \draw[thick,purple,domain=-3:3,smooth] plot (\x,{0.5*\x^2});
        \draw[thick,brown,domain=-3:3,smooth] plot (\x,{0.2*\x^3});
    \end{tikzpicture}

\caption{$y=1/2 x^2, y=1/5 x^3$}
\end{figure}

\end{document}
ajeh
  • 2,572
  • 12
    I think the parenthesis are required to properly square negative numbers. So, -5^2 will be -25. – Peter Grill Feb 06 '14 at 21:03
  • 4
    Slap on the forehead! Right! I am forgetting that this is not a true 'programming' language but macros. This means I gotta be careful in the future and overdoing parenthesis will not hurt :) – ajeh Feb 06 '14 at 21:08
  • 4
    @Peter sounds like that comment could make a pretty good answer. – David Z Feb 06 '14 at 21:26
  • 1
    @ajeh In most true 'programming' languages, the power operator has higher priority than unary minus operator. TikZ is not an exception. – Paul Gaborit Feb 06 '14 at 22:21
  • :) In most true programming languages, minus operator would not be a factor, as variable resolution is not pre-processed: x^2 would not be translated into -5^2 when x=-5. – ajeh Feb 07 '14 at 14:40

1 Answers1

16

The () are required so that exponents are properly applied to negative numbers. Otherwise we have -5^2=-25. Here is the output with and without the applied parenthesis:

enter image description here

Notes:

  • Even though this will only be an issue with even exponents, I would recommend always using parenthesis (\x).

Code:

\documentclass[border=2pt]{standalone}
\usepackage{tikz}

\begin{document} \begin{tikzpicture} \draw[very thin,color=gray] (-4.1,-4.1) grid (4.1,4.1); \draw[->] (-4.2,0) -- (4.2,0) node[right] {$x$}; \draw[->] (0,-4.2) -- (0,4.2) node[above] {$f(x)$};

    \draw[thick,purple,domain=-3:3,smooth] plot (\x,{0.5*\x^2}) node [right] {INCORRECT};
    \draw[thick,brown,domain=-3:3,smooth] plot (\x,{0.2*\x^3}) ;


\begin{scope}[xshift=9cm]
    \draw[very thin,color=gray] (-4.1,-4.1) grid (4.1,4.1);
    \draw[->] (-4.2,0) -- (4.2,0) node[right] {$x$};
    \draw[->] (0,-4.2) -- (0,4.2) node[above] {$f(x)$};

    \draw[ultra thick,purple,domain=-3:3,smooth] plot (\x,{0.5*(\x)^2}) node [right] {CORRECT};
    \draw[ultra thick,brown,domain=-3:3,smooth] plot (\x,{0.2*(\x)^3});
\end{scope}

\end{tikzpicture} \end{document}

Peter Grill
  • 223,288