简体   繁体   中英

rand() behaves differently between macOS and Linux

I'm trying to generate a random-number sequence with rand(). I have something like this:

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


int Random(int min, int max)
{
  /* returns a random integer in [min, max] */

  double uniform; // random variable from uniform distribution of [0, 1]
  int ret; // return value
  srand((unsigned int)clock());

  uniform = rand() / (double)RAND_MAX;
  ret = (int)(uniform * (double)(max - min)) + min;

  return ret;
}


int main(void)
{
  for(int i=0; i<10; i++)
    printf("%d ", Random(0, 100));
  printf("\n");

  return 0;
}

It made different results when executed on macOS v10.14 (Mojave) and Ubuntu 18.04 (Bionic Beaver).

It works on Ubuntu:

76 42 13 49 85 7 43 28 15 1

But not on macOS:

1 1 1 1 1 1 1 1 1 1

Why doesn't it work well on macOS? Is there something different in random number generators?

I'm a Mac user. To generate random numbers I initialise the seed like this:

srand(time(NULL));

Plus, try initialising it in your main.

If reproducible "random" numbers are something you care about, you should avoid the rand function. The C standard doesn't specify exactly what the sequence produced by rand is, even if the seed is given via srand . Notably:

  • rand uses an unspecified random number algorithm, and that algorithm can differ between C implementations, including versions of the same standard library .
  • rand returns values no greater than RAND_MAX , and RAND_MAX can differ between C implementations.

Instead, you should use an implementation of a pseudorandom number generator with a known algorithm, and you should also rely on your own way to transform pseudorandom numbers from that algorithm into the numbers you desire. (For example, I give ways to do so for uniform floating-point numbers . Note that there are other things to consider when reproducibility is important.)

See also the following:

rand is obsolete in Mac. Use random() instead.

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