Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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, rasher, 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.

1 Answer 1

up vote 2 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. –  rasher 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.