rand.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #define _RESEARCH_SOURCE
  10. #include <stdlib.h>
  11. #include <libv.h>
  12. /*
  13. random number generator from cacm 31 10, oct 88
  14. for 32 bit integers (called long here)
  15. */
  16. #ifdef MAIN
  17. #define A 16807
  18. #define M 2147483647
  19. #define Q 127773
  20. #define R 2836
  21. #else
  22. #define A 48271
  23. #define M 2147483647
  24. #define Q 44488
  25. #define R 3399
  26. #endif
  27. static int32_t seed = 1;
  28. void
  29. srand(unsigned int newseed)
  30. {
  31. seed = newseed;
  32. }
  33. int32_t
  34. lrand(void)
  35. {
  36. int32_t lo, hi, test;
  37. hi = seed/Q;
  38. lo = seed%Q;
  39. test = A*lo - R*hi;
  40. if(test > 0)
  41. seed = test;
  42. else
  43. seed = test+M;
  44. return(seed);
  45. }
  46. int
  47. rand(void)
  48. {
  49. return lrand()%(RAND_MAX+1);
  50. }
  51. #ifdef MAIN
  52. main()
  53. {
  54. int i;
  55. for(i = 0; i < 10000; i++)
  56. rand();
  57. if(seed == 1043618065)
  58. printf(" rand: pass\n");
  59. else
  60. printf("*****rand: fail; seed=%u, should be 1043618065\n", seed);
  61. exit(0);
  62. }
  63. #endif