There are a few problems with the code:
- PGF uses degrees for trig functions
- Seems that the
r
at the end of the function f
was intended to convert from radians to degree, but I changed it so that it is more obvious.
- Need to determine what happens at the end points of the piecewise domain, so note the slight tweaks for that.
- Not sure what the
tkz
portion of the code has to do with the problem of defining a piecewise function, so have commented that out.
- Be careful using single letter function names as documented in: Why do 2 identical function definitions with different names produce two different plots?
So, with slight modifications to your code I can produce the following. Note that there still is a problem around x=1
as pgf does not know what to do.

\documentclass[border=2pt]{standalone}
\usepackage{amsmath}
\usepackage{pgfplots}
\usepackage{tkz-fct}
\pgfmathdeclarefunction{p}{3}{%
\pgfmathparse{(and(#1>#2, #1<#3))}%
}
\pgfmathdeclarefunction{f}{1}{%
\pgfmathparse{p(#1,-100,-0.001)*1 + p(#1,0,1)*#1 + p(#1,1.01,100)*cos(deg(#1))}%
}
\begin{document}
\begin{tikzpicture}
% \tkzInit[xmin=-1,xmax=5,ymax=4] %
% \tkzGrid %
% \tkzAxeXY %
% \tkzFct{f(x)} %
% \draw plot function{f(x)};%
\begin{scope}[xshift=6cm]
\begin{axis}
\addplot[ultra thick, blue,domain=-2:4,samples=100]{f(x)};
\end{axis}
\end{scope}
\end{tikzpicture}
\end{document}
What I would recommend is that you draw the three separate portions individually and avoid the problem areas via a fixed value of \Tolerance
:

\documentclass[border=2pt]{standalone}
\usepackage{amsmath}
\usepackage{pgfplots}
\usepackage{tkz-fct}
\pgfmathdeclarefunction{p}{3}{%
\pgfmathparse{(and(#1>#2, #1<#3))}%
}
\newcommand{\Tolerance}{0.0001}%
\pgfmathdeclarefunction{f}{1}{%
\pgfmathparse{%
p(#1,-\maxdimen,-\Tolerance)*1.0 +%
p(#1,0,1-\Tolerance)*#1 +%
p(#1,1,\maxdimen)*cos(deg(#1))}%
}
\begin{document}
\begin{tikzpicture}
% \tkzInit[xmin=-1,xmax=5,ymax=4] %
% \tkzGrid %
% \tkzAxeXY %
% \tkzFct{f(x)} %
% \draw plot function{f(x)};%
\begin{scope}[xshift=6cm]
\begin{axis}
\addplot[ultra thick, blue,domain=-2:-\Tolerance,samples=100]{f(x)};
\addplot[ultra thick, green,domain=\Tolerance:1-\Tolerance,samples=100]{f(x)};
\addplot[ultra thick, red,domain=1+\Tolerance:4,samples=100]{f(x)};
\end{axis}
\end{scope}
\end{tikzpicture}
\end{document}
To clarify, the \addplot
calls above are really just:
\addplot[ultra thick, blue, domain=-2.0000:-0.0001, samples=100]{f(x)};
\addplot[ultra thick, green,domain= 0.0001: 0.9999, samples=100]{f(x)};
\addplot[ultra thick, red, domain= 1.0001: 4.0000, samples=100]{f(x)};
r
inside of thecos
. Also this does not cover the cases wherex=0
andx=1
, although that should not cause too much problems. – Roelof Spijker Nov 3 '11 at 20:28