I have a small toy script in Mathematica that I am trying to use to evaluate the pdf of $Y$ where $Y=X^2$, and $X$ is uniformly distributed in $[0,a]$.
The script is,
assum = {a > 0};
Subscript[P, X][x_] := If[Inequality[0, Less, x, LessEqual, a], 1/a, 0];
Y[x_] := x^2
Subscript[F, Y][y_] := Integrate[If[Y[x] <= y, 1, 0]*Subscript[P, X][x],
{x, -Infinity, Infinity}]
Subscript[P, Y][y_] := D[Subscript[F, Y][y], y]
It shows the correct form of the pdf:
In[192]:=
Simplify[Subscript[P, Y][y], assum]
Out[192]=
Piecewise[{{1/(2*a*Sqrt[y]), y > 0 && a^2 >= y}}, 0]
However, it doesn't evaluate the expression correctly:
In[194]:=
Simplify[Subscript[P, Y][a*(a/2)], assum]
During evaluation of In[194]:= General::ivar:a^2/2 is not a valid variable. >>
Out[194]=
D[1/Sqrt[2], a^2/2]
The session, in pretty printing looks like this:
Answer
$P[y]$ is defined to be $\partial_yF[y]$. If you now call $P[2]$ for example, this is translated to $\partial_2F[2]$, which of course does not make any sense.
One way to get around this behavior is not taking the derivative with respect to y
, but with respect to the first argument instead. The following example assigns f[y] to be the derivative of g[y]:
g[y_] := y^2
f[y_] := Derivative[1][g][y]
f[x]
2 x
Instead of Derivative[1][g][y]
you could also have used the shorthand notation g'[y]
. Read the explicit long version I used as an operator applied to multiple things: Derivative[1]
takes a function and calculates its first derivative with respect to the first argument. Derivative[1][g]
is that derivative (as a pure function), and Derivative[1][g][y]
is that pure function applied to a value y
.
The script above has one problem however: Every time you call f[x], it re-calculates the derivative, which can take some time if your function is more complicated and you need a lot of data points. If you use functions instead of patterns (i.e. no :=
) you can also get around this problem:
g = #^2 &
f = g'
f[x]
#1^2 &
2 #1 &
2 x
Comments
Post a Comment