7
$\begingroup$

I have an expression now

expr = x + x^2

what I want to do is to replace $x$ with $k\times p$ , and $x^2$ with $[k\times p + k\times(k - 1)\times p^2]$.

The sense of this opperation is that $x$ is a binomial random variable, and I want to take expection of the expression above, so I make the substituation. However, when I try to make the first substitution

expr = ReplaceAll[expr, x -> k*p]

I obtain the following output

kp + k^2 p^2

which is not what I want. So my question is what can I do to obtain the right answer?

I am new to Mathematica, so my question may seem a little bit silly. But I am still appreciate if someone could help me with that.

$\endgroup$
14
$\begingroup$

Give the replacement rules in a list:

expr /. {x^2 -> k p + k (k - 1) p^2, x -> k p}

2 k p + (-1 + k) k p^2

$\endgroup$
  • 1
    $\begingroup$ That's a good way! by the way I also tried to exchange the order expr /. {x -> k p, x^2 -> k p + k (k - 1) p^2}, and it also works! $\endgroup$ – Yuejiang_Li Sep 15 '19 at 1:50
  • $\begingroup$ @Yuejiang_Li, thank you for the accept. You are right; the rules can appear in either order in this case. $\endgroup$ – kglr Sep 15 '19 at 2:38
6
$\begingroup$

If you are calculating the expectation of an expression, use Expectation or other built-in statistics functions rather than replacements which can be error-prone (which is why you ended up asking the question).

expr = x + x^2;

Expectation[expr, x \[Distributed] BinomialDistribution[k, p]] //
 Simplify

(* k p (2 + (-1 + k) p) *)

Alternatively, using TransformedDistribution and Mean

Mean[TransformedDistribution[expr, 
   x \[Distributed] BinomialDistribution[k, p]]] // Simplify

(* k p (2 + (-1 + k) p) *)

Verifying that both results are identical,

% === %%

(* True *)
$\endgroup$
  • $\begingroup$ @Hanlon Thanks for your answer! I didn't realize mathematica can use expectation directly. But what if I only know different moments of $X$, rather than its distribution? will this method still work? $\endgroup$ – Yuejiang_Li Sep 15 '19 at 1:55
  • 1
    $\begingroup$ @Yuejiang_Li - You need the distribution to use Expectation or TransformedDistribution. If you know all of the moments, then you can derive the distribution from the moments. Or, if you know the general form of the distribution, you can determine or estimate the distribution from a few of the moments. Questions about statistics should be asked at Cross Validated. $\endgroup$ – Bob Hanlon Sep 15 '19 at 2:52
2
$\begingroup$

This is entirely equivalent to Bob's answer:

x + x^2 /. x^m_. :> Moment[BinomialDistribution[k, p], m]
   2 k p - (1 - k) k p^2
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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