rand.c 742 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. * Copyright (c) 2006-2018, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. */
  9. #include <stdlib.h>
  10. #include <stdint.h>
  11. #include <sys/types.h>
  12. static unsigned int _seed=1;
  13. /* Knuth's TAOCP section 3.6 */
  14. #define M ((1U<<31) -1)
  15. #define A 48271
  16. #define Q 44488 // M/A
  17. #define R 3399 // M%A; R < Q !!!
  18. int rand_r(unsigned int* seed)
  19. { int32_t X;
  20. X = *seed;
  21. X = A*(X%Q) - R * (int32_t) (X/Q);
  22. if (X < 0)
  23. X += M;
  24. *seed = X;
  25. return X;
  26. }
  27. int rand(void) {
  28. return rand_r(&_seed);
  29. }
  30. void srand(unsigned int i)
  31. {
  32. _seed=i;
  33. }
  34. int random(void) __attribute__((alias("rand")));
  35. void srandom(unsigned int i) __attribute__((alias("srand")));