[Tex/LaTex] pgf plot: Missing number, treated as zero

pgfplots

I am trying to plot cos(ln(x)) using pgfplots but I get this strange error that I cannot figure out.

Below is my MWE:

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[xmin = 1, xmax = 2]

\addplot[blue, samples=50]{ ln(x)             };
\addplot[red, samples=50]{ cos(deg(x))        };

\addplot[green, samples=50]{ cos(deg(ln(x))   };

\end{axis}
\end{tikzpicture}
\end{document}

The errors come from line: \addplot[green, samples=50]{ cos(deg(ln(x)) }; and are the following:

line 14: Missing number, treated as zero. …ot[green, samples=50]{
cos(deg(ln(x)) };

line 14: Illegal unit of measure (pt inserted). …ot[green,
samples=50]{ cos(deg(ln(x)) };

I am very confused since plotting ln(x) and cos(deg(x)) does not return any errors. And ln(x) is perfectly well behaved on 1 to 2…

Best Answer

You get the error because you try to evaluate cos(deg(ln(x))) for negative values of x, where the solutions of ln(x) are complex numbers, and ln(0) where it is -∞ (-inf). It seems deg can handle these values, but cos cannot, for reasons unbeknownst to me.

The reason this is no problem with only ln(x) is that pgfplots has the inital setting unbounded coords=discard, which means it drops the value if it evaluates to ±∞ (+inf or -inf) or if it is nan ("not a number"). This does not work for cos(deg(ln(x))), since you are trying to calculate cos(nan) or cos(-inf), which is why the error is raised only at the last plot.

This happens because you are not specifying a domain for the plot, meaning it will use the default domain -5:5.

So by specifying domain=1:2 in your axis (or only for the last plot):

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[xmin = 1, xmax = 2,domain=1:2]

\addplot[blue, samples=50]{ ln(x)             };
\addplot[red, samples=50]{ cos(deg(x))        };
\addplot[green, samples=50]{ cos(deg(ln(x)))  };

\end{axis}
\end{tikzpicture}
\end{document}

Output