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

187
Views
What is the best way of generating a random value within a closed interval in C?

In general, when I need to generate a random value within a closed interval (considering B as the beginning and E as the end of the interval) in C, I use one of the following approaches:

Approach 1:

n = round(B + ( (float)rand() / RAND_MAX ) * (E - B));

Approach 2:

n = B + rand()%(E - B+1);

Both of them consider the initialization of the random seed with the function time():

srand(time(NULL));

In Linux systems, both approaches seem good enough for generating interesting random values. However, in Windows systems, sometimes the numbers do not appear to be random enough.

Investigating these systems, I've found that the value of RAND_MAX is different. In the Linux systems that I have tested RAND_MAX is 2147483647. In these windows systems with a not-so-good behavior, RAND_MAX is 32767.

I think that with a larger RAND_MAX value we can generate better random numbers. But I'm not sure.

With this in mind, my question is: Is there some good way of generating interesting random numbers (within a closed interval) that work well on all systems?

Besides that, my approaches 1 and 2 are good approaches for generating random numbers within a closed interval?

over 4 years ago · Santiago Trujillo
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!