1

I'm trying to play with central limit theorem using Mathematica, so I wrote the following code,

f[x_] := UnitBox[x];  
For[i = 1, i < 4, i++,  
   f[x_] := Convolve[UnitBox[z], f[z], z, x]; 
    ]
Plot[f[x],{x,-3,3}]

hoping to produce a 3-fold convolution of the original function, but only to produce the following error notifications:

$RecursionLimit::reclim2: Recursion depth of 1024 exceeded during evaluation of UnitBox[z].
$RecursionLimit::reclim2: Recursion depth of 1024 exceeded during evaluation of UnitBox[z].
$RecursionLimit::reclim2: Recursion depth of 1024 exceeded during evaluation of UnitBox[z].
General::stop: Further output of $RecursionLimit::reclim2 will be suppressed during this calculation.

but I don't know how to comprehend this. What exactly is wrong with the code?

David G. Stork
  • 41,180
  • 3
  • 34
  • 96
Jia Yiyang
  • 197
  • 1
  • 8

2 Answers2

3
g[z_] := Nest[Convolve[#, UnitBox[x], x, z] &, UnitBox[x], 3];
Plot[g[z], {z, -2, 2}]

enter image description here

And try this, which is more instructive:

g[z_] := Nest[Convolve[#, UnitTriangle[x], x, z] &, UnitTriangle[x], 3];
Plot[g[z], {z, -2, 2}]

enter image description here

David G. Stork
  • 41,180
  • 3
  • 34
  • 96
  • 1
    Better to define g with Set than with SetDelayed for this function; particularly so for the UnitTriangle version. – Edmund Apr 08 '17 at 02:57
  • Better to include option, Exclusions -> None for the plot. It joins the skip zones. – Carl Apr 08 '17 at 03:05
  • 1
    Thanks for the answer. But does the first code block really produce a 3-fold convolution of UnitBox? I would expect the result of 3-fold convolution to be a (piece-wise) quadratic function. – Jia Yiyang Apr 08 '17 at 03:11
1

The following is a more recursive solution

g[0] = UnitBox;
g[n_] := g[n] = Function[{x}, 
   Evaluate[Module[{z}, Convolve[UnitBox[z], g[n - 1][z], z, x]]]]

Plot[g[3][x], {x, -3, 3}]

enter image description here

mikado
  • 16,741
  • 2
  • 20
  • 54
  • This works very well, thanks and +1. But exactly what's wrong with my original code? – Jia Yiyang Apr 10 '17 at 17:52
  • After some testing it seems what made the difference is "Evaluate", i.e. my code would also work if I enclose the "Convolve" with an "Evaluate". But I don't really understand the operating principle here. – Jia Yiyang Apr 10 '17 at 17:59
  • When learning Mathematica, I found making it evaluate my functions in the order I intended was one of the biggest challenges. I admit that I gave you something that worked rather than trying very hard to understand what you had done. – mikado Apr 10 '17 at 18:27