How to define an arbitrary discrete probability distribution with a list of mass without warnings
Asked Answered
N

2

14

In Mathematica 8, I want to define a discrete distribution with density mass given as a list. For example,

In[1] f = ProbabilityDistribution[{2/3, 1/3}[[x]], {x, 1, 2, 1}];

This seems to work. However, this emitted a twice-repeated warning:

"Part::pspec: Part specification x is neither an integer nor a list of integers." 

Nevertheless, f seems to work correctly. This message got me thinking that there may be a better way to define the same distribution. How can I define a discrete distribution using a list but without invoking the warning?

Nerveracking answered 10/11, 2011 at 17:24 Comment(0)
G
13

Could convert the list of weights to a Piecewise, and feed that to ProbabilityDistribution.

wts = {2/3, 1/3};
toPiecewise[wts_, x_] := 
 Piecewise[MapIndexed[{#1, x == #2[[1]]} &, wts]]

In[178]:= f = 
 ProbabilityDistribution[toPiecewise[wts, x], {x, 1, 2, 1}]

Out[178]= ProbabilityDistribution[
 Piecewise[{{2/3, \[FormalX] == 1}, {1/3, \[FormalX] == 2}}, 0], 
   {\[FormalX], 1, 2, 1}]

Daniel Lichtblau

Glorification answered 10/11, 2011 at 17:46 Comment(1)
Thank you for your answer. It works, and I learned a new function MapIndexed!Nerveracking
F
17

You may want to use EmpiricalDistribution when constructing a distribution from a list of values:

empiricalDistribution = EmpiricalDistribution[{2/3, 1/3} -> {1, 2}]

and you can then use this in other statistical and visualization functions:

Plot[CDF[empiricalDistribution][x], {x, 0, 4}]

The function ProbabilityDistribution is more appropriate when you have a pdf.

Formica answered 10/11, 2011 at 18:44 Comment(2)
Thank you for your answer. I tried this, and it indeed worked! I wish I was able to accept both Daniel's and your answers.Nerveracking
Yes, both answers provide great information about building a discrete distributionKalin
G
13

Could convert the list of weights to a Piecewise, and feed that to ProbabilityDistribution.

wts = {2/3, 1/3};
toPiecewise[wts_, x_] := 
 Piecewise[MapIndexed[{#1, x == #2[[1]]} &, wts]]

In[178]:= f = 
 ProbabilityDistribution[toPiecewise[wts, x], {x, 1, 2, 1}]

Out[178]= ProbabilityDistribution[
 Piecewise[{{2/3, \[FormalX] == 1}, {1/3, \[FormalX] == 2}}, 0], 
   {\[FormalX], 1, 2, 1}]

Daniel Lichtblau

Glorification answered 10/11, 2011 at 17:46 Comment(1)
Thank you for your answer. It works, and I learned a new function MapIndexed!Nerveracking

© 2022 - 2024 — McMap. All rights reserved.