基于Monte Carlo方法的Python正态分布服务时长概率计算咨询
Got it, let's work through this problem step by step using Monte Carlo simulation in Python. First, let's restate the key info we have: the service duration follows a normal distribution with mean = 60 minutes and standard deviation = 20 minutes.
Monte Carlo is perfect here because we can generate thousands (or millions) of simulated service times, then just count how many fit each of our conditions—no need to mess with complex analytical formulas if you prefer a more intuitive approach.
Step 1: Set Up the Environment
We'll use numpy to generate our normal distribution samples efficiently. If you don't have it installed, run pip install numpy first.
Step 2: Write the Simulation Code
Here's a complete script that handles parts a, b, and c. I've added comments to explain each part:
import numpy as np # Define the parameters of the normal distribution mean_time = 60 # minutes std_dev = 20 # minutes num_samples = 1_000_000 # More samples = more accurate results # Generate a million simulated service times from the normal distribution service_times = np.random.normal(loc=mean_time, scale=std_dev, size=num_samples) # Calculate probabilities for each question # a. Service time < 60 minutes (1 hour) prob_less_60 = np.mean(service_times < 60) # b. Service time > 50 minutes prob_more_50 = np.mean(service_times > 50) # c. Service time > 80 minutes prob_more_80 = np.mean(service_times > 80) # Print the results print(f"a. Probability service time < 1 hour: {prob_less_60:.4f} ({prob_less_60*100:.2f}%)") print(f"b. Probability service time > 50 minutes: {prob_more_50:.4f} ({prob_more_50*100:.2f}%)") print(f"c. Probability service time > 80 minutes: {prob_more_80:.4f} ({prob_more_80*100:.2f}%)")
Step 3: Interpret the Results
When you run this code, you'll get results close to the theoretical values:
- Part a: ~50% (since the mean of the normal distribution is 60, exactly half the samples will be below the mean)
- Part b: ~69.15% (50 is 0.5 standard deviations below the mean; the CDF at 50 is ~0.3085, so 1 - 0.3085 = 0.6915)
- Part c: ~15.87% (80 is 1 standard deviation above the mean; the CDF at 80 is ~0.8413, so 1 - 0.8413 = 0.1587)
The Monte Carlo results will shift slightly each run (due to random sampling) but will converge to these theoretical values as you increase num_samples.
Note on Part d
It looks like your part d got cut off! If you can share the full question (e.g., "If a service has already taken X minutes, what's the probability it takes Y more minutes?"), I can easily extend this code to handle that scenario too.
内容的提问来源于stack exchange,提问作者Laura Marinescu

