# How do I interpret the following syntax?

I have been given some code with the following line

PeriodicExtension[g_, x_] := If[Abs[x] < Pi, g[x], PeriodicExtension[g, x - 2 Sign[x] Pi]]


I do not understand the syntax. I would appreciate if someone can explain what this code does for different values of x.

-
It simply takes any given function g and makes it one that has period 2π. It works recursively, so if x is greater than π, for instance, it subtracts 2π repeatedly till x falls within the range -π < x < π and then evaluates g[x] – R. M. Aug 27 '12 at 23:06

PeriodicExtension[g_, x_] := If[Abs[x] < Pi, g[x], PeriodicExtension[g, x - 2 Sign[x] Pi]]
g[x_] := x
Plot[PeriodicExtension[g, x], {x, 0, 4 Pi}]


-

I'm not terribly fond of the use of a recursive solution when a non-recursive approach is easier to look at, so here's a more compact and more general implementation based on this math.SE answer I wrote:

PeriodicExtension[g_, {a_?NumericQ, b_?NumericQ}, x_?NumericQ] := g[Mod[x, b - a, a]]


Here, we use Mathematica's shifted version of Mod[], Mod[x, m, h] == h + Mod[x - h, m].

To use Verde's example:

Plot[PeriodicExtension[Identity, {-π, π}, x], {x, 0, 4 π}]


-

I agree with J.M.: don't use recursion if you don't need it. I was just running a benchmark when he posted his answer.

PeriodicExtension[g_, x_] := If[Abs[x] < Pi, g[x], PeriodicExtension[g, x - 2 Sign[x] Pi]];
g[x_] := x^3
Timing[Plot[PeriodicExtension[g, x], {x, 0, 1000 Pi}]]


{ 9.922 }

PeriodicExtension[g_, x_] := g[Mod[x + Pi, 2 Pi] - Pi];
g[x_] := x^3
Timing[Plot[PeriodicExtension[g, x], {x, 0, 1000 Pi}]]


{ 0.234 }

The non-recursive version runs 42 times faster! (For an interval of 10 000 Pi even 100 times.) What's worse is that the recursion fails for large intervals. The recursive version for an interval [0, 100 000] gives this plot:

whereas the non-recursive one gives

still within 0.4 seconds.

-