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.

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.

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

3 Answers 3

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

periodic extension

share|improve this answer
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}]

Mathematica graphics

share|improve this answer

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:

enter image description here

whereas the non-recursive one gives

enter image description here

still within 0.4 seconds.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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