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 ofx
, where the solutions ofln(x)
are complex numbers, andln(0)
where it is -∞ (-inf
). It seemsdeg
can handle these values, butcos
cannot, for reasons unbeknownst to me.The reason this is no problem with only
ln(x)
is thatpgfplots
has the inital settingunbounded coords=discard
, which means it drops the value if it evaluates to ±∞ (+inf
or-inf
) or if it isnan
("not a number"). This does not work forcos(deg(ln(x)))
, since you are trying to calculatecos(nan)
orcos(-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):