CoolFace
Apppublic

marimo-team/marimo-learn

sourceHugging Faceupdated 5mo agoView on Hugging Face
3likes
03_probability_of_or.py335 linesDownload Raw Back to probability
1# /// script2# requires-python = ">=3.10"3# dependencies = [4#     "marimo",5#     "matplotlib==3.10.8",6#     "matplotlib-venn==1.1.2"7# ]8# ///9 10import marimo11 12__generated_with = "0.18.4"13app = marimo.App(width="medium")14 15 16@app.cell17def _():18    import marimo as mo19    return (mo,)20 21 22@app.cell23def _():24    import matplotlib.pyplot as plt25    from matplotlib_venn import venn226    import numpy as np27    return plt, venn228 29 30@app.cell(hide_code=True)31def _(mo):32    mo.md(r"""33    # Probability of Or34 35    When calculating the probability of either one event _or_ another occurring, we need to be careful about how we combine probabilities. The method depends on whether the events can happen together[<sup>1</sup>](https://chrispiech.github.io/probabilityForComputerScientists/en/part1/prob_or/).36 37    Let's explore how to calculate $P(E \cup F)$, i.e. $P(E \text{ or } F)$, in different scenarios.38    """)39    return40 41 42@app.cell(hide_code=True)43def _(mo):44    mo.md(r"""45    ## Mutually Exclusive Events46 47    Two events $E$ and $F$ are **mutually exclusive** if they cannot occur simultaneously.48    In set notation, this means:49 50    $E \cap F = \emptyset$51 52    For example:53 54    - Rolling an even number (2,4,6) vs rolling an odd number (1,3,5)55    - Drawing a heart vs drawing a spade from a deck56    - Passing vs failing a test57 58    Here's a Python function to check if two sets of outcomes are mutually exclusive:59    """)60    return61 62 63@app.cell64def _():65    def are_mutually_exclusive(event1, event2):66        return len(event1.intersection(event2)) == 067 68    # Example with dice rolls69    even_numbers = {2, 4, 6}70    odd_numbers = {1, 3, 5}71    prime_numbers = {2, 3, 5, 7}72    return are_mutually_exclusive, even_numbers, odd_numbers, prime_numbers73 74 75@app.cell76def _(are_mutually_exclusive, even_numbers, odd_numbers):77    are_mutually_exclusive(even_numbers, odd_numbers)78    return79 80 81@app.cell82def _(are_mutually_exclusive, even_numbers, prime_numbers):83    are_mutually_exclusive(even_numbers, prime_numbers)84    return85 86 87@app.cell(hide_code=True)88def _(mo):89    mo.md(r"""90    ## Or with Mutually Exclusive Events91 92    For mutually exclusive events, the probability of either event occurring is simply the sum of their individual probabilities:93 94    $P(E \cup F) = P(E) + P(F)$95 96    This extends to multiple events. For $n$ mutually exclusive events $E_1, E_2, \ldots, E_n$:97 98    $P(E_1 \cup E_2 \cup \cdots \cup E_n) = \sum_{i=1}^n P(E_i)$99 100    Let's implement this calculation:101    """)102    return103 104 105@app.cell106def _():107    def prob_union_mutually_exclusive(probabilities):108        return sum(probabilities)109 110    # Example: Rolling a die111    # P(even) = P(2) + P(4) + P(6)112    p_even_mutually_exclusive = prob_union_mutually_exclusive([1/6, 1/6, 1/6])113    print(f"P(rolling an even number) = {p_even_mutually_exclusive}")114 115    # P(prime) = P(2) + P(3) + P(5)116    p_prime_mutually_exclusive = prob_union_mutually_exclusive([1/6, 1/6, 1/6])117    print(f"P(rolling a prime number) = {p_prime_mutually_exclusive}")118    return119 120 121@app.cell(hide_code=True)122def _(mo):123    mo.md(r"""124    ## Or with Non-Mutually Exclusive Events125 126    When events can occur together, we need to use the **inclusion-exclusion principle**:127 128    $P(E \cup F) = P(E) + P(F) - P(E \cap F)$129 130    Why subtract $P(E \cap F)$? Because when we add $P(E)$ and $P(F)$, we count the overlap twice!131 132    For example, consider calculating $P(\text{prime or even})$ when rolling a die:133 134    - Prime numbers: {2, 3, 5}135    - Even numbers: {2, 4, 6}136    - The number 2 is counted twice unless we subtract its probability137 138    Here's how to implement this calculation:139    """)140    return141 142 143@app.cell144def _():145    def prob_union_general(p_a, p_b, p_intersection):146        """Calculate probability of union for any two events"""147        return p_a + p_b - p_intersection148 149    # Example: Rolling a die150    # P(prime or even)151    p_prime_general = 3/6    # P(prime) = P(2,3,5)152    p_even_general = 3/6     # P(even) = P(2,4,6)153    p_intersection = 1/6     # P(intersection) = P(2)154 155    result = prob_union_general(p_prime_general, p_even_general, p_intersection)156    print(f"P(prime or even) = {p_prime_general} + {p_even_general} - {p_intersection} = {result}")157    return158 159 160@app.cell(hide_code=True)161def _(mo):162    mo.md(r"""163    ### Extension to Three Events164 165    For three events, the inclusion-exclusion principle becomes:166 167    $P(E_1 \cup E_2 \cup E_3) = P(E_1) + P(E_2) + P(E_3)$168    $- P(E_1 \cap E_2) - P(E_1 \cap E_3) - P(E_2 \cap E_3)$169    $+ P(E_1 \cap E_2 \cap E_3)$170 171    The pattern is:172 173    1. Add individual probabilities174    2. Subtract probabilities of pairs175    3. Add probability of triple intersection176    """)177    return178 179 180@app.cell(hide_code=True)181def _(mo):182    mo.md(r"""183    ### Interactive example:184    """)185    return186 187 188@app.cell189def _(event_type):190    event_type191    return192 193 194@app.cell(hide_code=True)195def _(mo):196    # Create a dropdown to select the type of events to visualize197    event_type = mo.ui.dropdown(198        options=[199            "Mutually Exclusive Events (Rolling Odd vs Even)",200            "Non-Mutually Exclusive Events (Prime vs Even)",201            "Three Events (Less than 3, Even, Prime)"202        ],203        value="Mutually Exclusive Events (Rolling Odd vs Even)",204        label="Select Event Type"205    )206    return (event_type,)207 208 209@app.cell(hide_code=True)210def _(event_type, mo, plt, venn2):211    # Define the events and their probabilities212    events_data = {213        "Mutually Exclusive Events (Rolling Odd vs Even)": {214            "sets": (round(3/6, 2), round(3/6, 2), 0),  # (odd, even, intersection)215            "labels": ("Odd\n{1,3,5}", "Even\n{2,4,6}"),216            "title": "Mutually Exclusive Events: Odd vs Even Numbers",217            "explanation": r"""218            ### Mutually Exclusive Events219 220            $P(\text{Odd}) = \frac{3}{6} = 0.5$221 222            $P(\text{Even}) = \frac{3}{6} = 0.5$223 224            $P(\text{Odd} \cap \text{Even}) = 0$225 226            $P(\text{Odd} \cup \text{Even}) = P(\text{Odd}) + P(\text{Even}) = 1$227 228            These events are mutually exclusive because a number cannot be both odd and even.229            """230        },231        "Non-Mutually Exclusive Events (Prime vs Even)": {232            "sets": (round(2/6, 2), round(2/6, 2), round(1/6, 2)),  # (prime-only, even-only, intersection)233            "labels": ("Prime\n{3,5}", "Even\n{4,6}"),234            "title": "Non-Mutually Exclusive: Prime vs Even Numbers",235            "explanation": r"""236            ### Non-Mutually Exclusive Events237 238            $P(\text{Prime}) = \frac{3}{6} = 0.5$ (2,3,5)239 240            $P(\text{Even}) = \frac{3}{6} = 0.5$ (2,4,6)241 242            $P(\text{Prime} \cap \text{Even}) = \frac{1}{6}$ (2)243 244            $P(\text{Prime} \cup \text{Even}) = \frac{3}{6} + \frac{3}{6} - \frac{1}{6} = \frac{5}{6}$245 246            These events overlap because 2 is both prime and even.247            """248        },249        "Three Events (Less than 3, Even, Prime)": {250            "sets": (round(1/6, 2), round(2/6, 2), round(1/6, 2)),  # (less than 3, even, intersection)251            "labels": ("<3\n{1,2}", "Even\n{2,4,6}"),252            "title": "Complex Example: Numbers < 3 and Even Numbers",253            "explanation": r"""254            ### Complex Event Interaction255 256            $P(x < 3) = \frac{2}{6}$ (1,2)257 258            $P(\text{Even}) = \frac{3}{6}$ (2,4,6)259 260            $P(x < 3 \cap \text{Even}) = \frac{1}{6}$ (2)261 262            $P(x < 3 \cup \text{Even}) = \frac{2}{6} + \frac{3}{6} - \frac{1}{6} = \frac{4}{6}$263 264            The number 2 belongs to both sets, requiring the inclusion-exclusion principle.265            """266        }267    }268 269    # Get data for selected event type270    data = events_data[event_type.value]271 272    # Create visualization273    plt.figure(figsize=(10, 5))274    v = venn2(subsets=data["sets"], 275              set_labels=data["labels"])276    plt.title(data["title"])277 278    # Display explanation alongside visualization279    mo.hstack([280        plt.gcf(),281        mo.md(data["explanation"])282    ])283    return284 285 286@app.cell(hide_code=True)287def _(mo):288    mo.md(r"""289    ## ๐Ÿค” Test Your Understanding290 291    Consider rolling a six-sided die. Which of these statements are true?292 293    <details>294    <summary>1. P(even or less than 3) = P(even) + P(less than 3)</summary>295 296    โŒ Incorrect! These events are not mutually exclusive (2 is both even and less than 3).297    We need to use the inclusion-exclusion principle.298    </details>299 300    <details>301    <summary>2. P(even or greater than 4) = 4/6</summary>302 303    โœ… Correct! {2,4,6} โˆช {5,6} = {2,4,5,6}, so probability is 4/6.304    </details>305 306    <details>307    <summary>3. P(prime or odd) = 5/6</summary>308 309    โœ… Correct! {2,3,5} โˆช {1,3,5} = {1,2,3,5}, so probability is 5/6.310    </details>311    """)312    return313 314 315@app.cell(hide_code=True)316def _(mo):317    mo.md("""318    ## Summary319 320    You've learned:321 322    - How to identify mutually exclusive events323    - The addition rule for mutually exclusive events324    - The inclusion-exclusion principle for overlapping events325    - How to extend these concepts to multiple events326 327    In the next lesson, we'll explore **conditional probability** - how the probability328    of one event changes when we know another event has occurred.329    """)330    return331 332 333if __name__ == "__main__":334    app.run()335