]>
gitweb.michael.orlitzky.com - dead/census-tools.git/blob - src/probability/Distribution.py
3 class Distribution(object):
5 A general class representing a probability distribution.
10 components is a list of probability distributions contained
11 within this one. Right now, it's only used for sums of other
12 distributions. This might change once I have a clearer idea of
18 def __add__(self
, dist2
):
20 Add another distribution to this one. Since we don't know what
21 kind of distributions we'll be adding here, we return a new
22 copy of the most general kind.
25 d
.components
= self
.components
+ dist2
.components
31 Sample one value from the distribution.
33 if len(self
.components
) == 0:
36 return sum([component
.sample() for component
in self
.components
])
41 Evaluate the cumulative distribution function at x. Since we don't
42 know our components, there is no good way to do this. Instead, we
43 take a large number of samples, and see how many were less than or
49 for i
in range(0, trials
):
50 if self
.sample() <= x
:
53 return (float(lte_count
) / float(trials
))
57 class Uniform(Distribution
):
59 Represents a uniform probability distribution.
62 def __init__(self
, a
, b
):
64 In subclasses, we know that there are no other components. For
65 example, a uniform distribution is just made up of a uniform
66 distribution and not, say, the sum of two uniforms (because
67 that would no longer be uniform).
69 self
.components
= [self
]
70 self
.min = float(min(a
,b
))
71 self
.max = float(max(a
,b
))
75 return random
.uniform(self
.min, self
.max)
80 We can evaluate the CDF in special cases like this.
89 # x is somewhere between self.min and self.max and is equally
90 # likely to be at all points in between; so, we just compute
91 # "how far" through the interval (self.min, self.max) is as a
92 # fraction of the whole, and return that.
93 return ((x
- self
.min) / (self
.max - self
.min))