Haleshot commited on
Commit
de962bf
·
unverified ·
1 Parent(s): b0625d6

Add `Continuous Distributions` notebook. It covers key concepts such as Probability Density Functions (PDFs), (CDFs), and their properties. Interactive visualizations allow users to explore different distributions (uniform, triangular, exponential).

Browse files
probability/16_continuous_distribution.py ADDED
@@ -0,0 +1,979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "marimo",
5
+ # "altair==5.5.0",
6
+ # "matplotlib==3.10.1",
7
+ # "numpy==2.2.4",
8
+ # "scipy==1.15.2",
9
+ # "sympy==1.13.3",
10
+ # "wigglystuff==0.1.10",
11
+ # "polars==1.26.0",
12
+ # ]
13
+ # ///
14
+
15
+ import marimo
16
+
17
+ __generated_with = "0.11.26"
18
+ app = marimo.App(width="medium")
19
+
20
+
21
+ @app.cell(hide_code=True)
22
+ def _(mo):
23
+ mo.md(
24
+ r"""
25
+ # Continuous Distributions
26
+
27
+ _This notebook is a computational companion to ["Probability for Computer Scientists"](https://chrispiech.github.io/probabilityForComputerScientists/en/part2/continuous/), by Stanford professor Chris Piech._
28
+
29
+ So far, all the random variables we've explored have been discrete, taking on only specific values (usually integers). Now we'll move into the world of **continuous random variables**, which can take on any real number value. Continuous random variables are used to model measurements with arbitrary precision like height, weight, time, and many natural phenomena.
30
+ """
31
+ )
32
+ return
33
+
34
+
35
+ @app.cell(hide_code=True)
36
+ def _(mo):
37
+ mo.md(
38
+ r"""
39
+ ## From Discrete to Continuous
40
+
41
+ To make the transition from discrete to continuous random variables, let's start with a thought experiment:
42
+
43
+ > Imagine you're running to catch a bus. You know you'll arrive at 2:15pm, but you don't know exactly when the bus will arrive. You want to model the bus arrival time (in minutes past 2pm) as a random variable $T$ so you can calculate the probability that you'll wait more than five minutes: $P(15 < T < 20)$.
44
+
45
+ This immediately highlights a key difference from discrete distributions. For discrete distributions, we described the probability that a random variable takes on exact values. But this doesn't make sense for continuous values like time.
46
+
47
+ For example:
48
+
49
+ - What's the probability the bus arrives at exactly 2:17pm and 12.12333911102389234 seconds?
50
+ - What's the probability of a child being born weighing exactly 3.523112342234 kilograms?
51
+
52
+ These questions don't have meaningful answers because real-world measurements can have infinite precision. The probability of a continuous random variable taking on any specific exact value is actually zero!
53
+
54
+ ### Visualizing the Transition
55
+
56
+ Let's visualize this transition from discrete to continuous:
57
+ """
58
+ )
59
+ return
60
+
61
+
62
+ @app.cell(hide_code=True)
63
+ def _(fig_to_image, mo, np, plt):
64
+ def create_discretization_plot():
65
+ fig, axs = plt.subplots(1, 3, figsize=(15, 5))
66
+
67
+ # values from 0 to 30 minutes
68
+ x = np.linspace(0, 30, 1000)
69
+
70
+ # Triangular distribution peaked at 15 minutes)
71
+ y = np.where(x <= 15, x/15, (30-x)/15)
72
+ y = y / np.trapezoid(y, x) # Normalize
73
+
74
+ # 5-minute chunks (first plot)
75
+ bins = np.arange(0, 31, 5)
76
+ hist, _ = np.histogram(x, bins=bins, weights=y)
77
+ width = bins[1] - bins[0]
78
+ axs[0].bar(bins[:-1], hist * width, width=width, alpha=0.7,
79
+ color='royalblue', edgecolor='black')
80
+ axs[0].set_xlim(0, 30)
81
+ axs[0].set_title('5-Minute Intervals')
82
+ axs[0].set_xlabel('Minutes past 2pm')
83
+ axs[0].set_ylabel('Probability')
84
+
85
+ # 15-20 minute range more prominent
86
+ axs[0].bar([15], hist[3] * width, width=width, alpha=0.7,
87
+ color='darkorange', edgecolor='black')
88
+
89
+ # 2.5-minute chunks (second plot)
90
+ bins = np.arange(0, 31, 2.5)
91
+ hist, _ = np.histogram(x, bins=bins, weights=y)
92
+ width = bins[1] - bins[0]
93
+ axs[1].bar(bins[:-1], hist * width, width=width, alpha=0.7,
94
+ color='royalblue', edgecolor='black')
95
+ axs[1].set_xlim(0, 30)
96
+ axs[1].set_title('2.5-Minute Intervals')
97
+ axs[1].set_xlabel('Minutes past 2pm')
98
+
99
+ # Make 15-20 minute range more prominent
100
+ highlight_indices = [6, 7]
101
+ for idx in highlight_indices:
102
+ axs[1].bar([bins[idx]], hist[idx] * width, width=width, alpha=0.7,
103
+ color='darkorange', edgecolor='black')
104
+
105
+ # Continuous distribution (third plot)
106
+ axs[2].plot(x, y, 'royalblue', linewidth=2)
107
+ axs[2].set_xlim(0, 30)
108
+ axs[2].set_title('Continuous Distribution')
109
+ axs[2].set_xlabel('Minutes past 2pm')
110
+ axs[2].set_ylabel('Probability Density')
111
+
112
+ # Highlight the AUC between 15 and 20
113
+ mask = (x >= 15) & (x <= 20)
114
+ axs[2].fill_between(x[mask], y[mask], color='darkorange', alpha=0.7)
115
+
116
+ # Mark 15-20 minute interval
117
+ for ax in axs:
118
+ ax.axvline(x=15, color='red', linestyle='--', alpha=0.5)
119
+ ax.axvline(x=20, color='red', linestyle='--', alpha=0.5)
120
+ ax.set_xticks([0, 5, 10, 15, 20, 25, 30])
121
+ ax.grid(alpha=0.3)
122
+
123
+ plt.tight_layout()
124
+ plt.gca()
125
+ return fig
126
+
127
+ # Plot creation & conversion
128
+ _fig = create_discretization_plot()
129
+ _img = mo.image(fig_to_image(_fig), width="100%")
130
+
131
+ _explanation = mo.md(
132
+ r"""
133
+ The figure above illustrates our transition from discrete to continuous thinking:
134
+
135
+ - **Left**: Time divided into 5-minute chunks, where the probability of the bus arriving between 15-20 minutes (highlighted in orange) is a single value.
136
+ - **Center**: Time divided into finer 2.5-minute chunks, where the 15-20 minute range consists of two chunks.
137
+ - **Right**: In the limit, we get a continuous probability density function where the probability is the area under the curve between 15 and 20 minutes.
138
+
139
+ As we make our chunks smaller and smaller, we eventually arrive at a smooth function that gives us the probability density at each point.
140
+ """
141
+ )
142
+
143
+ mo.vstack([_img, _explanation])
144
+ return (create_discretization_plot,)
145
+
146
+
147
+ @app.cell(hide_code=True)
148
+ def _(mo):
149
+ mo.md(
150
+ r"""
151
+ ## Probability Density Functions
152
+
153
+ In the world of discrete random variables, we used **Probability Mass Functions (PMFs)** to describe the probability of a random variable taking on specific values. In the continuous world, we need a different approach.
154
+
155
+ For continuous random variables, we use a **Probability Density Function (PDF)** which defines the relative likelihood that a random variable takes on a particular value. We traditionally denote the PDF with the symbol $f$ and write it as:
156
+
157
+ $$f(X=x) \quad \text{or simply} \quad f(x)$$
158
+
159
+ Where the lowercase $x$ implies that we're talking about the relative likelihood of a continuous random variable which is the uppercase $X$.
160
+
161
+ ### Key Properties of PDFs
162
+
163
+ A **Probability Density Function (PDF)** $f(x)$ for a continuous random variable $X$ has these key properties:
164
+
165
+ 1. The probability that $X$ takes a value in the interval $[a, b]$ is:
166
+
167
+ $$P(a \leq X \leq b) = \int_a^b f(x) \, dx$$
168
+
169
+ 2. The PDF must be non-negative everywhere:
170
+
171
+ $$f(x) \geq 0 \text{ for all } x$$
172
+
173
+ 3. The total probability must sum to 1:
174
+
175
+ $$\int_{-\infty}^{\infty} f(x) \, dx = 1$$
176
+
177
+ 4. The probability that $X$ takes any specific exact value is 0:
178
+
179
+ $$P(X = a) = \int_a^a f(x) \, dx = 0$$
180
+
181
+ This last property highlights a key difference from discrete distributions: the probability of a continuous random variable taking on an exact value is always 0. Probabilities only make sense when talking about ranges of values.
182
+
183
+ ### Caution: Density ≠ Probability
184
+
185
+ A common misconception is to think of $f(x)$ as a probability. It is instead a **probability density**, representing probability per unit of $x$. The values of $f(x)$ can actually exceed 1, as long as the total area under the curve equals 1.
186
+
187
+ The interpretation of $f(x)$ is only meaningful when:
188
+
189
+ 1. We integrate over a range to get a probability, or
190
+ 2. We compare densities at different points to determine relative likelihoods.
191
+ """
192
+ )
193
+ return
194
+
195
+
196
+ @app.cell(hide_code=True)
197
+ def _(TangleSlider, mo):
198
+ # Create sliders for a and b
199
+ a_slider = mo.ui.anywidget(TangleSlider(
200
+ amount=1,
201
+ min_value=0,
202
+ max_value=5,
203
+ step=0.1,
204
+ digits=1
205
+ ))
206
+
207
+ b_slider = mo.ui.anywidget(TangleSlider(
208
+ amount=3,
209
+ min_value=0,
210
+ max_value=5,
211
+ step=0.1,
212
+ digits=1
213
+ ))
214
+
215
+ # Distribution selector
216
+ distribution_radio = mo.ui.radio(
217
+ options=["uniform", "triangular", "exponential"],
218
+ value="uniform",
219
+ label="Distribution Type"
220
+ )
221
+
222
+ # Controls layout
223
+ _controls = mo.vstack([
224
+ mo.md("### Visualizing Probability as Area Under the PDF Curve"),
225
+ mo.md("Adjust sliders to change the interval $[a, b]$ and see how the probability changes:"),
226
+ mo.hstack([
227
+ mo.md("Lower bound (a):"),
228
+ a_slider,
229
+ mo.md("Upper bound (b):"),
230
+ b_slider
231
+ ], justify="start"),
232
+ distribution_radio
233
+ ])
234
+ _controls
235
+ return a_slider, b_slider, distribution_radio
236
+
237
+
238
+ @app.cell(hide_code=True)
239
+ def _(
240
+ a_slider,
241
+ b_slider,
242
+ create_pdf_visualization,
243
+ distribution_radio,
244
+ fig_to_image,
245
+ mo,
246
+ ):
247
+ a = a_slider.amount
248
+ b = b_slider.amount
249
+ distribution = distribution_radio.value
250
+
251
+ # Ensure a < b
252
+ if a > b:
253
+ a, b = b, a
254
+
255
+ # visualization
256
+ _fig, _probability = create_pdf_visualization(a, b, distribution)
257
+
258
+ # Display visualization
259
+ _img = mo.image(fig_to_image(_fig), width="100%")
260
+
261
+ # Add appropriate explanation
262
+ if distribution == "uniform":
263
+ _explanation = mo.md(
264
+ f"""
265
+ In the **uniform distribution**, all values between 0 and 5 are equally likely.
266
+ The probability density is constant at 0.2 (which is 1/5, ensuring the total area is 1).
267
+ For a uniform distribution, the probability that $X$ is in the interval $[{a:.1f}, {b:.1f}]$
268
+ is simply proportional to the width of the interval: $P({a:.1f} \leq X \leq {b:.1f}) = {_probability:.4f}$
269
+ Note that while the PDF has a constant value of 0.2, this is not a probability but a density!
270
+ """
271
+ )
272
+ elif distribution == "triangular":
273
+ _explanation = mo.md(
274
+ f"""
275
+ In this **triangular distribution**, the probability density increases linearly from 0 to 2.5,
276
+ then decreases linearly from 2.5 to 5.
277
+ The distribution's peak is at x = 2.5, where the value is highest.
278
+ The orange shaded area representing $P({a:.1f} \leq X \leq {b:.1f}) = {_probability:.4f}$
279
+ is calculated by integrating the PDF over the interval.
280
+ """
281
+ )
282
+ else:
283
+ _explanation = mo.md(
284
+ f"""
285
+ The **exponential distribution** (with λ = 0.5) models the time between events in a Poisson process.
286
+ Unlike the uniform and triangular distributions, the exponential distribution has infinite support
287
+ (extends from 0 to infinity). The probability density decreases exponentially as x increases.
288
+ The orange shaded area representing $P({a:.1f} \leq X \leq {b:.1f}) = {_probability:.4f}$
289
+ is calculated by integrating $f(x) = 0.5e^{{-0.5x}}$ over the interval.
290
+ """
291
+ )
292
+ mo.vstack([_img, _explanation])
293
+ return a, b, distribution
294
+
295
+
296
+ @app.cell(hide_code=True)
297
+ def _(mo):
298
+ mo.md(
299
+ r"""
300
+ ## Cumulative Distribution Function
301
+
302
+ Since working with PDFs requires solving integrals to find probabilities, we often use the **Cumulative Distribution Function (CDF)** as a more convenient tool.
303
+
304
+ The CDF $F(x)$ for a continuous random variable $X$ is defined as:
305
+
306
+ $$F(x) = P(X \leq x) = \int_{-\infty}^{x} f(t)\,dt$$
307
+
308
+ where $f(t)$ is the PDF of $X$.
309
+
310
+ ### Properties of CDFs
311
+
312
+ A CDF $F(x)$ has these key properties:
313
+
314
+ 1. $F(x)$ is always non-decreasing: if $a < b$, then $F(a) \leq F(b)$
315
+ 2. $\lim_{x \to -\infty} F(x) = 0$ and $\lim_{x \to \infty} F(x) = 1$
316
+ 3. $F(x)$ is right-continuous: $\lim_{h \to 0^+} F(x+h) = F(x)$
317
+
318
+ ### Using the CDF to Calculate Probabilities
319
+
320
+ The CDF is extremely useful because it allows us to calculate various probabilities without having to perform integrals each time:
321
+
322
+ | Probability Query | Solution | Explanation |
323
+ |-------------------|----------|-------------|
324
+ | $P(X < a)$ | $F(a)$ | Definition of the CDF |
325
+ | $P(X \leq a)$ | $F(a)$ | For continuous distributions, $P(X = a) = 0$ |
326
+ | $P(X > a)$ | $1 - F(a)$ | Since $P(X \leq a) + P(X > a) = 1$ |
327
+ | $P(a < X < b)$ | $F(b) - F(a)$ | Since $F(a) + P(a < X < b) = F(b)$ |
328
+ | $P(a \leq X \leq b)$ | $F(b) - F(a)$ | Since $P(X = a) = P(X = b) = 0$ |
329
+
330
+ For discrete random variables, the CDF is also defined but it's less commonly used:
331
+
332
+ $$F_X(a) = \sum_{i \leq a} P(X = i)$$
333
+
334
+ The CDF for discrete distributions is a step function, increasing at each point in the support of the random variable.
335
+ """
336
+ )
337
+ return
338
+
339
+
340
+ @app.cell(hide_code=True)
341
+ def _(fig_to_image, mo, np, plt):
342
+ def create_pdf_cdf_comparison():
343
+ fig, axs = plt.subplots(3, 2, figsize=(12, 10))
344
+
345
+ # x-values
346
+ x = np.linspace(-1, 6, 1000)
347
+
348
+ # 1. Uniform Distribution
349
+ # PDF
350
+ pdf_uniform = np.where((x >= 0) & (x <= 5), 0.2, 0)
351
+ axs[0, 0].plot(x, pdf_uniform, 'b-', linewidth=2)
352
+ axs[0, 0].set_title('Uniform PDF')
353
+ axs[0, 0].set_ylabel('Density')
354
+ axs[0, 0].grid(alpha=0.3)
355
+
356
+ # CDF
357
+ cdf_uniform = np.zeros_like(x)
358
+ for i, val in enumerate(x):
359
+ if val < 0:
360
+ cdf_uniform[i] = 0
361
+ elif val > 5:
362
+ cdf_uniform[i] = 1
363
+ else:
364
+ cdf_uniform[i] = val / 5
365
+
366
+ axs[0, 1].plot(x, cdf_uniform, 'r-', linewidth=2)
367
+ axs[0, 1].set_title('Uniform CDF')
368
+ axs[0, 1].set_ylabel('Probability')
369
+ axs[0, 1].grid(alpha=0.3)
370
+
371
+ # 2. Triangular Distribution
372
+ # PDF
373
+ pdf_triangular = np.where(x <= 2.5, x/6.25, (5-x)/6.25)
374
+ pdf_triangular = np.where((x < 0) | (x > 5), 0, pdf_triangular)
375
+
376
+ axs[1, 0].plot(x, pdf_triangular, 'b-', linewidth=2)
377
+ axs[1, 0].set_title('Triangular PDF')
378
+ axs[1, 0].set_ylabel('Density')
379
+ axs[1, 0].grid(alpha=0.3)
380
+
381
+ # CDF
382
+ cdf_triangular = np.zeros_like(x)
383
+ for i, val in enumerate(x):
384
+ if val <= 0:
385
+ cdf_triangular[i] = 0
386
+ elif val >= 5:
387
+ cdf_triangular[i] = 1
388
+ else:
389
+ # For x ≤ 2.5: CDF = x²/(2 *6 .25)
390
+ # For x > 2.5: CDF = 1 - (5 - x)²/(2 * 6.25)
391
+ if val <= 2.5:
392
+ cdf_triangular[i] = (val**2) / (2 * 6.25)
393
+ else:
394
+ cdf_triangular[i] = 1 - ((5 - val)**2) / (2 * 6.25)
395
+
396
+ axs[1, 1].plot(x, cdf_triangular, 'r-', linewidth=2)
397
+ axs[1, 1].set_title('Triangular CDF')
398
+ axs[1, 1].set_ylabel('Probability')
399
+ axs[1, 1].grid(alpha=0.3)
400
+
401
+ # 3. Exponential Distribution
402
+ # PDF
403
+ lambda_param = 0.5
404
+ pdf_exponential = np.where(x >= 0, lambda_param * np.exp(-lambda_param * x), 0)
405
+
406
+ axs[2, 0].plot(x, pdf_exponential, 'b-', linewidth=2)
407
+ axs[2, 0].set_title('Exponential PDF (λ=0.5)')
408
+ axs[2, 0].set_xlabel('x')
409
+ axs[2, 0].set_ylabel('Density')
410
+ axs[2, 0].grid(alpha=0.3)
411
+
412
+ # CDF
413
+ cdf_exponential = np.where(x < 0, 0, 1 - np.exp(-lambda_param * x))
414
+
415
+ axs[2, 1].plot(x, cdf_exponential, 'r-', linewidth=2)
416
+ axs[2, 1].set_title('Exponential CDF (λ=0.5)')
417
+ axs[2, 1].set_xlabel('x')
418
+ axs[2, 1].set_ylabel('Probability')
419
+ axs[2, 1].grid(alpha=0.3)
420
+
421
+ # Common x-limits
422
+ for ax in axs.flatten():
423
+ ax.set_xlim(-0.5, 5.5)
424
+ if ax in axs[:, 0]: # PDF plots
425
+ ax.set_ylim(-0.05, max(0.5, max(pdf_triangular)*1.1))
426
+ else: # CDF plots
427
+ ax.set_ylim(-0.05, 1.05)
428
+
429
+ plt.tight_layout()
430
+ plt.gca()
431
+ return fig
432
+
433
+ # Create visualization
434
+ _fig = create_pdf_cdf_comparison()
435
+ _img = mo.image(fig_to_image(_fig), width="100%")
436
+
437
+ _explanation = mo.md(
438
+ r"""
439
+ The figure above compares the Probability Density Functions (PDFs) on the left with their corresponding Cumulative Distribution Functions (CDFs) on the right for three common distributions:
440
+
441
+ 1. **Uniform Distribution**:
442
+
443
+ - PDF: Constant value (0.2) across the support range [0, 5]
444
+ - CDF: Linear increase from 0 to 1 across the support range
445
+
446
+ 2. **Triangular Distribution**:
447
+
448
+ - PDF: Linearly increases then decreases, forming a triangle shape
449
+ - CDF: Increases quadratically up to the peak, then approaches 1 quadratically
450
+
451
+ 3. **Exponential Distribution**:
452
+
453
+ - PDF: Starts at λ=0.5 and decreases exponentially
454
+ - CDF: Starts at 0 and approaches 1 exponentially (never quite reaching 1)
455
+
456
+ /// NOTE
457
+ The common properties of all CDFs:
458
+
459
+ - They are non-decreasing functions
460
+ - They start at 0 (for x = -∞) and approach or reach 1 (for x = ∞)
461
+ - The slope of the CDF at any point equals the PDF value at that point
462
+ """
463
+ )
464
+
465
+ mo.vstack([_img, _explanation])
466
+ return (create_pdf_cdf_comparison,)
467
+
468
+
469
+ @app.cell(hide_code=True)
470
+ def _(mo):
471
+ mo.md(
472
+ r"""
473
+ ## Solving for Constants in PDFs
474
+
475
+ Many PDFs contain a constant that needs to be determined to ensure the total probability equals 1. Let's work through an example to understand how to solve for these constants.
476
+
477
+ ### Example: Finding the Constant $C$
478
+
479
+ Let $X$ be a continuous random variable with PDF:
480
+
481
+ $$f(x) = \begin{cases}
482
+ C(4x - 2x^2) & \text{when } 0 < x < 2 \\
483
+ 0 & \text{otherwise}
484
+ \end{cases}$$
485
+
486
+ In this function, $C$ is a constant we need to determine. Since we know the PDF must integrate to 1:
487
+
488
+ \begin{align}
489
+ &\int_0^2 C(4x - 2x^2) \, dx = 1 \\
490
+ &C\left(2x^2 - \frac{2x^3}{3}\right)\bigg|_0^2 = 1 \\
491
+ &C\left[\left(8 - \frac{16}{3}\right) - 0 \right] = 1 \\
492
+ &C\left(\frac{24 - 16}{3}\right) = 1 \\
493
+ &C\left(\frac{8}{3}\right) = 1 \\
494
+ &C = \frac{3}{8}
495
+ \end{align}
496
+
497
+ Now that we know $C = \frac{3}{8}$, we can compute probabilities. For example, what is $P(X > 1)$?
498
+
499
+ \begin{align}
500
+ P(X > 1)
501
+ &= \int_1^{\infty}f(x) \, dx \\
502
+ &= \int_1^2 \frac{3}{8}(4x - 2x^2) \, dx \\
503
+ &= \frac{3}{8}\left(2x^2 - \frac{2x^3}{3}\right)\bigg|_1^2 \\
504
+ &= \frac{3}{8}\left[\left(8 - \frac{16}{3}\right) - \left(2 - \frac{2}{3}\right)\right] \\
505
+ &= \frac{3}{8}\left[\left(8 - \frac{16}{3}\right) - \left(\frac{6 - 2}{3}\right)\right] \\
506
+ &= \frac{3}{8}\left[\left(\frac{24 - 16}{3}\right) - \left(\frac{4}{3}\right)\right] \\
507
+ &= \frac{3}{8}\left[\left(\frac{8}{3}\right) - \left(\frac{4}{3}\right)\right] \\
508
+ &= \frac{3}{8} \cdot \frac{4}{3} \\
509
+ &= \frac{1}{2}
510
+ \end{align}
511
+
512
+ Let's visualize this distribution and verify our results:
513
+ """
514
+ )
515
+ return
516
+
517
+
518
+ @app.cell(hide_code=True)
519
+ def _(
520
+ create_example_pdf_visualization,
521
+ fig_to_image,
522
+ mo,
523
+ symbolic_calculation,
524
+ ):
525
+ # Create visualization
526
+ _fig = create_example_pdf_visualization()
527
+ _img = mo.image(fig_to_image(_fig), width="100%")
528
+
529
+ # Symbolic calculation
530
+ _sympy_verification = mo.md(symbolic_calculation())
531
+
532
+ _explanation = mo.md(
533
+ r"""
534
+ The figure above shows:
535
+
536
+ 1. **Left**: The PDF $f(x) = \frac{3}{8}(4x - 2x^2)$ for $0 < x < 2$, with the area representing P(X > 1) shaded in orange.
537
+ 2. **Right**: The corresponding CDF, showing F(1) = 0.5 and thus P(X > 1) = 1 - F(1) = 0.5.
538
+
539
+ Notice how we:
540
+
541
+ 1. First determined the constant C = 3/8 by ensuring the total area under the PDF equals 1
542
+ 2. Used this value to calculate specific probabilities like P(X > 1)
543
+ 3. Verified our results both graphically and symbolically
544
+ """
545
+ )
546
+ mo.vstack([_img, _sympy_verification, _explanation])
547
+ return
548
+
549
+
550
+ @app.cell(hide_code=True)
551
+ def _(mo):
552
+ mo.md(
553
+ r"""
554
+ ## Expectation and Variance of Continuous Random Variables
555
+
556
+ Just as with discrete random variables, we can calculate the expectation and variance of continuous random variables. The main difference is that we use integrals instead of sums.
557
+
558
+ ### Expectation (Mean)
559
+
560
+ For a continuous random variable $X$ with PDF $f(x)$, the expectation is:
561
+
562
+ $$E[X] = \int_{-\infty}^{\infty} x \cdot f(x) \, dx$$
563
+
564
+ More generally, for any function $g(X)$:
565
+
566
+ $$E[g(X)] = \int_{-\infty}^{\infty} g(x) \cdot f(x) \, dx$$
567
+
568
+ ### Variance
569
+
570
+ The variance is defined the same way as for discrete random variables:
571
+
572
+ $$\text{Var}(X) = E[(X - \mu)^2] = E[X^2] - (E[X])^2$$
573
+
574
+ where $\mu = E[X]$ is the mean of $X$.
575
+
576
+ To calculate $E[X^2]$, we use:
577
+
578
+ $$E[X^2] = \int_{-\infty}^{\infty} x^2 \cdot f(x) \, dx$$
579
+
580
+ ### Properties
581
+
582
+ The following properties hold for both continuous and discrete random variables:
583
+
584
+ 1. $E[aX + b] = aE[X] + b$ for constants $a$ and $b$
585
+ 2. $\text{Var}(aX + b) = a^2 \text{Var}(X)$ for constants $a$ and $b$
586
+
587
+ Let's calculate the expectation and variance for our example PDF:
588
+ """
589
+ )
590
+ return
591
+
592
+
593
+ @app.cell(hide_code=True)
594
+ def _(fig_to_image, mo, np, plt, sympy):
595
+ # Symbolic calculation of expectation and variance
596
+ def symbolic_stats_calc():
597
+ x = sympy.symbols('x')
598
+ C = sympy.Rational(3, 8)
599
+
600
+ # Define the PDF
601
+ pdf_expr = C * (4*x - 2*x**2)
602
+
603
+ # Calculate expectation
604
+ E_X = sympy.integrate(x * pdf_expr, (x, 0, 2))
605
+
606
+ # Calculate E[X²]
607
+ E_X2 = sympy.integrate(x**2 * pdf_expr, (x, 0, 2))
608
+
609
+ # Calculate variance
610
+ Var_X = E_X2 - E_X**2
611
+
612
+ # Calculate standard deviation
613
+ Std_X = sympy.sqrt(Var_X)
614
+
615
+ return E_X, E_X2, Var_X, Std_X
616
+
617
+ # Get symbolic results
618
+ E_X, E_X2, Var_X, Std_X = symbolic_stats_calc()
619
+
620
+ # Numerical values for plotting
621
+ E_X_val = float(E_X)
622
+ Var_X_val = float(Var_X)
623
+ Std_X_val = float(Std_X)
624
+
625
+ def create_expectation_variance_vis():
626
+ """Create visualization showing mean and variance for the example PDF."""
627
+ fig, ax = plt.subplots(figsize=(10, 6))
628
+
629
+ # x-values
630
+ x = np.linspace(-0.5, 2.5, 1000)
631
+
632
+ # PDF function
633
+ C = 3/8
634
+ pdf = np.where((x > 0) & (x < 2), C * (4*x - 2*x**2), 0)
635
+
636
+ # Plot the PDF
637
+ ax.plot(x, pdf, 'b-', linewidth=2, label='PDF')
638
+ ax.fill_between(x, pdf, where=(x > 0) & (x < 2), alpha=0.3, color='blue')
639
+
640
+ # Mark the mean
641
+ ax.axvline(x=E_X_val, color='r', linestyle='--', linewidth=2,
642
+ label=f'Mean (E[X] = {E_X_val:.3f})')
643
+
644
+ # Mark the standard deviation range
645
+ ax.axvspan(E_X_val - Std_X_val, E_X_val + Std_X_val, alpha=0.2, color='green',
646
+ label=f'±1 Std Dev ({Std_X_val:.3f})')
647
+
648
+ # Add labels and title
649
+ ax.set_xlabel('x')
650
+ ax.set_ylabel('Probability Density')
651
+ ax.set_title('PDF with Mean and Variance')
652
+ ax.legend()
653
+ ax.grid(alpha=0.3)
654
+
655
+ # Set x-limits
656
+ ax.set_xlim(-0.25, 2.25)
657
+
658
+ plt.tight_layout()
659
+ return fig
660
+
661
+ # Create the visualization
662
+ _fig = create_expectation_variance_vis()
663
+ _img = mo.image(fig_to_image(_fig), width="100%")
664
+
665
+ # Detailed calculations for our example
666
+ _calculations = mo.md(
667
+ f"""
668
+ ### Calculating Expectation and Variance for Our Example
669
+
670
+ Let's calculate the expectation and variance for the PDF:
671
+
672
+ $$f(x) = \\begin{{cases}}
673
+ \\frac{{3}}{{8}}(4x - 2x^2) & \\text{{when }} 0 < x < 2 \\\\
674
+ 0 & \\text{{otherwise}}
675
+ \\end{{cases}}$$
676
+
677
+ #### Expectation Calculation
678
+
679
+ $$E[X] = \\int_{{-\\infty}}^{{\\infty}} x \\cdot f(x) \\, dx = \\int_0^2 x \\cdot \\frac{{3}}{{8}}(4x - 2x^2) \\, dx$$
680
+
681
+ $$E[X] = \\frac{{3}}{{8}} \\int_0^2 (4x^2 - 2x^3) \\, dx = \\frac{{3}}{{8}} \\left[ \\frac{{4x^3}}{{3}} - \\frac{{2x^4}}{{4}} \\right]_0^2$$
682
+
683
+ $$E[X] = \\frac{{3}}{{8}} \\left[ \\frac{{4 \\cdot 2^3}}{{3}} - \\frac{{2 \\cdot 2^4}}{{4}} - 0 \\right] = \\frac{{3}}{{8}} \\left[ \\frac{{32}}{{3}} - 4 \\right]$$
684
+
685
+ $$E[X] = \\frac{{3}}{{8}} \\cdot \\frac{{32 - 12}}{{3}} = \\frac{{3}}{{8}} \\cdot \\frac{{20}}{{3}} = \\frac{{20}}{{8}} = {E_X}$$
686
+
687
+ #### Variance Calculation
688
+
689
+ First, we need $E[X^2]$:
690
+
691
+ $$E[X^2] = \\int_{{-\\infty}}^{{\\infty}} x^2 \\cdot f(x) \\, dx = \\int_0^2 x^2 \\cdot \\frac{{3}}{{8}}(4x - 2x^2) \\, dx$$
692
+
693
+ $$E[X^2] = \\frac{{3}}{{8}} \\int_0^2 (4x^3 - 2x^4) \\, dx = \\frac{{3}}{{8}} \\left[ \\frac{{4x^4}}{{4}} - \\frac{{2x^5}}{{5}} \\right]_0^2$$
694
+
695
+ $$E[X^2] = \\frac{{3}}{{8}} \\left[ 4 - \\frac{{2 \\cdot 32}}{{5}} - 0 \\right] = \\frac{{3}}{{8}} \\left[ 4 - \\frac{{64}}{{5}} \\right]$$
696
+
697
+ $$E[X^2] = \\frac{{3}}{{8}} \\cdot \\frac{{20 - 64/5}}{{1}} = {E_X2}$$
698
+
699
+ Now we can calculate the variance:
700
+
701
+ $$\\text{{Var}}(X) = E[X^2] - (E[X])^2 = {E_X2} - ({E_X})^2 = {Var_X}$$
702
+
703
+ Therefore, the standard deviation is $\\sqrt{{\\text{{Var}}(X)}} = {Std_X}$.
704
+ """
705
+ )
706
+ mo.vstack([_img, _calculations])
707
+ return (
708
+ E_X,
709
+ E_X2,
710
+ E_X_val,
711
+ Std_X,
712
+ Std_X_val,
713
+ Var_X,
714
+ Var_X_val,
715
+ create_expectation_variance_vis,
716
+ symbolic_stats_calc,
717
+ )
718
+
719
+
720
+ @app.cell(hide_code=True)
721
+ def _(mo):
722
+ mo.md(
723
+ r"""
724
+ ## 🤔 Test Your Understanding
725
+
726
+ Select which of these statements about continuous distributions you think are correct:
727
+
728
+ /// details | The PDF of a continuous random variable can have values greater than 1
729
+ ✅ Correct! Since the PDF represents density (not probability), it can exceed 1 as long as the total area under the curve equals 1.
730
+ ///
731
+
732
+ /// details | For a continuous distribution, $P(X = a) > 0$ for any value $a$ in the support
733
+ ❌ Incorrect! For continuous random variables, the probability of the random variable taking any specific exact value is always 0. That is, $P(X = a) = 0$ for any value $a$.
734
+ ///
735
+
736
+ /// details | The area under a PDF curve between $a$ and $b$ equals the probability $P(a \leq X \leq b)$
737
+ ✅ Correct! The area under the PDF curve over an interval gives the probability that the random variable falls within that interval.
738
+ ///
739
+
740
+ /// details | The CDF function $F(x)$ is always equal to $\int_{-\infty}^{x} f(t) \, dt$
741
+ ✅ Correct! The CDF at point $x$ is the integral of the PDF from negative infinity to $x$.
742
+ ///
743
+
744
+ /// details | For a continuous random variable, $F(x)$ ranges from 0 to the maximum value in the support of the random variable
745
+ ❌ Incorrect! The CDF $F(x)$ ranges from 0 to 1, representing probabilities. It approaches 1 (not the maximum value in the support) as $x$ approaches infinity.
746
+ ///
747
+
748
+ /// details | To calculate the variance of a continuous random variable, we use the formula $\text{Var}(X) = E[X^2] - (E[X])^2$
749
+ ✅ Correct! This formula applies to both discrete and continuous random variables.
750
+ ///
751
+ """
752
+ )
753
+ return
754
+
755
+
756
+ @app.cell(hide_code=True)
757
+ def _(mo):
758
+ mo.md(
759
+ r"""
760
+ ## Summary
761
+
762
+ Moving from discrete to continuous thinking is a big conceptual leap, but it opens up powerful ways to model real-world phenomena.
763
+
764
+ In this notebook, we've seen how continuous random variables let us model quantities that can take any real value. Instead of dealing with probabilities at specific points (which are actually zero!), we work with probability density functions (PDFs) and find probabilities by calculating areas under curves.
765
+
766
+ Some key points to remember:
767
+
768
+ • PDFs give us relative likelihood, not actual probabilities - that's why they can exceed 1
769
+ • The probability between two points is the area under the PDF curve
770
+ • CDFs offer a convenient shortcut to find probabilities without integrating
771
+ • Expectation and variance work similarly to discrete variables, just with integrals instead of sums
772
+ • Constants in PDFs are determined by ensuring the total probability equals 1
773
+
774
+ This foundation will serve you well as we explore specific continuous distributions like normal, exponential, and beta in future notebooks. These distributions are the workhorses of probability theory and statistics, appearing everywhere from quality control to financial modeling.
775
+
776
+ One final thought: continuous distributions are beautiful mathematical objects, but remember they're just models. Real-world data is often discrete at some level, but continuous distributions provide elegant approximations that make calculations more tractable.
777
+ """
778
+ )
779
+ return
780
+
781
+
782
+ @app.cell
783
+ def _(mo):
784
+ mo.md(r"""Appendix code (helper functions, variables, etc.):""")
785
+ return
786
+
787
+
788
+ @app.cell
789
+ def _():
790
+ import marimo as mo
791
+ return (mo,)
792
+
793
+
794
+ @app.cell(hide_code=True)
795
+ def _():
796
+ import numpy as np
797
+ import matplotlib.pyplot as plt
798
+ import scipy.stats as stats
799
+ import sympy
800
+ from scipy import integrate as scipy
801
+ import polars as pl
802
+ import altair as alt
803
+ from wigglystuff import TangleSlider
804
+ return TangleSlider, alt, np, pl, plt, scipy, stats, sympy
805
+
806
+
807
+ @app.cell(hide_code=True)
808
+ def _():
809
+ import io
810
+ import base64
811
+ from matplotlib.figure import Figure
812
+
813
+ # Helper function to convert mpl figure to an image format mo.image can handle
814
+ def fig_to_image(fig):
815
+ buf = io.BytesIO()
816
+ fig.savefig(buf, format='png')
817
+ buf.seek(0)
818
+ data = f"data:image/png;base64,{base64.b64encode(buf.read()).decode('utf-8')}"
819
+ return data
820
+ return Figure, base64, fig_to_image, io
821
+
822
+
823
+ @app.cell(hide_code=True)
824
+ def _(np, plt):
825
+ def create_pdf_visualization(a, b, distribution='uniform'):
826
+ fig, ax = plt.subplots(figsize=(10, 6))
827
+
828
+ # x-values
829
+ x = np.linspace(-0.5, 5.5, 1000)
830
+
831
+ # Various PDFs to visualize
832
+ if distribution == 'uniform':
833
+ # Uniform distribution from 0 to 5
834
+ y = np.where((x >= 0) & (x <= 5), 0.2, 0)
835
+ title = f"Uniform PDF from 0 to 5"
836
+
837
+ elif distribution == 'triangular':
838
+ # Triangular distribution peaked at 2.5
839
+ y = np.where(x <= 2.5, x/6.25, (5-x)/6.25) # peak at 2.5
840
+ y = np.where((x < 0) | (x > 5), 0, y)
841
+ title = f"Triangular PDF from 0 to 5"
842
+
843
+ elif distribution == 'exponential':
844
+ lambda_param = 0.5
845
+ y = np.where(x >= 0, lambda_param * np.exp(-lambda_param * x), 0)
846
+ title = f"Exponential PDF with λ = {lambda_param}"
847
+
848
+ # Plot PDF
849
+ ax.plot(x, y, 'b-', linewidth=2, label='PDF $f(x)$')
850
+
851
+ # Shade the area for the probability P(a ≤ X ≤ b)
852
+ mask = (x >= a) & (x <= b)
853
+ ax.fill_between(x[mask], y[mask], color='orange', alpha=0.5)
854
+
855
+ # Calculate the probability
856
+ dx = x[1] - x[0]
857
+ probability = np.sum(y[mask]) * dx
858
+
859
+ # vertical lines at a and b
860
+ ax.axvline(x=a, color='r', linestyle='--', alpha=0.7,
861
+ label=f'a = {a:.1f}')
862
+ ax.axvline(x=b, color='g', linestyle='--', alpha=0.7,
863
+ label=f'b = {b:.1f}')
864
+
865
+ # horizontal line at y=0
866
+ ax.axhline(y=0, color='black', linestyle='-', alpha=0.3)
867
+
868
+ # labels and title
869
+ ax.set_xlabel('x')
870
+ ax.set_ylabel('Probability Density $f(x)$')
871
+ ax.set_title(title)
872
+ ax.legend(loc='upper right')
873
+
874
+ # relevant annotations
875
+ ax.annotate(f'$P({a:.1f} \leq X \leq {b:.1f}) = {probability:.4f}$',
876
+ xy=(0.5, 0.9), xycoords='axes fraction',
877
+ bbox=dict(boxstyle='round,pad=0.5', facecolor='white', alpha=0.8),
878
+ horizontalalignment='center', fontsize=12)
879
+
880
+ plt.grid(alpha=0.3)
881
+ plt.tight_layout()
882
+ plt.gca()
883
+ return fig, probability
884
+ return (create_pdf_visualization,)
885
+
886
+
887
+ @app.cell(hide_code=True)
888
+ def _(np, plt, sympy):
889
+ def create_example_pdf_visualization():
890
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
891
+
892
+ # x-values
893
+ x = np.linspace(-0.5, 2.5, 1000)
894
+
895
+ # PDF function
896
+ C = 3/8
897
+ pdf = np.where((x > 0) & (x < 2), C * (4*x - 2*x**2), 0)
898
+
899
+ # CDF
900
+ cdf = np.zeros_like(x)
901
+ for i, val in enumerate(x):
902
+ if val <= 0:
903
+ cdf[i] = 0
904
+ elif val >= 2:
905
+ cdf[i] = 1
906
+ else:
907
+ # Analytical form: C*(2x^2 - 2x^3/3)
908
+ cdf[i] = C * (2*val**2 - (2*val**3)/3)
909
+
910
+ # PDF Plot
911
+ ax1.plot(x, pdf, 'b-', linewidth=2)
912
+ ax1.set_title('PDF: $f(x) = \\frac{3}{8}(4x - 2x^2)$ for $0 < x < 2$')
913
+ ax1.set_xlabel('x')
914
+ ax1.set_ylabel('Probability Density')
915
+ ax1.grid(alpha=0.3)
916
+
917
+ # Highlight the area for P(X > 1)
918
+ mask = (x > 1) & (x < 2)
919
+ ax1.fill_between(x[mask], pdf[mask], color='orange', alpha=0.5,
920
+ label='P(X > 1) = 0.5')
921
+
922
+ # Add vertical line at x=1
923
+ ax1.axvline(x=1, color='r', linestyle='--', alpha=0.7)
924
+ ax1.legend()
925
+
926
+ # CDF Plot
927
+ ax2.plot(x, cdf, 'r-', linewidth=2)
928
+ ax2.set_title('CDF: $F(x)$ for the Example Distribution')
929
+ ax2.set_xlabel('x')
930
+ ax2.set_ylabel('Cumulative Probability')
931
+ ax2.grid(alpha=0.3)
932
+
933
+ # Mark appopriate (F(1) & F(2)) points)
934
+ ax2.plot(1, cdf[np.abs(x-1).argmin()], 'ro', markersize=8)
935
+ ax2.plot(2, cdf[np.abs(x-2).argmin()], 'ro', markersize=8)
936
+
937
+ # annotations
938
+ F_1 = C * (2*1**2 - (2*1**3)/3) # F(1)
939
+ ax2.annotate(f'F(1) = {F_1:.3f}', xy=(1, F_1), xytext=(1.1, 0.4),
940
+ arrowprops=dict(facecolor='black', shrink=0.05, width=1))
941
+
942
+ ax2.annotate(f'F(2) = 1', xy=(2, 1), xytext=(1.7, 0.8),
943
+ arrowprops=dict(facecolor='black', shrink=0.05, width=1))
944
+
945
+ ax2.annotate(f'P(X > 1) = 1 - F(1) = {1-F_1:.3f}', xy=(1.5, 0.7),
946
+ bbox=dict(boxstyle='round,pad=0.5', facecolor='orange', alpha=0.2))
947
+
948
+ # common x-limits
949
+ for ax in [ax1, ax2]:
950
+ ax.set_xlim(-0.25, 2.25)
951
+
952
+ plt.tight_layout()
953
+ plt.gca()
954
+ return fig
955
+
956
+ def symbolic_calculation():
957
+ x = sympy.symbols('x')
958
+ C = sympy.Rational(3, 8)
959
+
960
+ # PDF defn
961
+ pdf_expr = C * (4*x - 2*x**2)
962
+
963
+ # Verify PDF integrates to 1
964
+ total_prob = sympy.integrate(pdf_expr, (x, 0, 2))
965
+
966
+ # Calculate P(X > 1)
967
+ prob_gt_1 = sympy.integrate(pdf_expr, (x, 1, 2))
968
+
969
+ return f"""Symbolic calculation verification:
970
+
971
+ 1. Total probability: ∫₀² {C}(4x - 2x²) dx = {total_prob}
972
+ 2. P(X > 1): ∫₁² {C}(4x - 2x²) dx = {prob_gt_1}
973
+ """
974
+
975
+ return create_example_pdf_visualization, symbolic_calculation
976
+
977
+
978
+ if __name__ == "__main__":
979
+ app.run()