# atan2 does not work with pgfplots

Trying to plot the amplitude and argument of two sine waves in terms of their amplitudes and phases using pgfplots, An error appears while compiling the atan2 function (supported by pgfmath). Here is the example

\documentclass[]{article}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
title={$\sqrt{x^2+1-2x\cos(y)}$},
xlabel=$x$, ylabel=$y$,
]
{sqrt(x^2+1-2*x*cos(y))};
\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[
title={$atan2(-\sin(y),x-cos(y)$},
xlabel=$x$, ylabel=$y$,
]
{atan2(-sin(y),x-cos(y)};
%{sqrt(x^2+1-2*x*cos(y))};
\end{axis}
\end{tikzpicture}

\end{document}


The errors are:

    (line 31) Illegal unit of measure (pt inserted) {atan2(-sin(y),x-cos(y)}


and

    (line 31) Missing = inserted for \ifdim. {atan2(-sin(y),x-cos(y)}


repeated several times

• Welcome to TeX.SX! – user31729 Sep 30 '14 at 12:39
• It runs using {atan(-sin(y)/(x-cos(y)))}; I tried using ifthenelse to handle the quadrants but got errors about badly formed numbers. I suspect the problem is that atan2 is not implemented in the fpu library. – John Kormylo Sep 30 '14 at 17:07
• Even {ifthenelse(x > .5, 1, 0)}; doesn't work. Weird! \pgfkeys{/pgf/fpu=false} doesn't help eiher. – John Kormylo Sep 30 '14 at 18:00

As others already mentioned, the floating point unit (FPU) shipped with PGF currently has no implementation of atan2 (it should get one; this is a bug).

A workaround is to configure pgfplots that it should not use the FPU. This works for the image in question (but is, in general, not recommended since it limits both data range + precision).

\documentclass{standalone}
\usepackage{pgfplots}

\pgfplotsset{compat=1.10}
\begin{document}

\begin{tikzpicture}
\begin{axis}[
title={$atan2(-\sin(y),x-cos(y)$},
xlabel=$x$, ylabel=$y$,
use fpu=false
]
{atan2(-sin(y),x-cos(y))};
%{sqrt(x^2+1-2*x*cos(y))};
\end{axis}
\end{tikzpicture}

\end{document}


You can fake it by falling back to PGF atan2 function pretending to be a fpu implementation.

\documentclass[]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\makeatletter
\pgfmathdeclarefunction{myatan2}{2}{%
\begingroup%
\pgfmathfloattofixed{#1}\edef\tempa{\pgfmathresult}%
\pgfmathfloattofixed{#2}%
\pgfkeys{pgf/fpu=false}%
\pgfmathparse{atan2(\tempa,\pgfmathresult)}\pgfkeys{/pgf/fpu}%
\pgfmathfloatparsenumber{\pgfmathresult}%
\pgfmath@smuggleone\pgfmathresult%
\endgroup
}
\makeatother

\begin{document}
\begin{tikzpicture}
\begin{axis}[
title={$atan2(-\sin(y),x-cos(y)$},
xlabel=$x$, ylabel=$y$,
]
{myatan2({-sin(y)},{x-cos(y)})};
%{sqrt(x^2+1-2*x*cos(y))};
\end{axis}
\end{tikzpicture}
\end{document}


Output is the same as John Kormylo's image.

I think I got the quadrants right.

\documentclass[]{article}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
title={$atan2(-\sin(y),x-cos(y))$},
xlabel=$x$, ylabel=$y$,
]