如何生成与rand(1..117)结果偏差±20且限1-117的随机数?
Generate a Constrained Random Number Relative to a First Value
Got it, let's walk through how to generate that second random number exactly as you need it.
First, let's recap your requirements clearly:
- You start with a random number from
rand(1..117)(you mentioned getting 80 as an example) - The second number needs to be within ±20 of the first one
- It also has to stay strictly between 1 and 117 (no negatives, no numbers over 117)
Step-by-Step Solution
The key here is to calculate a valid range for the second number that respects both the ±20 constraint and the 1-117 bounds. Here's how to do it in Ruby (since you used Ruby's rand syntax):
# First, get your initial random number (we'll use 80 as your example) first_num = 80 # or rand(1..117) to generate it dynamically # Calculate the lower bound: don't go below 1 lower_bound = [first_num - 20, 1].max # Calculate the upper bound: don't go above 117 upper_bound = [first_num + 20, 117].min # Generate the second random number within this safe range second_num = rand(lower_bound..upper_bound)
How This Works
- When your first number is 80:
lower_boundbecomes80-20=60(which is above 1, so we keep it), andupper_boundbecomes80+20=100(which is below 117, so we keep it). So your second number will be between 60 and 100—all values here are within ±20 of 80 and stay in the 1-117 range. - If your first number was closer to a boundary (like 15):
lower_boundwould be1(since 15-20=-5, we cap it at 1), andupper_boundis 35. So you get a number between 1 and 35. - If your first number was 110:
lower_boundis 90,upper_boundis 117 (since 110+20=130 exceeds 117, we cap it). So you get a number between 90 and 117.
Quick Note on Your Examples
A heads-up: some of the numbers you listed (like 50, 35, 108) are actually outside the ±20 range from 80. For example, 80-50=30, which is more than 20. Valid examples would be 64, 79, 99, 88—all of these are within 60-100, so they fit both constraints perfectly.
内容的提问来源于stack exchange,提问作者chris
相关产品推荐
相关产品推荐

