boring-math-probability-distributions 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ # Copyright 2024-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Visualize probability distributions
16
+
17
+ Distributions can be compared to either sample or population data. Package
18
+ originally derived from a Udacity exercise.
19
+
20
+ - Class Dataset
21
+
22
+ - boring_math.probability_distributions.dataset
23
+
24
+ - contains either sample or population data
25
+ - generates sample/population statistics
26
+
27
+ - Abstract Class Distribution
28
+
29
+ - boring_math.probability_distributions.distribution
30
+
31
+ - represents a probability distribution
32
+
33
+ - Concrete Distributions
34
+
35
+ - boring_math.probability_distributions.distributions
36
+
37
+ """
38
+
39
+ __author__ = 'Geoffrey R. Scheller'
40
+ __copyright__ = 'Copyright (c) 2024-2025 Geoffrey R. Scheller'
41
+ __license__ = 'Apache License 2.0'
@@ -0,0 +1,218 @@
1
+ # Copyright 2024 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # This module contains software derived from Udacity® exercises.
16
+ # Udacity® (https://www.udacity.com/)
17
+ #
18
+
19
+ """Module for - managing sample/population data
20
+
21
+ - *class* DataSet: contains sample or population data
22
+ - *class* DataSets: base class for managing data sets
23
+
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import math
29
+ from collections.abc import Iterator
30
+ from typing import Never
31
+ from pythonic_fp.fptools.maybe import MayBe
32
+
33
+ __all__ = ['DataSet', 'DataSets']
34
+
35
+
36
+ class DataSet:
37
+ """Class containing sample or population data.
38
+
39
+ - all data internally stored as floats (even integer data)
40
+ - data sorted smallest to largest
41
+ - methods provided to
42
+
43
+ - read in data from a file
44
+ - computing data statistics
45
+ - add or remove data
46
+
47
+ """
48
+
49
+ @staticmethod
50
+ def read_data_from_file(file_name: str, sample: bool = False) -> MayBe[DataSet]:
51
+ """Read in data from a text file, return a DataSet object.
52
+
53
+ The text file should
54
+
55
+ - have one number (float) per line and calculate statistics
56
+
57
+ - if sample is true (default), calculate sample stats
58
+ - if sample is false, calculate population stats
59
+
60
+ - blank lines and lines beginning with '#' are ignored
61
+
62
+ """
63
+ data: list[float] = []
64
+ try:
65
+ with open(file_name) as file:
66
+ line = file.readline()
67
+ while line:
68
+ if line[0] != '#' and line[0] != chr(ord('\n')):
69
+ data.append(float(line))
70
+ line = file.readline()
71
+ else:
72
+ line = file.readline()
73
+ except ValueError as esc:
74
+ raise RuntimeError('Error parsing "{}"'.format(file_name)) from esc
75
+ except FileNotFoundError as esc:
76
+ raise RuntimeError(
77
+ 'Can\'t find file data file "{}"'.format(file_name)
78
+ ) from esc
79
+ except PermissionError as esc:
80
+ raise RuntimeError(
81
+ 'No read permissiona for data file "{}"'.format(file_name)
82
+ ) from esc
83
+ else:
84
+ return MayBe(DataSet(*data, sample=sample))
85
+
86
+ def __init__(self, *data: int | float, sample: bool = False) -> None:
87
+ self._sample: bool = sample
88
+ self._data = list(map(lambda d: float(d), data))
89
+ self._size = len(self._data)
90
+ self._data.sort()
91
+ self._calculate_stats()
92
+
93
+ def _calculate_stats(self) -> None:
94
+ """Calculate data statistics"""
95
+ self._mean = self._calculate_mean()
96
+ self._stdev = self._calculate_stdev()
97
+ self._quartiles = self._calculate_quartiles()
98
+ self._median = self._quartiles.map(lambda t: t[1])
99
+
100
+ def _calculate_mean(self) -> MayBe[float]:
101
+ """Calculate the mean of the data set, if it exists."""
102
+ if self:
103
+ return MayBe(sum(self._data) / self._size)
104
+ else:
105
+ return MayBe()
106
+
107
+ def _calculate_stdev(self) -> MayBe[float]:
108
+ """From the data set, calculate & return the stdev if it exists.
109
+
110
+ - If sample is True, calculate a sample standard deviation
111
+ - If sample is False, calculate a population standard deviation
112
+
113
+ """
114
+ data = self._data
115
+ n = self._size
116
+ if self._mean:
117
+ mean = self._mean.get()
118
+ if self._sample:
119
+ if n > 1:
120
+ return MayBe(math.sqrt(sum(((x - mean) ** 2 for x in data)) / (n - 1)))
121
+ else:
122
+ if n > 0:
123
+ return MayBe(math.sqrt(sum(((x - mean) ** 2 for x in data)) / n))
124
+ return MayBe()
125
+
126
+ def _calculate_quartiles(self) -> MayBe[tuple[float, float, float]]:
127
+ """Calculate first, second (median), and third quartiles
128
+
129
+ Using the "trimmed mid-range" of the data.
130
+
131
+ """
132
+ n = self._size
133
+ data = self._data
134
+ if data:
135
+ q = n // 2
136
+ r = q // 2
137
+
138
+ if n % 2 == 0:
139
+ second = (data[q - 1] + data[q]) / 2.0
140
+ lower_half = data[:q]
141
+ upper_half = data[q:]
142
+ if q % 2 == 0:
143
+ first = (lower_half[r - 1] + lower_half[r]) / 2.0
144
+ third = (upper_half[r - 1] + upper_half[r]) / 2.0
145
+ else:
146
+ first = lower_half[(r)]
147
+ third = upper_half[(r)]
148
+ else:
149
+ second = data[q]
150
+ lower_half = data[:q]
151
+ upper_half = data[q:]
152
+ if q % 2 == 0:
153
+ first = (lower_half[r - 1] + lower_half[r]) / 2.0
154
+ third = (upper_half[r - 1] + upper_half[r]) / 2.0
155
+ else:
156
+ first = lower_half[(r)]
157
+ third = upper_half[(r)]
158
+
159
+ return MayBe((first, second, third))
160
+ else:
161
+ return MayBe()
162
+
163
+ def __bool__(self) -> bool:
164
+ return self._size > 0
165
+
166
+ def __iter__(self) -> Iterator[float]:
167
+ return iter(self._data)
168
+
169
+ def is_sample(self) -> bool:
170
+ return self._sample
171
+
172
+ def is_population(self) -> bool:
173
+ return not self._sample
174
+
175
+ def has_mean(self) -> bool:
176
+ return bool(self._mean)
177
+
178
+ def has_median(self) -> bool:
179
+ return bool(self._median)
180
+
181
+ def has_stdev(self) -> bool:
182
+ return bool(self._stdev)
183
+
184
+ def has_quartiles(self) -> bool:
185
+ return bool(self._quartiles)
186
+
187
+ @property
188
+ def mean(self) -> float | Never:
189
+ return self._mean.get()
190
+
191
+ @property
192
+ def median(self) -> float | Never:
193
+ return self._median.get()
194
+
195
+ @property
196
+ def stdev(self) -> float | Never:
197
+ return self._stdev.get()
198
+
199
+ @property
200
+ def quartiles(self) -> tuple[float, float, float] | Never:
201
+ return self._quartiles.get()
202
+
203
+
204
+ class DataSets:
205
+ """Base class for managing data sets.
206
+
207
+ - data sets can be samples or populations
208
+ - methods provided to
209
+
210
+ - add or remove data sets
211
+ - plot data sets
212
+
213
+ - how they are related to each other is up to the user of the class
214
+
215
+ """
216
+
217
+ def __init__(self) -> None:
218
+ self.data_sets: list[DataSet] = []
@@ -0,0 +1,105 @@
1
+ # Copyright 2024 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # This module contains software derived from Udacity® exercises.
16
+ # Udacity® (https://www.udacity.com/)
17
+ #
18
+
19
+ """Module boring_math.probability_distributions.distribution
20
+
21
+ Providing base classes to visualize probability distributions.
22
+
23
+ - *class* ContDist: base class to visualize continuous pd
24
+ - *class* DiscreteDist: base class to visualize discrete pd
25
+
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from abc import ABC, abstractmethod
31
+ from typing import Self, Never
32
+ import matplotlib.pyplot as plt
33
+ from .datasets import DataSet
34
+ from pythonic_fp.fptools.maybe import MayBe
35
+
36
+ __all__ = ['ContDist', 'DiscreteDist']
37
+
38
+
39
+ class ContDist(ABC):
40
+ """Base class to visualize continuous probability distributions."""
41
+
42
+ def __init__(self) -> None:
43
+ self.population: MayBe[DataSet] = MayBe()
44
+ self.samples: list[DataSet] = []
45
+
46
+ @abstractmethod
47
+ def pdf(self, kf: float) -> float:
48
+ """Probability distribution function."""
49
+ ...
50
+
51
+ @abstractmethod
52
+ def cdf(self, kf: float) -> float:
53
+ """Cumulative distribution function."""
54
+ ...
55
+
56
+ @abstractmethod
57
+ def __add__(self, other: Self) -> Self | Never:
58
+ """Add together two compatible distributions."""
59
+ ...
60
+
61
+
62
+ # def plot_bar_data(self) -> None: ...
63
+
64
+ # def barplot_pdf(self) -> tuple[list[int], List[float]]:
65
+ # """Function to plot the pdf of the binomial distribution.
66
+ #
67
+ # Returns:
68
+ # list: x values used for the pdf plot
69
+ # list: y values used for the pdf plot
70
+ # """
71
+ # pdf: Callable[[int], float] = lambda ii: self.pdf(float(ii))
72
+ #
73
+ # xs: list[int] = list(range(self.n + 1))
74
+ # ys: list[float] = list(map(pdf, range(self.n + 1)))
75
+ #
76
+ # plt.bar(list(str(x) for x in xs), ys, color ='maroon', width = 0.4)
77
+ # plt.title('Probability Density of Success')
78
+ # plt.xlabel('Successes for {} trials'.format(self.n))
79
+ # plt.ylabel('Probability')
80
+ # plt.show()
81
+ #
82
+ # return xs, ys
83
+
84
+
85
+ class DiscreteDist(ABC):
86
+ """Base class to visualize discrete probability distributions."""
87
+
88
+ def __init__(self) -> None:
89
+ self.population: MayBe[DataSet] = MayBe()
90
+ self.samples: list[DataSet] = []
91
+
92
+ @abstractmethod
93
+ def pdf(self, kf: float) -> float:
94
+ """Probability distribution function."""
95
+ ...
96
+
97
+ @abstractmethod
98
+ def cdf(self, kf: float) -> float:
99
+ """Cumulative distribution function."""
100
+ ...
101
+
102
+ @abstractmethod
103
+ def __add__(self, other: Self) -> Self | Never:
104
+ """Add together two compatible distributions."""
105
+ ...
@@ -0,0 +1,27 @@
1
+ # Copyright 2024-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Continuous Distributions
17
+ ========================
18
+
19
+ - Normal boring_math.probability_distributions.distributions.normal
20
+ - Uniform boring_math.probability_distributions.distributions.uniform
21
+
22
+ Discrete Distributions
23
+ ======================
24
+
25
+ - Binomial: boring_math.probability_distributions.distributions.binomial
26
+
27
+ """
@@ -0,0 +1,166 @@
1
+ # Copyright 2024 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # This module contains software derived from Udacity® exercises.
16
+ # Udacity® (https://www.udacity.com/)
17
+ #
18
+
19
+ """
20
+ Binomial Distribution
21
+ ---------------------
22
+
23
+ A binomial distribution class, derived from a Udacity
24
+ exercise template.
25
+
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from typing import Never
31
+ from math import comb, sqrt
32
+ import matplotlib.pyplot as plt
33
+ from ..datasets import DataSet
34
+ from ..distribution import DiscreteDist
35
+
36
+ __all__ = ['Binomial']
37
+
38
+
39
+ class Binomial(DiscreteDist):
40
+ """Class for visualizing data as Binomial distributions.
41
+
42
+ The binomial distribution represents the number of events with
43
+ probability ``p`` happening in ``n`` numbers of trials.
44
+
45
+ Attributes (some inherited):
46
+
47
+ - ``mean`` (float) representing the mean value of the distribution
48
+ - ``stdev`` (float) representing the standard deviation of the distribution
49
+ - ``data`` extracted from a data file (taken to be a population)
50
+ - ``p`` (float) representing the probability of an event occurring
51
+ - ``n`` (int) the total number of trials
52
+
53
+ """
54
+
55
+ def __init__(self, p: float = 0.5, n: int = 20):
56
+ if not (0.0 <= p <= 1.0) or n < 1:
57
+ msg1 = 'For a binomial distribution, '
58
+ msg2 = msg3 = ''
59
+ if not (0.0 <= p <= 1.0):
60
+ msg2 = '0 <= p <= 1'
61
+ if n < 0:
62
+ msg3 = 'the number of trials n must be non-negative'
63
+ if msg2 and msg3:
64
+ msg = msg1 + msg2 + ' and ' + msg3 + '.'
65
+ else:
66
+ msg = msg1 + msg2 + msg3 + '.'
67
+ raise ValueError(msg)
68
+
69
+ self.p: float = p
70
+ self.n: int = n
71
+
72
+ super().__init__()
73
+
74
+ def pdf(self, kf: float) -> float:
75
+ """Binomial probability distribution function."""
76
+ k = int(kf)
77
+ n = self.n
78
+ p = self.p
79
+ return comb(n, k) * (p**k) * (1 - p) ** (n - k)
80
+
81
+ def cdf(self, kf: float) -> float:
82
+ """Binomial cumulative probability distribution function."""
83
+ return sum((self.pdf(ii) for ii in range(int(kf))))
84
+
85
+ def calculate_mean(self) -> float:
86
+ """Calculate the mean from p and n"""
87
+ n = self.n
88
+ p = self.p
89
+ self.mean = mean = n * p
90
+ return mean
91
+
92
+ def calculate_stdev(self) -> float:
93
+ """Calculate the standard deviation using p and n"""
94
+ n = self.n
95
+ p = self.p
96
+ self.stdev = stdev = sqrt(n * p * (1 - p))
97
+ return stdev
98
+
99
+ def replace_stats_from_dataset(self, dset: DataSet) -> tuple[float, int]:
100
+ """Function to calculate p and n from a data set.
101
+
102
+ Where the read in data set is taken as the population.
103
+ """
104
+ if dset:
105
+ self.n = n = dset._size
106
+ self.p = p = sum(dset._data) / n
107
+ self.mean = n * p
108
+ self.stdev = sqrt(n * p * (1 - p))
109
+ return self.p, self.n
110
+
111
+ def plot_bar_data(self) -> None:
112
+ """Produce a bar-graph of the data using the matplotlib pyplot library."""
113
+ n = self.n
114
+ p = self.p
115
+
116
+ fig, axis = plt.subplots()
117
+ axis.bar(('0', '1'), (n * (1 - p), n * p), color='maroon', width=0.6)
118
+ axis.set_title('Failures and Successes for a sample of {}'.format(n))
119
+ axis.set_xlabel('prob = {}, n = {}'.format(p, n))
120
+ axis.set_ylabel('Sample Count')
121
+ plt.show()
122
+
123
+ def plot_bar_pdf(self) -> tuple[list[int], list[float]]:
124
+ """Function to plot the pdf of the binomial distribution.
125
+
126
+ :return:
127
+ A tuple containing
128
+
129
+ - list[int]: x values used for the pdf plot
130
+ - list[float]: y values used for the pdf plot
131
+
132
+ """
133
+
134
+ def pdf(ii: int) -> float:
135
+ return self.pdf(float(ii))
136
+
137
+ xs: list[int] = list(range(self.n + 1))
138
+ ys: list[float] = list(map(pdf, range(self.n + 1)))
139
+
140
+ plt.bar(list(str(x) for x in xs), ys, color='maroon', width=0.4)
141
+ plt.title('Probability Density of Success')
142
+ plt.xlabel('Successes for {} trials'.format(self.n))
143
+ plt.ylabel('Probability')
144
+ plt.show()
145
+
146
+ return xs, ys
147
+
148
+ def __add__(self, other: Binomial) -> Binomial | Never:
149
+ """Add together two Binomial distributions with equal p."""
150
+ if type(other) is not Binomial:
151
+ msg = 'A binomial distribution cannot be added to a {}'
152
+ msg = msg.format(type(other))
153
+ raise TypeError(msg)
154
+ if self.p != other.p:
155
+ msg = 'p values are not equal'
156
+ raise ValueError(msg)
157
+
158
+ return Binomial(self.p, self.n + other.n)
159
+
160
+ def __repr__(self) -> str:
161
+ repr_str = 'Binomial({}, {})'
162
+ return repr_str.format(self.p, self.n)
163
+
164
+ def __str__(self) -> str:
165
+ user_str = 'mean {}, standard deviation {}, p {}, n {}'
166
+ return user_str.format(self.mean, self.stdev, self.p, self.n)
@@ -0,0 +1,128 @@
1
+ # Copyright 2024-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # This module contains software derived from Udacity® exercises.
16
+ # Udacity® (https://www.udacity.com/)
17
+ #
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Never
22
+ from math import erf, exp, pi, sqrt
23
+ import matplotlib.pyplot as plt
24
+ from ..datasets import DataSet
25
+ from ..distribution import ContDist
26
+
27
+ __all__ = ['Normal']
28
+
29
+
30
+ class Normal(ContDist):
31
+ """Class for visualizing Normal distributions.
32
+
33
+ .. note::
34
+ The Normal, also called Gaussian, distribution is a continuous probability
35
+ distribution with probability density function
36
+
37
+ f(x) = (1/√(2πσ²))exp(-(x-μ)²/2σ²)
38
+ where
39
+ μ = mu = mean value of the distribution
40
+ σ = sigma = standard deviation of the distribution
41
+
42
+ """
43
+
44
+ def __init__(self, mu: float = 0.0, sigma: float = 1.0):
45
+ if sigma <= 0:
46
+ msg = 'For a Normal distribution, sigma must be greater than 0'
47
+ raise ValueError(msg)
48
+
49
+ self.mu = mu
50
+ self.sigma = sigma
51
+
52
+ super().__init__()
53
+
54
+ def __repr__(self) -> str:
55
+ repr_str = 'mean {}, standard deviation {}'
56
+ return repr_str.format(self.mu, self.sigma)
57
+
58
+ def pdf(self, x: float) -> float:
59
+ """Normal probability distribution function."""
60
+ c = 1.0 / sqrt(2 * pi)
61
+ mu = self.mu
62
+ sigma = self.sigma
63
+ return (c / sigma) * exp(-0.5 * ((x - mu) / sigma) ** 2)
64
+
65
+ def cdf(self, x: float) -> float:
66
+ """Normal cumulative probability distribution function."""
67
+ mu = self.mu
68
+ c = self.sigma * sqrt(2)
69
+ return 0.5 * (1 + erf((x - mu) / c))
70
+
71
+ def __add__(self, other: Normal) -> Normal | Never:
72
+ """Add together two Normal distributions."""
73
+ if type(other) is not Normal:
74
+ msg = 'A Normal distribution cannot be added to a {}'
75
+ msg = msg.format(type(other))
76
+ raise TypeError(msg)
77
+
78
+ return Normal(self.mu + other.mu, sqrt(self.sigma**2 + other.sigma**2))
79
+
80
+
81
+ # def plot_histogram_data(self) -> None:
82
+ # """Produce a histogram of the data using the matplotlib pyplot library."""
83
+ # fig, axis = plt.subplots()
84
+ # axis.hist(self.data)
85
+ # axis.set_title('Histogram of Data')
86
+ # axis.set_xlabel('Data')
87
+ # axis.set_ylabel('Count')
88
+ # plt.show()
89
+
90
+ # def plot_histogram_pdf(self, n_spaces: int = 100) -> tuple[list[float], list[float]]:
91
+ # """Method to plot the normalized histogram of the data and a plot of the
92
+ # probability density function along the same range
93
+
94
+ # Args:
95
+ # n_spaces (int): number of data points to plot
96
+
97
+ # Returns:
98
+ # list: x values used for the pdf plot
99
+ # list: y values used for the pdf plot
100
+ # """
101
+ # data = self.data
102
+ # pdf = self.pdf
103
+
104
+ # if len(data) == 0:
105
+ # return [], []
106
+
107
+ # min_x, max_x = min(data), max(data)
108
+ # if min_x == max_x:
109
+ # min_x, max_x = min_x - 0.5, max_x + 0.5
110
+ # interval = (max_x - min_x)/n_spaces
111
+
112
+ # x: list[float] = list((min_x + interval*n for n in range(n_spaces + 1)))
113
+ # y: list[float] = list((pdf(x) for x in x))
114
+
115
+ # # make the plots
116
+ # fig, axes = plt.subplots(2,sharex=True)
117
+ # fig.subplots_adjust(hspace=.5)
118
+ # axes[0].hist(data, density=True)
119
+ # axes[0].set_title('Normed Histogram of Data')
120
+ # axes[0].set_ylabel('Density')
121
+
122
+ # axes[1].plot(x, y)
123
+ # axes[1].set_title('Normal Distribution for the\n Sample Mean and Sample Standard Deviation')
124
+ # axes[1].set_xlabel('sample mean = {}, sample stdev = {}'.format(self.mean, self.stdev))
125
+ # axes[1].set_ylabel('Density')
126
+ # plt.show()
127
+
128
+ # return x, y
@@ -0,0 +1,100 @@
1
+ # Copyright 2024-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # This module contains software derived from Udacity® exercises.
16
+ # Udacity® (https://www.udacity.com/)
17
+ #
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Never
22
+ from math import sqrt
23
+ import matplotlib.pyplot as plt
24
+ from ..datasets import DataSet
25
+ from ..distribution import ContDist
26
+
27
+ __all__ = ['Uniform']
28
+
29
+
30
+ class Uniform(ContDist):
31
+ """Class for visualizing Normal distributions.
32
+
33
+ .. note::
34
+ The Uniform distribution is a continuous probability
35
+ distribution with probability density function
36
+
37
+ f(x) = 1/(b-a) for a < x < b
38
+ f(x) = 0 otherwise
39
+ where
40
+ μ = mu = (a+b)/2 = mean value
41
+ σ = sigma = (b-a)/2√3 = standard deviation
42
+
43
+ """
44
+
45
+ def __init__(self, a: float = 0.0, b: float = 1.0):
46
+ if b <= a:
47
+ msg = 'For a Uniorm distribution, b > a'
48
+ raise ValueError(msg)
49
+
50
+ self.mu = (a + b) / 2
51
+ self.sigma = (b - a) / (2 * sqrt(3))
52
+ self.a = a
53
+ self.b = b
54
+
55
+ super().__init__()
56
+
57
+ def __repr__(self) -> str:
58
+ repr_str = 'mean {}, standard deviation {}'
59
+ return repr_str.format(self.mu, self.sigma)
60
+
61
+ def pdf(self, x: float) -> float:
62
+ """Uniform probability distribution function."""
63
+ a = self.a
64
+ b = self.b
65
+ c = 1.0 / (b - a)
66
+ if a < x < b:
67
+ return c
68
+ else:
69
+ return 0
70
+
71
+ def cdf(self, x: float) -> float:
72
+ """Uniform cumulative probability distribution function."""
73
+ a = self.a
74
+ b = self.b
75
+ c = 1.0 / (b - a)
76
+ if x <= a:
77
+ return 0
78
+ elif x < b:
79
+ return c * (x - a)
80
+ else:
81
+ return 1
82
+
83
+ def __add__(self, other: Uniform) -> Uniform | Never:
84
+ """Add together two compatible Uniform distributions."""
85
+ if type(other) is not Uniform:
86
+ msg = 'A Uniform distribution cannot be added to a {}'
87
+ msg = msg.format(type(other))
88
+ raise TypeError(msg)
89
+
90
+ if other.a <= self.a <= other.b:
91
+ a = other.a
92
+ b = max(self.b, other.b)
93
+ elif self.a <= other.a <= self.b:
94
+ a = self.a
95
+ b = max(self.b, other.b)
96
+ else:
97
+ msg = 'Intervals of Uniform distributions must overlap'
98
+ raise ValueError(msg)
99
+
100
+ return Uniform(b, a)
File without changes
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: boring-math-probability-distributions
3
+ Version: 0.8.0
4
+ Summary: Visualize probability distributions
5
+ Keywords: distribution,probability distributions,sample data
6
+ Author-email: "Geoffrey R. Scheller" <geoffrey@scheller.com>
7
+ Requires-Python: >=3.12
8
+ Description-Content-Type: text/x-rst
9
+ Classifier: Development Status :: 2 - Pre-Alpha
10
+ Classifier: Framework :: Pytest
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Typing :: Typed
17
+ License-File: LICENSE
18
+ Requires-Dist: matplotlib >= 3.10.1
19
+ Requires-Dist: pythonic-fp.fptools >= 5.0.0
20
+ Requires-Dist: pytest>=8.4.1 ; extra == "test"
21
+ Project-URL: Changelog, https://github.com/grscheller/boring-math-probability-distributions/blob/main/CHANGELOG.md
22
+ Project-URL: Documentation, https://grscheller.github.io/boring-math/probability-distributions/development/build/html/releases.html
23
+ Project-URL: Homepage, https://github.com/grscheller/boring-math/blob/main/README.md
24
+ Project-URL: Source, https://github.com/grscheller/boring-math-probability-distributions
25
+ Provides-Extra: test
26
+
27
+ Boring Math - Probability Distributions
28
+ =======================================
29
+
30
+ PyPI project
31
+ `boring-math-probability-distributions
32
+ <https://pypi.org/project/boring-math-probability-distributions>`_.
33
+
34
+ Package to generate and visualize probability distributions.
35
+
36
+ - continuous distributions:
37
+
38
+ - Normal: ``boring_math.probability_distributions.normal``
39
+ - Uniform: ``boring_math.probability_distributions.uniform``
40
+
41
+ - discrete distributions:
42
+
43
+ - Binomial: ``boring_math.probability_distributions.binomial``
44
+
45
+ This PyPI project is part of of the grscheller
46
+ `boring-math namespace projects
47
+ <https://github.com/grscheller/boring-math/blob/main/README.md>`_
48
+
49
+ Documentation
50
+ -------------
51
+
52
+ Documentation for this project is hosted on
53
+ `GitHub Pages
54
+ <https://grscheller.github.io/boring-math/probability-distributions/development/build/html/>`_.
55
+
56
+ Copyright and License
57
+ ---------------------
58
+
59
+ Copyright (c) 2023-2025 Geoffrey R. Scheller. Licensed under the Apache
60
+ License, Version 2.0. See the LICENSE file for details.
61
+
@@ -0,0 +1,13 @@
1
+ boring_math/probability_distributions/__init__.py,sha256=PniHFxGul_qgsgXSg3G-RVuGP7qEm0bEWO7LISnFVw4,1280
2
+ boring_math/probability_distributions/datasets.py,sha256=fIpOoWv4DxqxrFCA0w8bsINHt1qK3Nt6sTPXQnlx_x0,6702
3
+ boring_math/probability_distributions/distribution.py,sha256=PerGpnJ4AjfGm0nK0sRC1QFPVNScDf4_hTBjQjZuKmc,3161
4
+ boring_math/probability_distributions/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ boring_math/probability_distributions/distributions/__init__.py,sha256=0CJeUhnFLEceC_TgoEcS1hcHk0VMUukHv6hnx_QXUHA,911
6
+ boring_math/probability_distributions/distributions/binomial.py,sha256=rBNNeFnq5eSyVTCEl8UNTRjF1G0067kYYrDJuX9Kic4,5408
7
+ boring_math/probability_distributions/distributions/normal.py,sha256=2H0zMRj6WieTNsi0bsbkFxdXKnGCbNQRyOcV5rNwP2M,4261
8
+ boring_math/probability_distributions/distributions/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ boring_math/probability_distributions/distributions/uniform.py,sha256=wzcV7GcCSxc5idTVkfPbChoVBjL586wge9PlbkOBS98,2944
10
+ boring_math_probability_distributions-0.8.0.dist-info/licenses/LICENSE,sha256=psuoW8kuDP96RQsdhzwOqi6fyWv0ct8CR6Jr7He_P_k,10173
11
+ boring_math_probability_distributions-0.8.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
12
+ boring_math_probability_distributions-0.8.0.dist-info/METADATA,sha256=jo0L9tYqnmCfPP951If0F4ljt2lQa1JtL1L1XHDwvAM,2278
13
+ boring_math_probability_distributions-0.8.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS