简体   繁体   中英

Random number between two ranges

I'm trying to generate a random number between two ranges in Objective-C. For example between [-50;-30] and [30,50] .

I achieved to do it between [-50,50] but I need to eliminate all the values between [-30,30] .

int rads = -50 + arc4random() % (50 - (-50));

Thanks for your help.

To build on the previous answer (which has been removed):

  1. use arc4random_uniform

  2. use correct upper bounds and correct arithmetics

Regarding 1: arc4random_uniform(50) will yield a number between 0 and 49 inclusive. It will yield that value with a correct unfirom distribution. Using only arc4random % something introduces modulo bias.

Regarding 2: You are trying not to retrieve 40 values but 42 since you want to be able to retrieve the upper a nd the lower bound values as well. If we simplify the bounds we can see the error better, assume [-5;-3] and [3;5] : you want the numbers -5,-4,-3,3,4,5 six values, not 4.

Solution:

int rads = arc4random_uniform(42) - 20; // values between -20 and 21 inclusive, 42 different numbers
if (rads <= 0) { // subtract from the lower 21 values [-20;0]
    rads = rads - 30; // [-50;-30]
} else { // add to the upper 21 values [1;21]
    rads = rads + 29; // [30;50]
}

More general for symmetric upper and lower bounds

int lower = 30;
int upper = 50;
int diff = upper - lower;
int rads = arc4random_uniform((diff + 1) * 2) - diff; // values between -diff and (diff+1) inclusive, ((diff+1)*2) different numbers
if (rads <= 0) { // subtract from the lower (diff+1) values [-diff;0]
    rads = rads - lower; // [-upper;-lower]
} else { // add to the upper 21 values [1;diff+1]
    rads = rads + lower - 1; // [lower;upper]
}

Note that you can simplfy the code a bit by moving the conditional substraction up to the initial rads calculation and changing the later addition and the condition for adding. BUT that would make the code a bit less readable and intutive.

One thing to try would be choosing randomly either 1 or -1. Then multiplying that by another random number between 30-50 would work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM