simulation code

import random

def simulate_one_game():
    # Returns number of tosses needed to get 3 in a row
    tosses = []
    while len(tosses) < 3 or (tosses[-3:] != ['H', 'H', 'H'] and tosses[-3:] != ['T', 'T', 'T']):
        toss = random.choice(['H', 'T'])
        tosses.append(toss)
    return len(tosses)

def estimate_probability(n_simulations=1000000, threshold=10):
    # Count games that take more than threshold tosses
    count_over_threshold = 0
    
    for _ in range(n_simulations):
        tosses_needed = simulate_one_game()
        if tosses_needed > threshold:
            count_over_threshold += 1
    
    return count_over_threshold / n_simulations

# Run simulation
n_sims = 1000000
threshold = 10
prob = estimate_probability(n_sims, threshold)

print(f"Based on {n_sims:,} simulations:")
print(f"Probability of needing more than {threshold} tosses: {prob:.6f}")

# Optional: Get distribution of number of tosses needed
def get_distribution(n_simulations=100000, max_tosses=50):
    distribution = [0] * (max_tosses + 1)
    
    for _ in range(n_simulations):
        tosses = simulate_one_game()
        if tosses <= max_tosses:
            distribution[tosses] += 1
    
    # Convert to probabilities
    distribution = [x/n_simulations for x in distribution]
    
    return distribution

# Print distribution
dist = get_distribution()
print("\nDistribution of number of tosses needed:")
for i, prob in enumerate(dist):
    if prob > 0:
        print(f"{i} tosses: {prob:.4f}")

 

請您先登陸,再發跟帖!