3
$\begingroup$

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.

enter image description here

$\endgroup$

4 Answers 4

5
$\begingroup$
  • 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}]

enter image description here

  • The same as the Nest.
Plot[Nest[g, x, 3], {x, 0, 1}]
$\endgroup$
0
3
$\begingroup$
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

enter image description here

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

enter image description here

$\endgroup$
0
1
$\begingroup$

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}]

enter image description here

$\endgroup$
1
  • 1
    $\begingroup$ your answer is helpful to me $\endgroup$
    – river7816
    Commented Mar 22, 2023 at 2:19
0
$\begingroup$

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]]

Mathematica graphics

Mathematica graphics

Of course, I may have missed something.

$\endgroup$
1
  • $\begingroup$ thanks for your answer $\endgroup$
    – river7816
    Commented Mar 22, 2023 at 2:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.