# Piecewise function is not correct plotted with tikz

I am trying to plot a piecewise function using the code below. The problem is, that the right piece is not plotted correct. It should (obviously) be constant zero, for values bigger than pi/2, but it does not look like that in the plot. I am sure I did something wrong.

\begin{tikzpicture}[
declare function={
func(\x)= and(\x >= -pi, \x < -pi/2) * (0)   +
and(\x >= -pi/2, \x <= pi/2) * (-(\x)*(\x)+pi*pi/4)     +
and(\x > pi/2, \x <= pi) * * (0)
;
}
]
\begin{axis}[
Axis Style,
xtick={
-3.14159, -1.5708, 0,
1.5708, 3.14159
},
xticklabels={
$-\pi$, $-\frac{\pi}{2}$, $0$, $\frac{\pi}{2}$, $\pi$
},
ytick={
0,
1.234, 2.467
},
yticklabels={
$0$, $\frac{\pi^2}{8}$, $\frac{\pi^2}{4}$
},
samples=75
]
\addplot [mark=none,ultra thick, domain=-3.1415:3.15, blue] {func(x)};
\end{axis}
\end{tikzpicture}

• Welcome to TeX.SX! Without testing it I would guess that this is because of the number of samples and where they are. Remove mark=none to confirm this. Then you can either increase the number of samples by adding samples=<number of samples to either the axis or the \addplot options or make sure that there is a sample point at all relevant places. Jan 13, 2019 at 11:01
• I have already tried increasing/decreasing the number of samples, it sometimes got better, but a higher number of samples did not mean a better result... Jan 13, 2019 at 11:03
• I haven't tested but I think that removing a * in the third line in declare function would do.
– user156344
Jan 13, 2019 at 11:04
• Both of the first two lines have one * each, but the third one has two *s. Maybe that is the problem.
– user156344
Jan 13, 2019 at 11:05
• Ah, thanks a lot. I wonder how I could not have noticed that.. Jan 13, 2019 at 11:06

There was a small mistake in your code. Try with this small change:

\documentclass{article}
\usepackage{tikz,pgfplots}

\begin{document}
\begin{tikzpicture}[
declare function={
func(\x)= and(\x >= -pi, \x < -pi/2) * (0)   +
and(\x >= -pi/2, \x <= pi/2) * (-(\x)*(\x)+pi*pi/4)     +
and(\x > pi/2, \x <= pi)  * (0)
;
}
]
\begin{axis}[
Axis Style,
xtick={
-3.14159, -1.5708, 0,
1.5708, 3.14159
},
xticklabels={
$-\pi$, $-\frac{\pi}{2}$, $0$, $\frac{\pi}{2}$, $\pi$
},
ytick={
0,
1.234, 2.467
},
yticklabels={
$0$, $\frac{\pi^2}{8}$, $\frac{\pi^2}{4}$
},
samples=75
]
\addplot [mark=none,ultra thick, domain=-3.1415:3.15, blue] {func(x)};
\end{axis}
\end{tikzpicture}

\end{document}

• Axis Style, is not defined ... Jan 13, 2019 at 14:27