Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
Random number range, exclude 0

I have the following function that generates a random number between -10 and 2:

#include <stdlib.h>
#include <time.h>

static int
getRandomReturnCode(void)
{
    int N = 2,
        M = -10;

    srand(time(NULL));

    r = M + rand() / (RAND_MAX / (N - M + 1) + 1);

    if (r == 0){
        getRandomReturnCode();
    }

    return r;
}

Currently, if a return code of 0 (success) is returned, it will recursively call the function over until a non-zero return code is met and returned. What can I do to improve my code such that 0 is excluded from the range of randomly chosen numbers?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Whatever you do, don't redraw if a returned value is 0: that will introduce statistical bias into the result.

The best thing to do here is to draw between -10 and 1 inclusive and add 1 to any non-negative output.

Finally, call srand once else you'll ruin the generator's statistical properties.

(Briefly - since this comment is more for the mathematics site - and restricting the argument to a linear congruential generator, what tends to happen if you omit generated values is that you increase the variance of the resulting distribution so it's no longer uniform. A previously drawn small number will be linearly related to the subsequent drawing as the generator's modulus will have no effect. This autocorrelation - necessary for the resulting distribution to be uniform - of adjacent drawings will be curtailed if drawings are discarded and that increases the sample variance.)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!