[Tex/LaTex] Good workaround for pgfmath/tikz definition of inverse cosine

pgfmathtikz-pgf

I wanted to draw a graph of y = arccosine(x) and saw in the Tikz documentation the function acos which claims to do this but returns a result in the range [-90,90] (degrees). I was surprised by this since cos(x) is not one-to-one over the domain [-90,90], and most conventional definitions would put the range of acos as [0,180].

The fact that the function defined is not inverse cosine can be verified by the following minimal working example, in which pgf claims that the inverse cosine of -1 is 0:

\documentclass{minimal}
\usepackage{pgfmath}
\begin{document}
Inverse cosine of $-1$ is apparently \pgfmathparse{acos(-1)} \pgfmathresult 
\end{document}

I'm not sure whether to count this as a bug (since the documentation explicitly states that it will work in this way) but is there a good workaround to easily get the actual inverse cosine function in pgfmath/tikz?

Best Answer

This was fixed in revision 1.3 of pgfmathfunctions.trigonometric.code.tex, dated 2009-01-22.

It is strongly recommended to upgrade to the current version of PGF (v 2.1), which includes this file.

If you do not want to update, you can just declare the fixed functions in your document by including the following code chunk in your preamble. You can then access the corrected functions using newasin and newacos.

\makeatletter
\pgfmathdeclarefunction{newasin}{1}{%
    \begingroup%
        \expandafter\pgfmath@x#1pt\relax%
        \pgfmath@xa\pgfmath@x%
        \ifdim\pgfmath@x<0pt\relax%
            \pgfmath@x-\pgfmath@x%
        \fi%
        \pgfmath@x1000\pgfmath@x%
        \afterassignment\pgfmath@gobbletilpgfmath@%
        \expandafter\c@pgfmath@counta\the\pgfmath@x\relax\pgfmath@%
        \pgfmath@x-\csname pgfmath@acos@\the\c@pgfmath@counta\endcsname pt\relax%
        \advance\pgfmath@x90pt\relax%
        \ifdim\pgfmath@xa<0pt\relax%
            \pgfmath@x-\pgfmath@x%
        \fi%
        \pgfmath@returnone\pgfmath@x%
    \endgroup%
}

\pgfmathdeclarefunction{newacos}{1}{%
    \begingroup%
        \expandafter\pgfmath@x#1pt\relax%
        \pgfmath@xa\pgfmath@x%
        \ifdim\pgfmath@x<0pt\relax%
            \pgfmath@x-\pgfmath@x%
        \fi%
        \pgfmath@x1000\pgfmath@x%
        \afterassignment\pgfmath@gobbletilpgfmath@%
        \expandafter\c@pgfmath@counta\the\pgfmath@x\relax\pgfmath@%
        \expandafter\pgfmath@x\csname pgfmath@acos@\the\c@pgfmath@counta\endcsname pt\relax%
        \ifdim\pgfmath@xa<0pt\relax%
            \pgfmath@x-\pgfmath@x%
            \advance\pgfmath@x by180pt\relax%
        \fi%
        \pgfmath@returnone\pgfmath@x%
    \endgroup%
}
Related Question