Generate random value with a distance between them

Hey all!

I have a question. I have a piece of code that generates random numbers and then the motor moves those positions. However, sometimes, the random numbers are almost the same (e.g. 591 and 595). How can I make sure that there is always a distnace of for example 50 between 2 randomly generated numbers?

Thanks in advange!

However, sometimes, the random numbers are almost the same (e.g. 591 and 595)

Random numbers should be random, and that will happen. They can even be equal! If you make a rule about a "distance between them" they will not be random.

But post the code, following forum rules.

Remember the previous number, check the new against the previous, if not big enough difference take a new random number.

Yes. Just keep generating random numbers until you get one you like.

There is no way to tell the random() function that you want a number that isn't really random.

Steve

Just keep generating random numbers until you get one you like.

Very useful for cheating at cards and dice!

jremington:
Very useful for cheating at cards and dice!

Don't tell everyone, I need whatever minor advantage I can get.

Steve

Hahaha, thanks all for the tips and help! Good to know!

@wvmarle, thanks! I will try that.

Personally, I would avoid repeated calls to random - you can't predict how many times you'll have to call it. I would just call it once and map the value to a range that starts 50 away from the first one.

you can't predict how many times you'll have to call it.

Why should that matter?

If you do it wrong you can get stuck in a loop for some time.

gutbag:
Personally, I would avoid repeated calls to random - you can't predict how many times you'll have to call it. I would just call it once and map the value to a range that starts 50 away from the first one.

How would you map a value to a number that is at least 50 higher or 50 lower than the first number?

Steve

If it's higher but not high enough: add 50. If it's lower but not low enough: subtract 50. Apply limits as needed. Should be random enough for OPs application.

If you do it wrong you can get stuck in a loop for some time.

Great advice!

Except that other bad things can happen if you "do it wrong".

If your range is 1000 and you need the 50 distance above or below, the right way would be to think that the range of the random next number is from 50 to 950. If the new number is greater than the old number, add 50. If less (or equal), subtract 50. If it goes over 1000 or under 0, have it wrap around. Simple forward logic, no risk for endless loop.