1 ------------------------------------------------------------------------------
3 -- GNAT RUN-TIME COMPONENTS --
5 -- S Y S T E M . R A N D O M _ N U M B E R S --
9 -- Copyright (C) 2007,2009 Free Software Foundation, Inc. --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception, --
20 -- version 3.1, as published by the Free Software Foundation. --
22 -- You should have received a copy of the GNU General Public License and --
23 -- a copy of the GCC Runtime Library Exception along with this program; --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
25 -- <http://www.gnu.org/licenses/>. --
27 -- GNAT was originally developed by the GNAT team at New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc. --
30 ------------------------------------------------------------------------------
32 ------------------------------------------------------------------------------
34 -- The implementation here is derived from a C-program for MT19937, with --
35 -- initialization improved 2002/1/26. As required, the following notice is --
36 -- copied from the original program. --
38 -- Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, --
39 -- All rights reserved. --
41 -- Redistribution and use in source and binary forms, with or without --
42 -- modification, are permitted provided that the following conditions --
45 -- 1. Redistributions of source code must retain the above copyright --
46 -- notice, this list of conditions and the following disclaimer. --
48 -- 2. Redistributions in binary form must reproduce the above copyright --
49 -- notice, this list of conditions and the following disclaimer in the --
50 -- documentation and/or other materials provided with the distribution.--
52 -- 3. The names of its contributors may not be used to endorse or promote --
53 -- products derived from this software without specific prior written --
56 -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
57 -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
58 -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
59 -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
60 -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
61 -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
62 -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
63 -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
64 -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
65 -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
66 -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
68 ------------------------------------------------------------------------------
70 ------------------------------------------------------------------------------
72 -- This is an implementation of the Mersenne Twister, twisted generalized --
73 -- feedback shift register of rational normal form, with state-bit --
74 -- reflection and tempering. This version generates 32-bit integers with a --
75 -- period of 2**19937 - 1 (a Mersenne prime, hence the name). For --
76 -- applications requiring more than 32 bits (up to 64), we concatenate two --
79 -- See http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html for --
82 -- In contrast to the original code, we do not generate random numbers in --
83 -- batches of N. Measurement seems to show this has very little if any --
84 -- effect on performance, and it may be marginally better for real-time --
85 -- applications with hard deadlines. --
87 ------------------------------------------------------------------------------
89 with Ada.Calendar; use Ada.Calendar;
90 with Ada.Unchecked_Conversion;
91 with Interfaces; use Interfaces;
95 package body System.Random_Numbers is
97 -------------------------
98 -- Implementation Note --
99 -------------------------
101 -- The design of this spec is very awkward, as a result of Ada 95 not
102 -- permitting in-out parameters for function formals (most naturally,
103 -- Generator values would be passed this way). In pure Ada 95, the only
104 -- solution is to use the heap and pointers, and, to avoid memory leaks,
107 -- This is awfully heavy, so what we do is to use Unrestricted_Access to
108 -- get a pointer to the state in the passed Generator. This works because
109 -- Generator is a limited type and will thus always be passed by reference.
111 Low31_Mask : constant := 2**31-1;
112 Bit31_Mask : constant := 2**31;
114 Matrix_A_X : constant array (State_Val range 0 .. 1) of State_Val :=
117 Y2K : constant Calendar.Time :=
119 (Year => 2000, Month => 1, Day => 1, Seconds => 0.0);
120 -- First Year 2000 day
122 subtype Image_String is String (1 .. Max_Image_Width);
126 procedure Init (Gen : out Generator; Initiator : Unsigned_32);
127 -- Perform a default initialization of the state of Gen. The resulting
128 -- state is identical for identical values of Initiator.
130 procedure Insert_Image
131 (S : in out Image_String;
134 -- Insert image of V into S, in the Index'th 11-character substring
136 function Extract_Value (S : String; Index : Integer) return State_Val;
137 -- Treat S as a sequence of 11-character decimal numerals and return
138 -- the result of converting numeral #Index (numbering from 0)
140 function To_Unsigned is
141 new Unchecked_Conversion (Integer_32, Unsigned_32);
142 function To_Unsigned is
143 new Unchecked_Conversion (Integer_64, Unsigned_64);
149 function Random (Gen : Generator) return Unsigned_32 is
150 G : Generator renames Gen'Unrestricted_Access.all;
158 Y := (G.S (I) and Bit31_Mask) or (G.S (I + 1) and Low31_Mask);
159 Y := G.S (I + M) xor Shift_Right (Y, 1) xor Matrix_A_X (Y and 1);
163 Y := (G.S (I) and Bit31_Mask) or (G.S (I + 1) and Low31_Mask);
164 Y := G.S (I + (M - N))
165 xor Shift_Right (Y, 1)
166 xor Matrix_A_X (Y and 1);
170 Y := (G.S (I) and Bit31_Mask) or (G.S (0) and Low31_Mask);
171 Y := G.S (M - 1) xor Shift_Right (Y, 1) xor Matrix_A_X (Y and 1);
182 Y := Y xor Shift_Right (Y, 11);
183 Y := Y xor (Shift_Left (Y, 7) and 16#9d2c5680#);
184 Y := Y xor (Shift_Left (Y, 15) and 16#efc60000#);
185 Y := Y xor Shift_Right (Y, 18);
190 function Random (Gen : Generator) return Float is
192 -- Note: The application of Float'Machine (...) is necessary to avoid
193 -- returning extra significand bits. Without it, the function's value
194 -- will change if it is spilled, for example, causing
195 -- gratuitous nondeterminism.
197 Result : constant Float :=
199 (Float (Unsigned_32'(Random (Gen))) * 2.0 ** (-32));
204 return Float'Adjacent (1.0, 0.0);
208 function Random (Gen : Generator) return Long_Float is
209 Result : constant Long_Float :=
210 Long_Float'Machine ((Long_Float (Unsigned_32'(Random (Gen)))
212 + (Long_Float (Unsigned_32'(Random (Gen))) * 2.0 ** (-64)));
217 return Long_Float'Adjacent (1.0, 0.0);
221 function Random (Gen : Generator) return Unsigned_64 is
223 return Shift_Left (Unsigned_64 (Unsigned_32'(Random (Gen))), 32)
224 or Unsigned_64 (Unsigned_32'(Random (Gen)));
227 ---------------------
228 -- Random_Discrete --
229 ---------------------
231 function Random_Discrete
233 Min : Result_Subtype := Default_Min;
234 Max : Result_Subtype := Result_Subtype'Last) return Result_Subtype
241 raise Constraint_Error;
243 elsif Result_Subtype'Base'Size > 32 then
245 -- In the 64-bit case, we have to be careful, since not all 64-bit
246 -- unsigned values are representable in GNAT's root_integer type.
247 -- Ignore different-size warnings here; since GNAT's handling
250 pragma Warnings ("Z");
251 function Conv_To_Unsigned is
252 new Unchecked_Conversion (Result_Subtype'Base, Unsigned_64);
253 function Conv_To_Result is
254 new Unchecked_Conversion (Unsigned_64, Result_Subtype'Base);
255 pragma Warnings ("z");
257 N : constant Unsigned_64 :=
258 Conv_To_Unsigned (Max) - Conv_To_Unsigned (Min) + 1;
260 X, Slop : Unsigned_64;
264 return Conv_To_Result (Conv_To_Unsigned (Min) + Random (Gen));
267 Slop := Unsigned_64'Last rem N + 1;
271 exit when Slop = N or else X <= Unsigned_64'Last - Slop;
274 return Conv_To_Result (Conv_To_Unsigned (Min) + X rem N);
278 elsif Result_Subtype'Pos (Max) - Result_Subtype'Pos (Min) =
281 return Result_Subtype'Val
282 (Result_Subtype'Pos (Min) + Unsigned_32'Pos (Random (Gen)));
285 N : constant Unsigned_32 :=
286 Unsigned_32 (Result_Subtype'Pos (Max) -
287 Result_Subtype'Pos (Min) + 1);
288 Slop : constant Unsigned_32 := Unsigned_32'Last rem N + 1;
294 exit when Slop = N or else X <= Unsigned_32'Last - Slop;
299 (Result_Subtype'Pos (Min) + Unsigned_32'Pos (X rem N));
308 function Random_Float (Gen : Generator) return Result_Subtype is
310 if Result_Subtype'Base'Digits > Float'Digits then
311 return Result_Subtype'Machine (Result_Subtype
312 (Long_Float'(Random (Gen))));
314 return Result_Subtype'Machine (Result_Subtype
315 (Float'(Random (Gen))));
323 procedure Reset (Gen : out Generator) is
324 X : constant Unsigned_32 := Unsigned_32 ((Calendar.Clock - Y2K) * 64.0);
329 procedure Reset (Gen : out Generator; Initiator : Integer_32) is
331 Init (Gen, To_Unsigned (Initiator));
334 procedure Reset (Gen : out Generator; Initiator : Unsigned_32) is
336 Init (Gen, Initiator);
339 procedure Reset (Gen : out Generator; Initiator : Integer) is
341 pragma Warnings ("C");
342 -- This is probably an unnecessary precaution against future change, but
343 -- since the test is a static expression, no extra code is involved.
345 if Integer'Size <= 32 then
346 Init (Gen, To_Unsigned (Integer_32 (Initiator)));
350 Initiator1 : constant Unsigned_64 :=
351 To_Unsigned (Integer_64 (Initiator));
352 Init0 : constant Unsigned_32 :=
353 Unsigned_32 (Initiator1 mod 2 ** 32);
354 Init1 : constant Unsigned_32 :=
355 Unsigned_32 (Shift_Right (Initiator1, 32));
357 Reset (Gen, Initialization_Vector'(Init0, Init1));
361 pragma Warnings ("c");
364 procedure Reset (Gen : out Generator; Initiator : Initialization_Vector) is
368 Init (Gen, 19650218);
372 if Initiator'Length > 0 then
373 for K in reverse 1 .. Integer'Max (N, Initiator'Length) loop
376 xor ((Gen.S (I - 1) xor Shift_Right (Gen.S (I - 1), 30))
378 + Initiator (J + Initiator'First) + Unsigned_32 (J);
384 Gen.S (0) := Gen.S (N - 1);
388 if J >= Initiator'Length then
394 for K in reverse 1 .. N - 1 loop
396 (Gen.S (I) xor ((Gen.S (I - 1)
397 xor Shift_Right (Gen.S (I - 1), 30)) * 1566083941))
402 Gen.S (0) := Gen.S (N - 1);
407 Gen.S (0) := Bit31_Mask;
410 procedure Reset (Gen : out Generator; From_State : Generator) is
412 Gen.S := From_State.S;
413 Gen.I := From_State.I;
416 procedure Reset (Gen : out Generator; From_State : State) is
422 procedure Reset (Gen : out Generator; From_Image : String) is
426 for J in 0 .. N - 1 loop
427 Gen.S (J) := Extract_Value (From_Image, J);
435 procedure Save (Gen : Generator; To_State : out State) is
444 To_State (0 .. N - 1 - Gen.I) := Gen.S (Gen.I .. N - 1);
445 To_State (N - Gen.I .. N - 1) := Gen.S (0 .. Gen.I - 1);
453 function Image (Of_State : State) return String is
454 Result : Image_String;
457 Result := (others => ' ');
459 for J in Of_State'Range loop
460 Insert_Image (Result, J, Of_State (J));
466 function Image (Gen : Generator) return String is
467 Result : Image_String;
470 Result := (others => ' ');
472 for J in 0 .. N - 1 loop
473 Insert_Image (Result, J, Gen.S ((J + Gen.I) mod N));
483 function Value (Coded_State : String) return State is
487 Reset (Gen, Coded_State);
496 procedure Init (Gen : out Generator; Initiator : Unsigned_32) is
498 Gen.S (0) := Initiator;
500 for I in 1 .. N - 1 loop
503 * (Gen.S (I - 1) xor Shift_Right (Gen.S (I - 1), 30))
514 procedure Insert_Image
515 (S : in out Image_String;
519 Value : constant String := State_Val'Image (V);
521 S (Index * 11 + 1 .. Index * 11 + Value'Length) := Value;
528 function Extract_Value (S : String; Index : Integer) return State_Val is
530 return State_Val'Value (S (S'First + Index * 11 ..
531 S'First + Index * 11 + 11));
534 end System.Random_Numbers;