2

I'm trying to return a random number within a specific range while also excluding a specific range within it. I've seen similar questions posed, but I can't get it to work. Here's what I have so far:

var x = xFunction();

function xFunction() {
    return parseFloat(Math.round(Math.random() * 2250) / 1000).toFixed(3);  
}

if (x > 1.250 && x < 2.001 ) {
  // this number is excluded so redo xFunction();  
} else {
  // this number is acceptable so do some code
}

Any help is appreciated. Thank you so much!

3
  • generate a random 1/0, if its 0 generate the lower range if its 1 generate the upper? Commented Aug 14, 2018 at 16:07
  • Good call @Alex K. That's a simple solution that would work. Commented Aug 14, 2018 at 16:42
  • @AlexK. Picking the range based on 1/0 choice will mean about half the values will come from the range 2 - 2.25 and the other half from 0 - 1.25 even though the range 2-2.25 represents much fewer than half the distribution. This will bias the randomness aggressively toward the top range. Commented Aug 14, 2018 at 16:58

1 Answer 1

3

One way to handle this is to look for a random number in the range with the excluded part removed. For example if you were looking for a random number between 0 and 100 with 70-80 removed, you would find a random number between 0 and 90 (removing the 10 from the excluded range). Then if any value falls above 70 you add the excluded range back. This will preserve the appropriate ratio of randomness for each range and you should see results mostly from the lower range with a few from the upper range because that is a larger percentage of the distribution.

(I've moved the division and rounding out of the function just to make it clearer how it works.)

function xFunction(max, exclude) {
  let excluded_range = exclude[1] - exclude[0]
  let rand = Math.random() * (max - excluded_range)
  if (rand > exclude[0]) rand += excluded_range
  return rand
}


for (let x = 0; x<10; x++){
  let r = xFunction(2250, [1250, 2000])
  console.log ((r / 1000).toFixed(3));  

}

If you pick a random 0 or 1 and use that to determine the range as recommended in the comments, you will end up with approximately half of the result in the much smaller top range. This will bias your results toward that top range rather than truly finding a random number within the whole range.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.