--> Skip to main content

Total Pageviews

Stats 2 Extra activity 2

Google Colab Notebook Activity

📚

Extra activity 2

Release Date : 4 October 2024
Submission due date : 16 October 2024
Peer Review Due Date : 20 October 2024

  1. Copy the code in Google Colab:
    • Open the provided Google Colab notebook available in the supplementary content. Make a copy of it and save it to your Google Drive. Before running any code, press Ctrl+F9 to run all cells. Once this is done, you can start experimenting with different values as demonstrated by Andrew Sir in Week 0 Part 2. If you run the code directly without this step, it may show errors.

  2. Select an Experiment and Event:
    • Choose an experiment and event from the examples discussed in your lectures or pick any other problem that interests you. This could be anything from a simple probability problem to a more complex statistical experiment.
  3. Add the Experiment and Event to the Notebook:
    • Incorporate your chosen experiment and event into the Google Colab notebook. Ensure you clearly define the parameters and the setup for your experiment.
  4. Perform a Monte Carlo Simulation:
    • Use Monte Carlo simulation techniques to verify the computed probability of your experiment. This involves running a large number of simulations to approximate the probability of the event.
    • Write the code to perform these simulations in the notebook. Make sure to document your steps and explain your code for clarity.
  5. Share the Notebook:
    • Once your notebook is ready, set the sharing permissions to “view” for everyone in the Onlinedegree domain. This ensures that others can access and review your work.
    • Add the notebook to the designated site under the heading ‘Activity 2’.
  6. Take a Screenshot:
    • Finally, take a screenshot of the website with the embedded Colab Notebook. This serves as proof of completion and can be submitted as required.

HTML and Python Code Snippets

HTML Code Snippet


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Coin Toss Probability Activity</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    <style>
        body {
            color: white;
        }
    </style>
</head>
<body>
    <h1>Coin Toss Probability Activity</h1>
    <p>For this activity, I conducted a series of experiments to determine the probability of getting a specific number of heads in a series of coin tosses. Specifically, I focused on three scenarios: tossing a coin 10 times, 50 times, and 100 times. For each scenario, I calculated the probability of getting exactly 5 heads in 10 tosses, 25 heads in 50 tosses, and 50 heads in 100 tosses.</p>
    
    <h2>Generate Sequences</h2>
    <p>First, I generated sequences of outcomes for each number of tosses using Python. This involved simulating the coin tosses and recording the number of heads obtained in each experiment. I printed all possible outcomes to provide a comprehensive view of the results.</p>
    
    <h2>Calculate Theoretical Probability</h2>
    <p>Use the binomial distribution formula to calculate the theoretical probability of getting the specified number of heads:</p>
    <pre><code>
    <p>\[ P(X = k) = \binom{n}{k} \left( \frac{1}{2} \right)^k \left( \frac{1}{2} \right)^{n-k} \]</p>
    <p>For 10 tosses, \( k = 5 \), the theoretical probability is:</p>
    <p>\[ P(X = 5) = \binom{10}{5} \left( \frac{1}{2} \right)^5 \left( \frac{1}{2} \right)^5 = \binom{10}{5} \left( \frac{1}{2} \right)^{10} \approx 0.2461 \]</p>
    <p>For 50 tosses, \( k = 25 \), the theoretical probability is:</p>
    <p>\[ P(X = 25) = \binom{50}{25} \left( \frac{1}{2} \right)^{25} \left( \frac{1}{2} \right)^{25} = \binom{50}{25} \left( \frac{1}{2} \right)^{50} \approx 0.1123 \]</p>
    <p>For 100 tosses, \( k = 50 \), the theoretical probability is:</p>
    <p>\[ P(X = 50) = \binom{100}{50} \left( \frac{1}{2} \right)^{50} \left( \frac{1}{2} \right)^{50} = \binom{100}{50} \left( \frac{1}{2} \right)^{100} \approx 0.0796 \]</p>
    </code></pre>
</body>
</html>
        

Python Code Snippet

Python code to generate sequence in form 1 and 2 where 1 is head and 2 is tail


import numpy as np

# Function to generate sequences of 1s and 2s
def generate_sequences(n_tosses, n_experiments):
    sequences = []
    for _ in range(n_experiments):
        sequence = np.random.choice([1, 2], size=n_tosses)
        sequences.append(sequence)
    return sequences

# Parameters
n_experiments = 1

# Generate sequences for 10, 50, and 100 tosses
tosses_list = [10, 50, 100]
sequences_dict = {}

for n_tosses in tosses_list:
    sequences = generate_sequences(n_tosses, n_experiments)
       sequences_dict[n_tosses] = sequences

# Display results
for n_tosses, sequences in sequences_dict.items():
    print(f"Results for {n_tosses} tosses:")
    for sequence in sequences:
        print(sequence)
    print("\n")
        

This python code will give you Monte Carlo simulation result


import numpy as np

# Function to simulate coin toss
def coin_toss_simulation(n_tosses, n_experiments):
    results = []
    for _ in range(n_experiments):
        tosses = np.random.choice(['H', 'T'], size=n_tosses)
        heads_count = np.sum(tosses == 'H')
        results.append(heads_count)
    return results

# Function to calculate theoretical probability of exactly k heads
def theoretical_probability(n_tosses, k):
    from math import comb
    probability = comb(n_tosses, k) * (0.5 ** k) * (0.5 ** (n_tosses - k))
    return probability

# Function to calculate probability from simulation results
def calculate_probability(results, k):
    count_k_heads = results.count(k)
    probability = count_k_heads / len(results)
    return probability

# Parameters
n_experiments = 1000

# Simulate for 10, 50, and 100 tosses
tosses_list = [10, 50, 100]
results_dict = {}

for n_tosses in tosses_list:
    results = coin_toss_simulation(n_tosses, n_experiments)
    results_dict[n_tosses] = results

# Display results and calculate probabilities
for n_tosses, results in results_dict.items():
    print(f"Results for {n_tosses} tosses (first 10 outcomes):")
    print(results[:10])  # Display first 10 outcomes for brevity
    
    if n_tosses == 10:
        k = 5
    elif n_tosses == 50:
        k = 25
    elif n_tosses == 100:
        k = 50
    
    # Theoretical probability
    theoretical_prob = theoretical_probability(n_tosses, k)
    print(f"Theoretical probability of getting exactly {k} heads in {n_tosses} tosses: {theoretical_prob:.4f}")
    
    # Monte Carlo probability
    monte_carlo_prob = calculate_probability(results, k)
    print(f"Monte Carlo probability of getting exactly {k} heads in {n_tosses} tosses: {monte_carlo_prob:.4f}")
    print("\n")
        

These code snippets are provided for practice purposes. Feel free to experiment with different values and run the codes to see the results. Please use different values for your activity.

If you have any issue with code please leave a comment below.

Comments