While循环无法约束参数值范围,如何修正计算使结果符合区间要求?
Fixing Your Loop to Keep Values Within 0.2–0.29
It looks like two key issues are causing your values to go out of bounds (and even turn negative):
1. You’re not updating the Omo array
Your Omo array is initialized to zeros except for the first element. But after calculating Omn[i], you never assign it back to Omo[i]. That means for all i > 0, Omo[i] stays zero—so every subsequent iteration starts from zero instead of the previous valid value. That’s why you’re seeing negatives and values like 0.01.
2. You’re not validating the generated value before accepting it
Your while True loop runs without checking if the result falls within your desired range before assigning it to Omn[i]. You need to generate a candidate value, verify it’s between 0.2 and 0.29, and only keep it if it meets the criteria.
Corrected Code
import numpy as np import warnings warnings.filterwarnings("ignore") N = 1000 Omo = np.zeros((N,)) Omo[0] = 0.24 Omn = np.zeros((N,)) for i in range(1, N): while True: # Generate a candidate value based on the previous valid Omo entry candidate = Omo[i-1] + 0.01 * np.random.normal() # Check if it's within your desired range if 0.2 <= candidate <= 0.29: Omn[i] = candidate # Update Omo so the next iteration uses this valid value Omo[i] = candidate break # Optional: Verify the results print("Min value in Omn:", np.min(Omn)) print("Max value in Omn:", np.max(Omn))
Key Changes Explained
- Updating
Omo[i]: After finding a valid candidate, we assign it toOmo[i]so the next loop iteration uses this valid value as the starting point (not zero). - Range Validation: The
whileloop now generates a candidate, checks if it’s between 0.2 and 0.29, and only exits the loop when a valid value is found. This ensures no out-of-bounds values are stored inOmn. - Cleaned up unused imports: The
from math import *wasn’t being used, so I removed it to simplify the code.
Notes
- If you want to track how many iterations the
whileloop takes to find a valid value, you can add a counter inside the loop (like your originalnumvariable). - Since
np.random.normal()can produce large deviations (though rare with the 0.01 scaling), the loop might run a few extra times occasionally—but it will always find a valid value eventually (the normal distribution covers all real numbers, so there’s always a chance to get a value in your range).
内容的提问来源于stack exchange,提问作者Bob
相关产品推荐
相关产品推荐

