# Piecewise Function in tikzpicture

I'm trying to create a piecewise plot in tikzpicture. Trying to emulate the example from this answer Plotting a piecewise function didn't work for me, and I don't understand why this code isn't working.

\documentclass[11pt, letterpaper]{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}[
declare function={
func(\x)= (\x<=0) * ((0.5)*exp(\x))   +
and(\x>0) * (1-(0.5)*exp(-\x))
;
}
]
\begin{axis}[
axis x line=middle, axis y line=middle,
ymin=0, ymax=1, ytick={0,0.5,1}, ylabel=$F_{X-Y}(t)$,
xmin=-5, xmax=5, xtick={-5,...,5}, xlabel=$t$,
]
\end{axis}
\end{tikzpicture}
\end{document}


Any help would be greatly appreciated!

• Welcome! You have an excess and. Use func(\x)= (\x<=0) * ((0.5)*exp(\x)) + (\x>0) * (1-(0.5)*exp(-\x));.
– user194703
Feb 19, 2020 at 3:51

Welcome! You call and with only one argument, and it seems to me (but I may be wrong) that you do not want an and at all. (You may also change the function to only use abs and sign functions, see the afunc definition.)

\documentclass[11pt, letterpaper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}[
declare function={
func(\x)= (\x<=0) * ((0.5)*exp(\x))   +
(\x>0) * (1-(0.5)*exp(-\x));
afunc(\x)=0.5*(1+sign(\x)-sign(\x)*exp(-abs(\x)));
}
]
\begin{axis}[
axis x line=middle, axis y line=middle,
ymin=0, ymax=1, ytick={0,0.5,1}, ylabel=$F_{X-Y}(t)$,
xmin=-5, xmax=5, xtick={-5,...,5}, xlabel=$t$,
]
\end{axis}
\end{tikzpicture}
\end{document}


Of course, the function may be approximated by a tanh.

\documentclass[11pt, letterpaper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}[
declare function={
func(\x)= (\x<=0) * ((0.5)*exp(\x))   +
(\x>0) * (1-(0.5)*exp(-\x));
}
]
\begin{axis}[
axis x line=middle, axis y line=middle,
ymin=0, ymax=1, ytick={0,0.5,1}, ylabel=$F_{X-Y}(t)$,
xmin=-5, xmax=5, xtick={-5,...,5}, xlabel=$t$,
]
\end{axis}
\end{tikzpicture}
\end{document}


• afunc(\x)=0.5*(1+sign(\x)*(1-exp(-abs(\x)))); works too :-) . Nice answer (+1) Feb 19, 2020 at 4:19
• @Zarko Thanks! Yes, this is even simpler.
– user194703
Feb 19, 2020 at 4:21
• BTW, such function (without offset) is used as approximation of sign˙ function in a realization of the sliding mode control (SMC). With it theoretical infinity switching frequency of the SMC is set to some reachable value of a used hardware. Feb 19, 2020 at 4:32
• @Zarko Thanks again! I am more familiar with tanh`, which has an analytic continuation. It appears often in domain walls, kinks and quantum mechanics.
– user194703
Feb 19, 2020 at 4:34
• @Schrodinger's cat This works perfectly, thank you!
– Nico
Feb 19, 2020 at 4:36