# Cannot Draw a Composite Piecewise Function

I have defined two functions: g, which is a piecewise function, and h, which is the composition of g.

g = Piecewise[{{2 x, x < 1/2}, {2*(1 - x), x > 1/2}}]
h = g@*g@*g@x


I want to plot two functions. I used the command Plot[g, {x, 0, 1}] and Plot[h, {x, 0, 1}]. The first one was successful while the second one failed.

• g should be a pure function when we use Composition, @*.
Clear[g,h];
g = Function[{x}, Piecewise[{{2 x, x < 1/2}, {2*(1 - x), x > 1/2}}]];
h = g@*g@*g;
Plot[h@x, {x, 0, 1}]


• The same as the Nest.
Plot[Nest[g, x, 3], {x, 0, 1}]

Clear["Global*"]


The arguments to functions should be explicit rather than implied.

g[x_] = Piecewise[{{2 x, x < 1/2}, {2*(1 - x), x > 1/2}}];


Use PiecewiseExpand to produce a single Piecewise

h[x_] = g@*g@*g@x // PiecewiseExpand // Simplify


Plot[h@x, {x, 0, 1}]


Using Bob Hanlon's idea with the help of Fold:

g[x_] = Piecewise[{{2 x, x < 1/2}, {2*(1 - x), x > 1/2}}];

Plot[Simplify@Fold[g@# &, ConstantArray[g[x], 3]], {x, 0, 1}]


Your problems started with defining expressions that were not Mathematica Functions.

Your problem with $$h$$ is that Mathematica Plot expects its first argument to be an expression of the plotting variable and not a bare function. Mathematica needs to know where to put the plotting variable.

g = Function[x, Piecewise[{{2*x, x < 1/2},
{2*(1 - x), x >= 1/2}}]]
h = Function[x, (g @* g @* g)[x]]
Plot[g[x], {x, 0, 1}]
Plot[h[x], {x, 0, 1}]


The outputs:

Function[x, Piecewise[{{2*x, x < 1/2}, {2*(1 - x), x >= 1/2}}]]
Function[x, (g @* g @* g)[x]]
`

Of course, I may have missed something.