1 /* Implementation of the IRAND, RAND, and SRAND intrinsics.
2 Copyright (C) 2004 Free Software Foundation, Inc.
3 Contributed by Steven G. Kargl <kargls@comcast.net>.
5 This file is part of the GNU Fortran 95 runtime library (libgfortran).
7 Libgfortran is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
12 Libgfortran is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with libgfor; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* Simple multiplicative congruent algorithm.
23 The period of this generator is approximately 2^31-1, which means that
24 it should not be used for anything serious. The implementation here
25 is based of an algorithm from S.K. Park and K.W. Miller, Comm. ACM,
26 31, 1192-1201 (1988). It is also provided solely for compatibility
30 #include "libgfortran.h"
32 #define GFC_RAND_A 16807
33 #define GFC_RAND_M 2147483647
34 #define GFC_RAND_M1 (GFC_RAND_M - 1)
36 static GFC_UINTEGER_8 rand_seed
= 1;
39 /* Set the seed of the irand generator. Note 0 is a bad seed. */
42 prefix(srand
) (GFC_INTEGER_4
*i
)
44 rand_seed
= (GFC_UINTEGER_8
) (*i
!= 0) ? *i
: 123459876;
48 /* Return an INTEGER in the range [1,GFC_RAND_M-1]. */
51 prefix(irand
) (GFC_INTEGER_4
*i
)
58 /* Return the next RN. */
62 /* Reset the RN sequence to system-dependent sequence and return the
69 /* Seed the RN sequence with j and return the first value. */
74 rand_seed
= GFC_RAND_A
* rand_seed
% GFC_RAND_M
;
76 return (GFC_INTEGER_4
) rand_seed
;
80 /* Return a REAL in the range [0,1). Cast to double to use the full
81 range of pseudo-random numbers returned by irand(). */
84 prefix(rand
) (GFC_INTEGER_4
*i
)
89 val
= (GFC_REAL_4
)((double)(prefix(irand
) (i
) - 1) / (double) GFC_RAND_M1
);