A class representing an integer probability distribution function (PDF) of a random variable.
Provides methods to add, subtract, multiply, divide, and much more between instances of PDFs, as well as visualizing the result as a bar chart.
Notice that the sum of two D6 (six-sided dice) is not equal to rolling one D6 and doubling the result.
A discrete Probability Distribution Function (PDF) in mathematics is a function
In the real world, we are often interested in the sum (or other combination) of two (or more) random variables. For example, if
A PDF is an object with just two member attributes: a dictionary of outcomes {value: weight, ...} and an integer total. All values are integers, and the probabilities are represented by an integer weight, as a fraction of total.
For example, PDF([1, 2, 3], [1, 1, 4]) represents a three-sided die (D3) where you are four times as likely to get a three compared to a two or a three. This is the same as a six-sided die with sides labeled 1, 2, 3, 3, 3, 3, which means the same PDF is obtained via PDF([1, 2, 3, 3, 3, 3]).
The following are all equivalent:
PDF({1: 1, 2: 1, 3: 4})
PDF([1, 2, 3], [1, 1, 4]) # This one is returned by __repr__
PDF([1, 2, 3, 3, 3, 3], [1, 1, 1, 1, 1, 1])
PDF([1, 2, 3, 3, 3, 3])The following operations and methods are supported:
- Binary operations:
- Arithmetic operations:
__add__,__sub__,__mul__,__floordiv__,__mod__,__pow__, and all__rvariants - Bit shift operations:
__lshift__,__rshift__,__rlshift__,__rrshift__ - Bitwise operations:
__or__,__and__,__xor__, and all__rvariants - Comparison operations:
__eq__,__ne__,__lt__,__le__,__gt__,__ge__ - Max/min operations:
max,min - Repeated sum:
summed
- Arithmetic operations:
- Unary operations:
- Sign change operations:
__abs__,__pos__,__neg__ - Casts to "booleans":
bool_,not_ - Bitwise not:
__invert__
- Sign change operations:
- Statistical properties:
mean,median,mode,equivalent
- Evaluation, sampling, introspection, plotting:
__call__,sample,as_lists,plot
If all you want is to explore the look of different probability distributions (perhaps for a new TTRPG system), there is a simple CLI (command-line interface) implemented as well. Where you would normally write in Python:
>>> A = d(20)
>>> B = d(12)
>>> (A % B + 1).plot()you can instead type in the terminal:
$ python ./pdf.py "D20 % D12 + 1"The shorthand [Dd]{n} is expanded to d({n}) and the resulting PDF is plotted. In the latter case, a title is also added with the input expression:
2D20 mod 2D10:
Middle of 3D20:
Second-smallest of 4D6:
Really uneven distribution:
The same as above, summed twice:
After three sums, it clearly approaches a normal distribution:








