If you use a parametric representation of the curve (i.e. [sqrt(2)*sin(x), sin(2*x)]
), you can plot it precisely to the extrema.
Here I've used PGFPlots, and also plotted your original equation in gray underneath the parametric representation:

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
domain=-pi/2:pi/2, % The range over which to evaluate the functions
xtick={-1,...,1}, ytick={-1,...,1}, % Tick marks only on integers between -1 and 1
axis lines=middle, % Axis lines go through (0,0)
enlargelimits=true, % Make the axis lines a bit longer than required for the plots
samples=101, % Number of samples for evaluating the functions (use an odd number to capture the (0,0) point
xlabel=$x$, ylabel=$y$, % Axis labels
clip=false % So the labels aren't cut off
]
\addplot [thick, red]
( {sqrt(2) * sin(deg(x))},
{abs(sin(deg(x*2)))} )
node [pos=0.8, anchor=south] {$f(x) = |x|\sqrt{2-x^2}$}; % Add a text node at 80% of the plot length
\addplot [thick, blue]
( {sqrt(2) * sin(deg(x))},
{-abs(sin(deg(x*2)))} )
node [pos=0.8, anchor=north] {$f(x) = -|x|\sqrt{2-x^2}$};
\end{axis}
\end{tikzpicture}
\end{document}
About the underlying problem: The problem is not solved by using PGFPlots (but I would still recommend PGFPlots for plots like this). Also, while using a parametric equation for functions like this will typically lead to better results because of the more even sampling along the plot, that's also not the root cause. The problem occurs because of numerical errors when deciding where to sample the domain, which causes the last sampling point (sqrt(2)
) to be skipped. At it's core, it's the problem discussed in Why doesn't TikZ's \foreach iterate over the last element of the list?. In this context, a good solution would be to patch the function that generates the sampling expression to explicitly include the upper edge of the domain. By putting the following in your preamble (after \usepackage{tikz}
), your original code will work without a gap:
\makeatletter
\def\tikz@plot@samples@recalc#1:#2\relax{%
\pgfmathsetmacro\tikz@temp@start{#1}%
\pgfmathsetmacro\tikz@temp@end{#2}%
\pgfmathsetmacro\tikz@temp@step{(\tikz@temp@end-\tikz@temp@start)/(\tikz@plot@samples-1)}%
\pgfmathsetmacro\tikz@temp@second{\tikz@temp@start+\tikz@temp@step}%
\pgfmathsetmacro\tikz@temp@penultimate{\tikz@temp@end-\tikz@temp@step}
\ifdim\tikz@temp@penultimate pt<\tikz@temp@second pt
\edef\tikz@plot@samplesat{\tikz@temp@start,\tikz@temp@second,...,\tikz@temp@end}%
\else%
\edef\tikz@plot@samplesat{\tikz@temp@start,\tikz@temp@second,...,\tikz@temp@penultimate,\tikz@temp@end}%
\fi%
}
\makeatother

samples
and usesmooth
as in\draw[color=green] plot [smooth,samples=20] (\x,{-abs(\x)*sqrt(2 - \x*\x)});
, they meet. But better usepgfplots
.