Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

Let's start from the simplest case: say I have a function $f(x)=x$, and let's say I want to define a new function (of $x$) to be its $n$-th power $(f(x))^n$. How should I write the code? I tried:

f[n_, x_] := f[n - 1, x]*f[n - 1, x]
f[1, x] = x

But the result is much different from what I wanted.

share|improve this question

marked as duplicate by Jacob Akkerboom, m_goldberg, Michael E2, ciao, Yves Klett Mar 12 '14 at 10:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 3 down vote accepted
f[x_] := x^2
f[x_, n_] := Nest[f[#] &, x, n]

f[2, 3]

share|improve this answer
@francis: Thanks for accept. Note you can write the Nest as Nest[f, x, n], I put in all the gory guts to make it (perhaps) more clear. – ciao Mar 11 '14 at 10:26
Just a note that in the original there is an underscore missing and would be better using SetDelayed, so f[1,x_]:=x. This does I think what the OP intended (though rasher's answer is better). – Ymareth Mar 11 '14 at 11:16

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