Using the question here I have tried to plot a piecewise function. My code looks like
\begin{document}
\pgfmathdeclarefunction{func}{1}{%
\pgfmathparse{%
(and(#1<=-2) * (#1*#1 + #1*6 + 8) +%
(and(#1>=-2 ,#1<=1) * (2 - #1 - #1*#1) +%
(and(#1>=1 ,#1<=2) * (6 - #1*8 + #1*#1*2) +%
(and(#1>=2) * (-10 + #1*6 - #1*#1) %
}%
}
\begin{tikzpicture}[scale=0.8
\begin{axis}[
axis x line=middle,
axis y line=middle,
ymin=-5, ymax=5, ytick={-1,-2,-3,-4,-5,1,2,3,4,5}, ylabel=$y$,
xmin=-5, xmax=5, xtick={-5,-4,-3,-2,-1,1,2,3,4,5}, xlabel=$x$
]
\addplot[blue,domain=-5:5]{func(x)};
\end{axis}
\end{tikzpicture}
\end{document}
The function will be x^2+6x+8 for x<=-2, 2-x-x^2 for -2<=x<=1, 2x^2-8x+6 for 1<=x<=2, and -x^2+6x-10 for x>=2. When I try to compile it gives me a PGF Math Error: internal routine of the floating point
. How do I fix this?
Best Answer
The
and
function has at least two arguments, otherwise it can’tand
anything. Simply remove theand
s from the first and the last term.You should also make sure that the pieces do not overlap which they do in your case as you always use
<=
and>=
on the same border value.Furthermore, I have used the top-level
declare function
key to declare a function.Code
Output