OSDN Git Service

* check.c (gfc_check_second_sub, gfc_check_irand, gfc_check_rand
[pf3gnuchains/gcc-fork.git] / libgfortran / intrinsics / rand.c
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>.
4
5 This file is part of the GNU Fortran 95 runtime library (libgfortran).
6
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.
11
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.
16
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.  */
21
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 
27    with G77.  */
28
29 #include "config.h"
30 #include "libgfortran.h"
31
32 #define GFC_RAND_A      16807
33 #define GFC_RAND_M      2147483647
34 #define GFC_RAND_M1     (GFC_RAND_M - 1)
35
36 static GFC_UINTEGER_8 rand_seed = 1;
37
38
39 /* Set the seed of the irand generator.  Note 0 is a bad seed.  */
40
41 void
42 prefix(srand) (GFC_INTEGER_4 *i)
43 {
44   rand_seed = (GFC_UINTEGER_8) (*i != 0) ? *i : 123459876;
45 }
46
47
48 /* Return an INTEGER in the range [1,GFC_RAND_M-1].  */
49
50 GFC_INTEGER_4
51 prefix(irand) (GFC_INTEGER_4 *i)
52 {
53   
54   GFC_INTEGER_4 j = *i;
55
56   switch (j)
57   {
58     /* Return the next RN. */
59     case 0:
60       break;
61
62     /* Reset the RN sequence to system-dependent sequence and return the
63        first value.  */
64     case 1:
65       j = 0;
66       prefix(srand) (&j);
67       break;
68     
69     /* Seed the RN sequence with j and return the first value.  */
70     default:
71       prefix(srand) (&j);
72    }
73
74    rand_seed = GFC_RAND_A * rand_seed % GFC_RAND_M;
75
76    return (GFC_INTEGER_4) rand_seed;
77 }
78
79
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().  */
82
83 GFC_REAL_4
84 prefix(rand) (GFC_INTEGER_4 *i)
85 {
86   GFC_REAL_4 val;
87
88   do 
89     val = (GFC_REAL_4)((double)(prefix(irand) (i) - 1) / (double) GFC_RAND_M1);
90   while (val == 1.0);
91
92   return val;
93 }