硬币抛掷模拟中的意外概率:01与11序列终止次数的疑问
Hey there! Let's figure out why your coin flip simulation's termination counts for sequences 01 and 11 aren't matching your expectations. First, let's get the theoretical expectations straight—this will help you validate if your "expected" values were even correct to begin with:
- For the target sequence
01, the expected number of flips to terminate is 4. - For
11, that expected number jumps to 6.
If your script's average results (over many trials) are far from these numbers, here are the most common issues to check:
1. You're only testing a small number of trials
Single coin flip runs are super random—you might get 11 in 2 flips one time, and 15 flips the next. To get close to the theoretical average, you need to run hundreds or thousands of simulations and take the mean. If you're only looking at a handful of runs, the results will be all over the place.
2. Your termination check logic is flawed
The most common mistake here is not properly tracking the trailing characters of your flip sequence. For example:
- If you're rebuilding the entire flip string every time and checking for a match anywhere (not just at the end), you might terminate early when the sequence appears in the middle (which isn't what you want—you need it to be the ending of the flip sequence).
- Or, if you're not keeping enough trailing characters to detect overlaps, you might miss valid termination conditions.
Here's a corrected way to handle the termination check efficiently:
import random def coin_series(target): target_len = len(target) if target_len == 0: return 0 # Keep only the last (target_len -1) characters to check for matches current_trailing = "" flip_count = 0 while True: flip = str(random.randint(0, 1)) flip_count += 1 # Check if adding this flip completes the target sequence if (current_trailing + flip).endswith(target): return flip_count # Update trailing characters to keep only what we need for next check if target_len > 1: current_trailing = (current_trailing + flip)[-(target_len - 1):] else: current_trailing = flip
3. Your random number generator is biased
Make sure you're generating 0s and 1s with equal probability. Using random.randint(0, 1) or random.choice([0, 1]) works—avoid custom logic that might accidentally weight one side more than the other.
4. You're miscounting the flips
Double-check that you're incrementing your flip counter every time you generate a new coin flip. It's easy to accidentally count extra steps or miss increments in loop logic.
To verify, run a bulk test with the corrected script above:
def run_trials(target, num_trials=10000): total_flips = 0 for _ in range(num_trials): total_flips += coin_series(target) return total_flips / num_trials print(f"Average flips for '01': {run_trials('01'):.2f}") print(f"Average flips for '11': {run_trials('11'):.2f}")
You should see averages hovering around 4.0 for 01 and 6.0 for 11.
内容的提问来源于stack exchange,提问作者Psmith

