Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2. FUNCTION
  3. <<random>>, <<srandom>>---pseudo-random numbers
  4.  
  5. INDEX
  6.         random
  7. INDEX
  8.         srandom
  9.  
  10. ANSI_SYNOPSIS
  11.         #define _XOPEN_SOURCE 500
  12.         #include <stdlib.h>
  13.         long int random(void);
  14.         void srandom(unsigned int <[seed]>);
  15.  
  16.  
  17.  
  18. DESCRIPTION
  19. <<random>> returns a different integer each time it is called; each
  20. integer is chosen by an algorithm designed to be unpredictable, so
  21. that you can use <<random>> when you require a random number.
  22. The algorithm depends on a static variable called the ``random seed'';
  23. starting with a given value of the random seed always produces the
  24. same sequence of numbers in successive calls to <<random>>.
  25.  
  26. You can set the random seed using <<srandom>>; it does nothing beyond
  27. storing its argument in the static variable used by <<rand>>.  You can
  28. exploit this to make the pseudo-random sequence less predictable, if
  29. you wish, by using some other unpredictable value (often the least
  30. significant parts of a time-varying value) as the random seed before
  31. beginning a sequence of calls to <<rand>>; or, if you wish to ensure
  32. (for example, while debugging) that successive runs of your program
  33. use the same ``random'' numbers, you can use <<srandom>> to set the same
  34. random seed at the outset.
  35.  
  36. RETURNS
  37. <<random>> returns the next pseudo-random integer in sequence; it is a
  38. number between <<0>> and <<RAND_MAX>> (inclusive).
  39.  
  40. <<srandom>> does not return a result.
  41.  
  42. NOTES
  43. <<random>> and <<srandom>> are unsafe for multi-threaded applications.
  44.  
  45. _XOPEN_SOURCE may be any value >= 500.
  46.  
  47. PORTABILITY
  48. <<random>> is required by XSI. This implementation uses the same
  49. algorithm as <<rand>>.
  50.  
  51. <<random>> requires no supporting OS subroutines.
  52. */
  53.  
  54. #ifndef _REENT_ONLY
  55.  
  56. #include <stdlib.h>
  57. #include <reent.h>
  58.  
  59. void
  60. _DEFUN (srandom, (seed), unsigned int seed)
  61. {
  62.   struct _reent *reent = _REENT;
  63.  
  64.   _REENT_CHECK_RAND48(reent);
  65.   _REENT_RAND_NEXT(reent) = seed;
  66. }
  67.  
  68. long int
  69. _DEFUN_VOID (random)
  70. {
  71.   struct _reent *reent = _REENT;
  72.  
  73.   /* This multiplier was obtained from Knuth, D.E., "The Art of
  74.      Computer Programming," Vol 2, Seminumerical Algorithms, Third
  75.      Edition, Addison-Wesley, 1998, p. 106 (line 26) & p. 108 */
  76.   _REENT_CHECK_RAND48(reent);
  77.   _REENT_RAND_NEXT(reent) =
  78.      _REENT_RAND_NEXT(reent) * __extension__ 6364136223846793005LL + 1;
  79.   return (long int)((_REENT_RAND_NEXT(reent) >> 32) & RAND_MAX);
  80. }
  81.  
  82. #endif /* _REENT_ONLY */
  83.