中心极限定理代码调试求助:电梯载重概率计算结果异常
Let's break down exactly why your code is returning 1.0 instead of the expected 0.0098, and fix the issues step by step.
The Core Issues in Your Code
Looking at your code side-by-side with the correct version, there are two critical points (one breaking the calculation entirely, another causing confusion):
1. Fatal Operator Precedence Bug in Z-Score Calculation
The biggest problem is how you compute the z-score in your cdf function:
z=x-mean/var
In Python, division (/) has higher priority than subtraction (-), so this line calculates x - (mean / var) instead of the correct (x - mean) / var.
Let's plug in your input values to see the stark difference:
- Correct Z-score:
(9800 - (49*205)) / (sqrt(49)*15) = (9800-9945)/105 = -145/105 ≈ -1.38095 - Your code's Z-score:
9800 - (9945 / 105) = 9800 - 94.714 ≈ 9705.286
A z-score of ~9705 is way outside the normal distribution's range, so the CDF returns 1.0 (since nearly 100% of the data falls below that value).
2. Misleading Variable Naming
You named your input parameter var, but you're passing in var_sum which is the standard deviation of the sum (not variance). Variance would be sigma², but your input is the standard deviation (15). This doesn't break the code directly, but it's easy to mix up—using sigma like the correct code does makes the intent clearer.
Fixed Version of Your Code
Here's your code with the critical bug fixed, plus improved naming for readability:
import math maxwt = int(input()) n = int(input()) mean = int(input()) sigma = int(input()) # Renamed from var to sigma (standard deviation) sigma_sum = math.sqrt(n) * sigma mean_sum = mean * n def cdf(x, mu, sigma): z = (x - mu) / sigma # Fixed parentheses for correct z-score calculation return (1 + math.erf(z / math.sqrt(2))) / 2 print(round(cdf(maxwt, mean_sum, sigma_sum), 4))
Testing this with your input 9800 49 205 15 will return the expected 0.0098.
Quick CLT Recap
For the sum of n independent random variables:
- The mean of the sum is
n * mu - The standard deviation of the sum is
sqrt(n) * sigma(notn*sigma—this is a common gotcha!) - We calculate the z-score for the maximum weight, then use the normal distribution's CDF to find the probability the sum stays under the elevator's limit.
内容的提问来源于stack exchange,提问作者Pranav Pushkar

