Re: Mathematical expectation
- To: mathgroup at smc.vnet.net
- Subject: [mg84137] Re: [mg84113] Mathematical expectation
- From: DrMajorBob <drmajorbob at bigfoot.com>
- Date: Tue, 11 Dec 2007 06:09:24 -0500 (EST)
- References: <2929821.1197341645609.JavaMail.root@m35>
- Reply-to: drmajorbob at bigfoot.com
Add another pattern: Clear[Esp] Esp[X[_]] := Esp[X] Esp[X[_]^y_] := Esp[X^y] Esp[Esp[x_]] := Esp[x] Esp[Esp[x_]^y_] := Esp[x]^y Esp[x_ + y_] := Esp[x] + Esp[y] Esp[x_ y_] := Esp[x] Esp[y] /; FreeQ[x, y] && FreeQ[y, x] Esp[c_] := c /; FreeQ[c, X] Esp[c_ x_] := c Esp[x] /; NumberQ[c] Esp[expr_] /; expr =!= Expand@expr := Esp@Expand@expr Esp[(X[1] + X[2])^2] 2 Esp[X]^2 + 2 Esp[X^2] or, more efficient if Expand could take a lot of time... Clear[Esp] Esp[X[_]] := Esp[X] Esp[X[_]^y_] := Esp[X^y] Esp[Esp[x_]] := Esp[x] Esp[Esp[x_]^y_] := Esp[x]^y Esp[x_ + y_] := Esp[x] + Esp[y] Esp[x_ y_] := Esp[x] Esp[y] /; FreeQ[x, y] && FreeQ[y, x] Esp[c_] := c /; FreeQ[c, X] Esp[c_ x_] := c Esp[x] /; NumberQ[c] Esp[expr_] := Module[{expanded = Expand@expr}, Esp@expanded /; expanded =!= expr] Esp[(X[1] + X[2])^2] 2 Esp[X]^2 + 2 Esp[X^2] Bobby On Mon, 10 Dec 2007 19:40:00 -0600, Benoît Frénay <benoit.frenay at uclouvain.be> wrote: > Hello, > > I'm new to Mathematica and I'm trying to define a generic mathematical > expectation operator (called Esp) for i.i.d variables X[i] following the > same distribution as the variable X (i.e. Esp[X[i]] == Esp[X]). My code > is > > Esp[X[_]] := Esp[X] > Esp[X[_]^y_] := Esp[X^y] > Esp[Esp[x_]] := Esp[x] > Esp[Esp[x_]^y_] := Esp[x]^y > Esp[x_ + y_] := Esp[x] + Esp[y] > Esp[x_ y_] := Esp[x] Esp[y] /; FreeQ[x, y] && FreeQ[y, x] > Esp[c_] := c /; FreeQ[c, X] > Esp[c_ x_] := c Esp[x] /; NumberQ[c] > > But when I feed > >>> In[14]:= Esp[(X[1] + X[2])^2] > I obtain > >>> Out[14]= Esp[(X[1] + X[2])^2] > In fact, I obtain the correct answer only if I ask Mathematica to expand > the inner term: > In[16]:= Esp[Expand[(X[1] + X[2])^2]] > Out[16]= 2 Esp[X]^2 + 2 Esp[X^2] > > Where am I wrong? > > Thanks, > > Benoît Frénay > > > -- DrMajorBob at bigfoot.com