2
$\begingroup$

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.

$\endgroup$
1
  • 2
    $\begingroup$ 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] $\endgroup$
    – rm -rf
    Aug 27, 2012 at 23:06

3 Answers 3

3
$\begingroup$

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

$\endgroup$
2
$\begingroup$
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

$\endgroup$
2
$\begingroup$

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.

$\endgroup$

Your Answer

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

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