Debian Codegraph @

source_2020/pre_math.mss

raw
1 @comment{ $Source: e:\\cvsroot/ARM/Source/pre_math.mss,v $ }
2 @comment{ $Revision: 1.47 $ $Date: 2019/04/09 04:56:52 $ $Author: randy $ }
3 @Part(predefmath, Root="ada.mss")
4
5 @Comment{$Date: 2019/04/09 04:56:52 $}
6
7 @LabeledClause{The Numerics Packages}
8
9 @begin{Intro}
10 The library package Numerics is the parent of several child units that provide
11 facilities for mathematical computation. One child, the generic package
12 Generic_Elementary_Functions, is defined in @RefSecNum{Elementary Functions},
13 together with nongeneric equivalents;
14 two others,
15 the package Float_Random and the generic package Discrete_Random,
16 are defined in @RefSecNum{Random Number Generation}.
17 Additional (optional)
18 children are defined in @RefSec{Numerics}.
19 @end{Intro}
20
21 @begin{StaticSem}
22 @ChgRef{Version=[1], Kind=[Deleted]}
23 @ChgDeleted[Version=[1],Text=<@ @;@comment{Empty paragraph to hang junk paragraph number from original RM}>]
24 @begin{Example}
25 @ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00388-01]}
26 @key[package] Ada.Numerics @key[is]@ChildUnit{Parent=[Ada],Child=[Numerics]}
27 @key[pragma] Pure(Numerics);
28 @AdaExcDefn{Argument_Error} : @key[exception];
29 @AdaObjDefn{Pi} : @key[constant] :=
30 3.14159_26535_89793_23846_26433_83279_50288_41971_69399_37511;@Chg{Version=[2],New=[
31 @pi : @key[constant] := Pi;],Old=[]}
32 @AdaObjDefn{e} : @key[constant] :=
33 2.71828_18284_59045_23536_02874_71352_66249_77572_47093_69996;
34 @key[end] Ada.Numerics;
35 @end{Example}
36
37 The Argument_Error exception is raised by a subprogram in
38 a child unit of Numerics
39 to signal that one or more of the actual subprogram parameters are outside the
40 domain of the corresponding mathematical function.
41
42 @end{StaticSem}
43
44 @begin{ImplPerm}
45 The implementation may specify the values of Pi and e to a larger number of
46 significant digits.
47 @begin{Reason}
48 51 digits seem more than adequate for all present computers; converted to
49 binary, the values given above are accurate to more than 160 bits.
50 Nevertheless, the permission allows implementations to accommodate
51 unforeseen hardware advances.
52 @end{Reason}
53 @end{ImplPerm}
54
55 @begin{Extend83}
56 @Defn{extensions to Ada 83}
57 Numerics and its children were not predefined in Ada 83.
58 @end{Extend83}
59
60 @begin{Extend95}
61 @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00388-01]}
62 @ChgAdded{Version=[2],Text=[@Defn{extensions to Ada 95}
63 The alternative declaration of @pi is new.]}
64 @end{Extend95}
65
66
67 @LabeledSubClause{Elementary Functions}
68
69 @begin{Intro}
70 Implementation-defined
71 approximations to the mathematical functions known as the @lquotes@;elementary
72 functions@rquotes@; are provided by the subprograms in
73 Numerics.@!Generic_@!Elementary_@!Functions. Nongeneric equivalents of this generic
74 package for each of the predefined floating point types are also provided as
75 children of Numerics.
76 @ImplDef{The accuracy actually achieved by the elementary functions.}
77 @end{Intro}
78
79 @begin{StaticSem}
80 @Leading@;The generic library package
81 Numerics.Generic_Elementary_Functions has the following declaration:
82 @begin{Example}
83 @ChgRef{Version=[5],Kind=[Revised],ARef=[AI12-0241-1]}
84 @key{generic}
85 @key{type} Float_Type @key{is} @key{digits} <>;
86 @ChildUnit{Parent=[Ada.Numerics],Child=[Generic_@!Elementary_@!Functions]}
87 @key{package} Ada.Numerics.Generic_Elementary_Functions@Chg{Version=[5],New=[],Old=[ @key{is}]}
88 @Chg{Version=[5],New=[@key[with]],Old=[@key[pragma]]} Pure@Chg{Version=[5],New=[, Nonblocking @key[is]],Old=[(Generic_Elementary_Functions);]}
89
90 @key{function} @AdaSubDefn{Sqrt} (X : Float_Type'Base) @key{return} Float_Type'Base;
91 @key{function} @AdaSubDefn{Log} (X : Float_Type'Base) @key{return} Float_Type'Base;
92 @key{function} @AdaSubDefn{Log} (X, Base : Float_Type'Base) @key{return} Float_Type'Base;
93 @key{function} @AdaSubDefn{Exp} (X : Float_Type'Base) @key{return} Float_Type'Base;
94 @key{function} "**" (Left, Right : Float_Type'Base) @key{return} Float_Type'Base;
95
96 @key{function} @AdaSubDefn{Sin} (X : Float_Type'Base) @key{return} Float_Type'Base;
97 @key{function} @AdaSubDefn{Sin} (X, Cycle : Float_Type'Base) @key{return} Float_Type'Base;
98 @key{function} @AdaSubDefn{Cos} (X : Float_Type'Base) @key{return} Float_Type'Base;
99 @key{function} @AdaSubDefn{Cos} (X, Cycle : Float_Type'Base) @key{return} Float_Type'Base;
100 @key{function} @AdaSubDefn{Tan} (X : Float_Type'Base) @key{return} Float_Type'Base;
101 @key{function} @AdaSubDefn{Tan} (X, Cycle : Float_Type'Base) @key{return} Float_Type'Base;
102 @key{function} @AdaSubDefn{Cot} (X : Float_Type'Base) @key{return} Float_Type'Base;
103 @key{function} @AdaSubDefn{Cot} (X, Cycle : Float_Type'Base) @key{return} Float_Type'Base;
104
105 @key{function} @AdaSubDefn{Arcsin} (X : Float_Type'Base) @key{return} Float_Type'Base;
106 @key{function} @AdaSubDefn{Arcsin} (X, Cycle : Float_Type'Base) @key{return} Float_Type'Base;
107 @key{function} @AdaSubDefn{Arccos} (X : Float_Type'Base) @key{return} Float_Type'Base;
108 @key{function} @AdaSubDefn{Arccos} (X, Cycle : Float_Type'Base) @key{return} Float_Type'Base;
109 @key{function} @AdaSubDefn{Arctan} (Y : Float_Type'Base;
110 X : Float_Type'Base := 1.0)
111 @key{return} Float_Type'Base;
112 @key{function} @AdaSubDefn{Arctan} (Y : Float_Type'Base;
113 X : Float_Type'Base := 1.0;
114 Cycle : Float_Type'Base) @key{return} Float_Type'Base;
115 @key{function} @AdaSubDefn{Arccot} (X : Float_Type'Base;
116 Y : Float_Type'Base := 1.0)
117 @key{return} Float_Type'Base;
118 @key{function} @AdaSubDefn{Arccot} (X : Float_Type'Base;
119 Y : Float_Type'Base := 1.0;
120 Cycle : Float_Type'Base) @key{return} Float_Type'Base;
121
122 @key{function} @AdaSubDefn{Sinh} (X : Float_Type'Base) @key{return} Float_Type'Base;
123 @key{function} @AdaSubDefn{Cosh} (X : Float_Type'Base) @key{return} Float_Type'Base;
124 @key{function} @AdaSubDefn{Tanh} (X : Float_Type'Base) @key{return} Float_Type'Base;
125 @key{function} @AdaSubDefn{Coth} (X : Float_Type'Base) @key{return} Float_Type'Base;
126 @key{function} @AdaSubDefn{Arcsinh} (X : Float_Type'Base) @key{return} Float_Type'Base;
127 @key{function} @AdaSubDefn{Arccosh} (X : Float_Type'Base) @key{return} Float_Type'Base;
128 @key{function} @AdaSubDefn{Arctanh} (X : Float_Type'Base) @key{return} Float_Type'Base;
129 @key{function} @AdaSubDefn{Arccoth} (X : Float_Type'Base) @key{return} Float_Type'Base;
130
131 @key{end} Ada.Numerics.Generic_Elementary_Functions;
132 @end{Example}
133
134 @ChgRef{Version=[1],Kind=[Revised],Ref=[8652/0020],ARef=[AI95-00126-01]}
135 @ChildUnit{Parent=[Ada.Numerics],Child=[Elementary_@!Functions]}
136 The library package Numerics.Elementary_Functions
137 @Chg{New=[is declared pure and ],Old=[]}defines the same subprograms as
138 Numerics.@!Generic_@!Elementary_@!Functions,
139 except that the predefined type Float is systematically substituted for
140 Float_Type'Base throughout. Nongeneric equivalents of
141 Numerics.@!Generic_@!Elementary_@!Functions for each of the other predefined
142 floating point types are defined similarly, with the names
143 Numerics.@!Short_@!Elementary_@!Functions, Numerics.@!Long_@!Elementary_@!Functions, etc.
144 @begin{Reason}
145 The nongeneric equivalents are provided to allow the programmer to
146 construct simple mathematical applications without being required to
147 understand and use generics.
148 @end{Reason}
149
150 The functions have their usual mathematical meanings. When the Base parameter
151 is specified, the Log function computes the logarithm to the given base;
152 otherwise, it computes the natural logarithm. When the Cycle parameter is
153 specified, the parameter X of the forward trigonometric functions (Sin, Cos,
154 Tan, and Cot) and the results of the inverse trigonometric functions (Arcsin,
155 Arccos, Arctan, and Arccot) are measured in units such that a full cycle of
156 revolution has the given value; otherwise, they are measured in radians.
157
158 @Leading@;The computed results of the mathematically multivalued functions are
159 rendered single-valued by the following conventions, which are meant to imply
160 the principal branch:
161 @begin{Itemize}
162 The results of the Sqrt and Arccosh functions and that of the exponentiation
163 operator are nonnegative.
164
165 The result of the Arcsin function is in the quadrant containing the point
166 (1.0, @i[x]), where @i[x] is the value of the parameter X. This quadrant is
167 I or IV; thus, the range of the Arcsin function is approximately
168 @en@Pi/2.0 to @Pi/2.0
169 (@en@R[Cycle]/4.0 to @R[Cycle]/4.0,
170 if the parameter Cycle is specified).
171
172 The result of the Arccos function is in the quadrant containing the point
173 (@i{x}, 1.0), where @i[x] is the value of the parameter X. This quadrant is
174 I or II; thus, the Arccos function ranges from 0.0 to approximately
175 @Pi (@R[Cycle]/2.0, if the parameter Cycle is specified).
176
177 The results of the Arctan and Arccot functions are in the quadrant
178 containing the point (@i[x], @i[y]), where @i[x] and @i[y] are the values of
179 the parameters X and Y, respectively. This may be any quadrant (I through
180 IV) when the parameter X (resp., Y) of Arctan (resp., Arccot) is specified,
181 but it is restricted to quadrants I and IV (resp., I and II) when that
182 parameter is omitted. Thus, the range when that parameter is specified is
183 approximately @en@Pi to @Pi
184 (@en@R[Cycle]/2.0 to @R[Cycle]/2.0,
185 if the parameter Cycle is specified); when omitted, the range of Arctan
186 (resp., Arccot) is that of Arcsin (resp., Arccos), as given above. When the
187 point (@i[x], @i[y]) lies on the negative x-axis, the result approximates
188 @begin{Itemize}
189 @Pi (resp., @en@Pi) when the sign of the parameter Y is
190 positive (resp., negative), if Float_Type'Signed_Zeros is True;
191
192 @Pi, if Float_Type'Signed_Zeros is False.
193 @end{Itemize}
194 @end{Itemize}
195
196 (In the case of the inverse trigonometric functions, in which a result lying on
197 or near one of the axes may not be exactly representable, the approximation
198 inherent in computing the result may place it in an adjacent quadrant, close to
199 but on the wrong side of the axis.)
200 @end{StaticSem}
201
202 @begin{RunTime}
203 @Leading@;The exception Numerics.Argument_Error is raised, signaling a
204 parameter value outside the domain of the corresponding mathematical function,
205 in the following cases:
206 @begin{Itemize}
207 by any forward or inverse trigonometric function with specified cycle, when
208 the value of the parameter Cycle is zero or negative;
209
210 by the Log function with specified base, when the value of the parameter
211 Base is zero, one, or negative;
212
213 by the Sqrt and Log functions, when the value of the parameter X is
214 negative;
215
216 by the exponentiation operator, when the value of the left operand is
217 negative or when both operands have the value zero;
218
219 by the Arcsin, Arccos, and Arctanh functions, when the absolute value of the
220 parameter X exceeds one;
221
222 by the Arctan and Arccot functions, when the parameters X and Y both have
223 the value zero;
224
225 by the Arccosh function, when the value
226 of the parameter X is less than one; and
227
228 by the Arccoth function, when the absolute value
229 of the parameter X is less than one.
230 @end{Itemize}
231
232 @Leading
233 The exception Constraint_Error is raised, signaling a pole of the mathematical
234 function (analogous to dividing by zero), in the following cases, provided that
235 Float_Type'Machine_Overflows is True:
236 @begin{Itemize}
237 by the Log, Cot, and Coth functions, when the value of the parameter X is
238 zero;
239
240 by the exponentiation operator, when the value of the left operand is zero
241 and the value of the exponent is negative;
242
243 by the Tan function with specified cycle, when the value of the parameter X
244 is an odd multiple of the quarter cycle;
245
246 by the Cot function with specified cycle, when the value of the parameter X
247 is zero or a multiple of the half cycle; and
248
249 by the Arctanh and Arccoth functions, when the absolute value of the
250 parameter X is one.
251 @end{Itemize}
252
253 @redundant[Constraint_Error can also be raised
254 when a finite result overflows
255 (see @RefSecNum{Accuracy Requirements for the Elementary Functions}); this may
256 occur for parameter values sufficiently @i{near} poles, and, in the case of
257 some of the functions, for parameter values with sufficiently large
258 magnitudes.]@PDefn{unspecified} When Float_Type'Machine_Overflows is False,
259 the result at poles is unspecified.
260 @begin{Reason}
261 The purpose of raising Constraint_Error (rather than
262 Numerics.Argument_Error) at the poles of a function, when
263 Float_Type'Machine_Overflows is True, is to provide continuous behavior as
264 the actual parameters of the function approach the pole and finally reach
265 it.
266 @end{Reason}
267 @begin{Discussion}
268 It is anticipated that an Ada binding to IEC 559:1989 will be developed
269 in the future. As part of such a binding, the Machine_Overflows attribute
270 of a conformant floating point type will be specified to yield False, which
271 will permit both the predefined arithmetic operations and implementations of
272 the elementary functions to deliver signed infinities (and set the overflow
273 flag defined by the binding) instead of raising Constraint_Error in overflow
274 situations, when traps are disabled. Similarly, it is appropriate for the
275 elementary functions to deliver signed infinities (and set the zero-divide
276 flag defined by the binding) instead of raising Constraint_Error at poles,
277 when traps are disabled. Finally, such a binding should also specify the
278 behavior of the elementary functions, when sensible, given parameters with
279 infinite values.
280 @end{Discussion}
281
282 When one parameter of a function with multiple parameters represents a pole and
283 another is outside the function's domain, the latter takes precedence (i.e.,
284 Numerics.Argument_Error is raised).
285 @end{RunTime}
286
287 @begin{ImplReq}
288 In the implementation of Numerics.Generic_Elementary_Functions,
289 the range of intermediate values allowed during the calculation
290 of a final result shall not be affected by any
291 range constraint of the subtype Float_Type.
292 @begin{ImplNote}
293 Implementations of Numerics.Generic_Elementary_Functions written in Ada
294 should therefore avoid declaring local variables of subtype Float_Type; the
295 subtype Float_Type'Base should be used instead.
296 @end{ImplNote}
297
298 @Leading@Defn2{Term=[prescribed result],
299 Sec=[for the evaluation of an elementary function]}
300 In the following cases, evaluation of an elementary function shall yield the
301 @i{prescribed result},
302 provided that the preceding rules do not call for an exception to be
303 raised:
304 @begin{Itemize}
305 When the parameter X has the value zero, the Sqrt, Sin, Arcsin, Tan, Sinh,
306 Arcsinh, Tanh, and Arctanh functions yield a result of zero, and the Exp,
307 Cos, and Cosh functions yield a result of one.
308
309 When the parameter X has the value one, the Sqrt function yields a result
310 of one, and the Log, Arccos, and Arccosh functions yield a result of zero.
311
312 When the parameter Y has the value zero and the parameter X has a positive
313 value, the Arctan and Arccot functions yield a result of zero.
314
315 The results of the Sin, Cos, Tan, and Cot functions with specified cycle are
316 exact when the mathematical result is zero; those of the first two are also
317 exact when the mathematical result is @PorM 1.0.
318
319 Exponentiation by a zero exponent yields the value one. Exponentiation by
320 a unit exponent yields the value of the left operand. Exponentiation of
321 the value one yields the value one. Exponentiation of the value zero
322 yields the value zero.
323 @end{Itemize}
324
325 Other accuracy requirements for the elementary functions, which apply only in
326 implementations conforming to the Numerics Annex, and then only in the
327 @lquotes@;strict@rquotes@; mode defined there (see @RefSecNum{Numeric Performance Requirements}),
328 are given in @RefSecNum{Accuracy Requirements for the Elementary Functions}.
329
330 @Leading@;When Float_Type'Signed_Zeros is True, the sign of a zero result
331 shall be as follows:
332 @begin{itemize}
333 A prescribed zero result delivered
334 @i{at the origin} by one of the odd functions (Sin, Arcsin, Sinh,
335 Arcsinh, Tan, Arctan or Arccot as a function of Y when X is fixed and
336 positive, Tanh, and Arctanh) has the sign of the parameter X (Y, in the case
337 of Arctan or Arccot).
338
339 A prescribed zero result delivered by one of the odd functions @i{away from
340 the origin}, or by some other elementary function, has
341 an implementation-defined sign.
342 @ImplDef{The sign of a zero result from some of the operators or functions
343 in Numerics.Generic_Elementary_Functions, when Float_Type'Signed_Zeros is
344 True.}
345
346 @redundant[A zero result that is not a prescribed result
347 (i.e., one that results from
348 rounding or underflow) has the correct mathematical sign.]
349 @begin{Reason}
350 This is a consequence of the rules specified in IEC 559:1989 as they
351 apply to underflow situations with traps disabled.
352 @end{Reason}
353 @end{itemize}
354 @end{ImplReq}
355
356 @begin{ImplPerm}
357 The nongeneric equivalent packages may, but need not, be actual
358 instantiations of the generic package for the appropriate predefined type.
359 @end{ImplPerm}
360
361 @begin{DiffWord83}
362 @Leading@;The semantics of Numerics.Generic_Elementary_Functions differs from
363 Generic_Elementary_Functions as defined in ISO/IEC DIS 11430 (for Ada 83)
364 in the following ways:
365 @begin{itemize}
366 The generic package is a child unit of the package defining the
367 Argument_Error exception.
368
369 DIS 11430 specified names for the nongeneric equivalents, if provided.
370 Here, those nongeneric equivalents are required.
371
372 Implementations are not allowed to impose an optional restriction that the
373 generic actual parameter associated with Float_Type be unconstrained.
374 (In view of the ability to declare variables of subtype Float_Type'Base in
375 implementations of Numerics.Generic_Elementary_Functions, this flexibility
376 is no longer needed.)
377
378 The sign of a prescribed zero result at the origin of the odd functions is
379 specified, when Float_Type'Signed_Zeros is True. This conforms with
380 recommendations of Kahan and other numerical analysts.
381
382 The dependence of Arctan and Arccot on the sign of a parameter value of zero
383 is tied to the value of Float_Type'Signed_Zeros.
384
385 Sqrt is prescribed to yield a result of one when its parameter has the
386 value one. This guarantee makes it easier to achieve certain prescribed
387 results of the complex elementary functions
388 (see @RefSec{Complex Elementary Functions}).
389
390 Conformance to accuracy requirements is conditional.
391 @end{itemize}
392 @end{DiffWord83}
393
394 @begin{DiffWord95}
395 @ChgRef{Version=[2],Kind=[AddedNormal],Ref=[8652/0020],ARef=[AI95-00126-01]}
396 @ChgAdded{Version=[2],Text=[@b<Corrigendum:> Explicitly stated that the
397 nongeneric equivalents of Generic_Elementary_Functions are pure.]}
398 @end{DiffWord95}
399
400
401 @LabeledSubClause{Random Number Generation}
402
403 @begin{Intro}
404 @redundant[Facilities for the generation of pseudo-random floating point numbers are
405 provided in the package Numerics.Float_Random; the generic package
406 Numerics.Discrete_Random provides similar facilities for the generation of
407 pseudo-random integers and pseudo-random values of enumeration
408 types.
409 @Defn{random number}
410 For brevity, pseudo-random values of any of these types are called @i{random
411 numbers}.
412
413 Some of the facilities provided are basic to all applications of random
414 numbers. These include a limited private type each of whose objects serves as
415 the generator of a (possibly distinct) sequence of random numbers; a function
416 to obtain the @lquotes@;next@rquotes@; random number from a given sequence of random numbers
417 (that is, from its generator); and subprograms to initialize or reinitialize a
418 given generator to a time-dependent state or a state denoted by a single
419 integer.
420
421 Other facilities are provided specifically for advanced applications. These
422 include subprograms to save and restore the state of a given generator; a
423 private type whose objects can be used to hold the saved state of a
424 generator;
425 and subprograms to obtain a string representation of a given generator state,
426 or, given such a string representation, the corresponding state.]
427 @begin{Discussion}
428 These facilities support a variety of requirements ranging from repeatable
429 sequences (for debugging) to unique sequences in each execution of a program.
430 @end{Discussion}
431 @end{Intro}
432
433 @begin{StaticSem}
434 @Leading@;The library package Numerics.Float_Random has the following declaration:
435 @begin{Example}
436 @key[package] Ada.Numerics.Float_Random @key[is]@ChildUnit{Parent=[Ada.Numerics],Child=[Float_@!Random]}
437
438 -- @RI{Basic facilities}
439
440 @key[type] @AdaTypeDefn{Generator} @key[is] @key[limited] @key[private];
441
442
443 @key[subtype] @AdaSubtypeDefn{Name=[Uniformly_Distributed],Of=[Float]} @key[is] Float @key[range] 0.0 .. 1.0;
444 @key[function] @AdaSubDefn{Random} (Gen : Generator) @key[return] Uniformly_Distributed;
445
446
447 @key[procedure] @AdaSubDefn{Reset} (Gen : @key[in] Generator;
448 Initiator : @key[in] Integer);
449 @key[procedure] @AdaSubDefn{Reset} (Gen : @key[in] Generator);
450
451
452 -- @RI{Advanced facilities}
453
454 @key[type] @AdaTypeDefn{State} @key[is] @key[private];
455
456
457 @key[procedure] @AdaSubDefn{Save} (Gen : @key[in] Generator;
458 To_State : @key[out] State);
459 @key[procedure] @AdaSubDefn{Reset} (Gen : @key[in] Generator;
460 From_State : @key[in] State);
461
462
463 @AdaObjDefn{Max_Image_Width} : @key[constant] := @RI{implementation-defined integer value};
464
465
466 @key[function] @AdaSubDefn{Image} (Of_State : State) @key[return] String;
467 @key[function] @AdaSubDefn{Value} (Coded_State : String) @key[return] State;
468
469
470 @key[private]
471 ... -- @RI{not specified by the language}
472 @key[end] Ada.Numerics.Float_Random;
473 @end{Example}
474
475 @ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00360-01]}
476 @ChgAdded{Version=[2],Text=[The type Generator
477 needs finalization@PDefn2{Term=<needs finalization>,Sec=<language-defined type>}
478 (see @RefSecNum{Assignment and Finalization}).]}
479
480 The generic library package Numerics.Discrete_Random has the following
481 declaration:
482 @begin{Example}
483 @ChildUnit{Parent=[Ada.Numerics],Child=[Discrete_@!Random]}
484 @key[generic]
485 @key[type] Result_Subtype @key[is] (<>);
486 @key[package] Ada.Numerics.Discrete_Random @key[is]
487
488 -- @RI{Basic facilities}
489
490 @key[type] @AdaTypeDefn{Generator} @key[is] @key[limited] @key[private];
491
492
493 @key[function] @AdaSubDefn{Random} (Gen : Generator) @key[return] Result_Subtype;
494
495 @ChgRef{Version=[5],Kind=[Added],ARef=[AI12-0144-1]}
496 @ChgAdded{Version=[5],Text=[ @key[function] Random (Gen : Generator;
497 First : Result_Subtype;
498 Last : Result_Subtype) @key[return] Result_Subtype
499 @key[with] Post => Random'Result @key[in] First .. Last;]}
500
501 @key[procedure] @AdaSubDefn{Reset} (Gen : @key[in] Generator;
502 Initiator : @key[in] Integer);
503 @key[procedure] @AdaSubDefn{Reset} (Gen : @key[in] Generator);
504
505
506 -- @RI{Advanced facilities}
507
508 @key[type] @AdaTypeDefn{State} @key[is] @key[private];
509
510
511 @key[procedure] @AdaSubDefn{Save} (Gen : @key[in] Generator;
512 To_State : @key[out] State);
513 @key[procedure] @AdaSubDefn{Reset} (Gen : @key[in] Generator;
514 From_State : @key[in] State);
515
516
517 @AdaObjDefn{Max_Image_Width} : @key[constant] := @RI{implementation-defined integer value};
518
519
520 @key[function] @AdaSubDefn{Image} (Of_State : State) @key[return] String;
521 @key[function] @AdaSubDefn{Value} (Coded_State : String) @key[return] State;
522
523
524 @key[private]
525 ... -- @RI{not specified by the language}
526 @key[end] Ada.Numerics.Discrete_Random;
527 @end{Example}
528 @ImplDef{The value of Numerics.Float_Random.Max_Image_Width.}
529 @ImplDef{The value of Numerics.Discrete_Random.Max_Image_Width.}
530 @begin{ImplNote}
531 @ChgRef{Version=[1],Kind=[Revised],Ref=[8652/0097],ARef=[AI95-00115-01]}
532 @Leading@;
533 The following is a possible implementation of the private part of
534 @Chg{New=[Numerics.Float_Random], Old=[each package]} (assuming the presence
535 of @lquotes@;@key[with] Ada.Finalization;@rquotes@; as a context clause):
536 @begin{example}
537 @key[type] State @key[is] ...;
538 @key[type] Access_State @key[is] @key[access] State;
539 @key[type] Generator @key[is] @key[new] Finalization.Limited_Controlled @key[with]
540 @key[record]
541 S : Access_State := @key[new] State'(...);
542 @key[end] @key[record];
543 @key[procedure] Finalize (G : @key[in] @key[out] Generator);
544 @end{Example}
545
546 @ChgRef{Version=[1],Kind=[Added],Ref=[8652/0097],ARef=[AI95-00115-01]}
547 @ChgRef{Version=[2],Kind=[RevisedAdded],ARef=[AI95-00344-01]}
548 @ChgAdded{Version=[1],Text=[@Chg{Version=[2],New=[],
549 Old=[Unfortunately, ]}Numerics.Discrete_Random.Generator @Chg{Version=[2],New=[also can],Old=[cannot]} be
550 implemented this way@Chg{Version=[2],New=[],Old=[, as Numerics.Discrete_Random can be instantiated at any
551 nesting depth. However, Generator could have a component of a controlled type,
552 as long as that type is declared in some other (nongeneric) package. One
553 possible solution would be to implement Numerics.@!Discrete_@!Random in terms
554 of Numerics.@!Float_@!Random, using a component of Numerics.@!Float_@!Random.Generator
555 to implement Numerics.@!Float_@!Random.@!Generator]}.]}
556
557 Clearly some level of indirection is required in the implementation of a
558 Generator, since the parameter mode is @key(in) for all operations on a
559 Generator. For this reason, Numerics.Float_Random and Numerics.Discrete_Random
560 cannot be declared pure.
561 @end{ImplNote}
562
563 @ChgRef{Version=[2],Kind=[Added],ARef=[AI95-00360-01]}
564 @ChgAdded{Version=[2],Text=[The type Generator
565 needs finalization@PDefn2{Term=<needs finalization>,Sec=<language-defined type>}
566 (see @RefSecNum{Assignment and Finalization})
567 in every instantiation of Numerics.Discrete_Random.]}
568
569 An object of the limited private type Generator is associated with a sequence
570 of random numbers. Each generator has a hidden (internal) state, which the
571 operations on generators use to determine the position in the associated
572 sequence.
573 @PDefn{unspecified}
574 All generators are implicitly initialized to an unspecified state
575 that does not vary from one program execution to another;
576 they may also be explicitly initialized, or reinitialized, to a time-dependent
577 state, to a previously saved state, or to a state uniquely denoted by an
578 integer value.
579 @begin{Discussion}
580 The repeatability provided by the implicit initialization may be exploited for
581 testing or debugging purposes.
582 @end{Discussion}
583
584 @ChgRef{Version=[3],Kind=[Revised],ARef=[AI05-0280-1]}
585 An object of the private type State can be used to hold the internal state of a
586 generator. Such objects are only needed if the application is designed to
587 save and restore generator states or to examine or manufacture
588 them.@Chg{Version=[3],New=[ The implicit initial value of type State
589 corresponds to the implicit initial value of all generators.],Old=[]}
590
591 @begin{Discussion}
592 @ChgRef{Version=[3],Kind=[AddedNormal],ARef=[AI05-0280-1]}
593 @ChgAdded{Version=[3],Text=[All generators are implicitly initialized to
594 the same unchanging value, and using Reset on a default initialized object
595 of type State will produce a generator with that same value.]}
596 @end{Discussion}
597
598 @Trailing@;The operations on generators affect the state and therefore the future values
599 of the associated sequence. The semantics of the operations on generators and
600 states are defined below.
601 @begin{DescribeCode}
602 @begin{Example}
603 @key[function] Random (Gen : Generator) @key[return] Uniformly_Distributed;
604 @key[function] Random (Gen : Generator) @key[return] Result_Subtype;
605 @end{Example}
606 @Trailing@;@ChgRef{Version=[5],Kind=[Revised],ARef=[AI12-0144-1]}
607 Obtains the @lquotes@;next@rquotes@; random number from the given generator,
608 relative to its current state, according to an implementation-defined
609 algorithm.@Chg{Version=[5],New=[],Old=[ The result of the function in
610 Numerics.Float_Random is delivered as a value of
611 the subtype Uniformly_Distributed, which is a subtype of the predefined type
612 Float having a range of
613 0.0 .. 1.0.
614 The result of the function in an
615 instantiation of Numerics.Discrete_Random is delivered as a value of the
616 generic formal subtype Result_Subtype.]}
617 @ChgImplDef{Version=[2],Kind=[Deleted],InitialVersion=[0],
618 Text=[@ChgDeleted{Version=[2],Text=[The
619 algorithms for random number generation.]}]}
620 @begin{Discussion}
621 @ChgRef{Version=[2],Kind=[Added]}
622 @ChgAdded{Version=[2],Text=[The algorithm is the subject of a @DocReqName@;,
623 so we don't separately summarize this implementation-defined item.]}
624 @end{Discussion}
625 @begin{Reason}
626 The requirement for a level of indirection in accessing the internal state
627 of a generator arises from the desire to make Random a function, rather than
628 a procedure.
629 @end{Reason}
630
631 @begin{Example}
632 @ChgRef{Version=[5],Kind=[Added],ARef=[AI12-0144-1]}
633 @ChgAdded{Version=[5],Text=[@key[function] Random (Gen : Generator;
634 First : Result_Subtype;
635 Last : Result_Subtype) @key[return] Result_Subtype
636 @key[with] Post => Random'Result @key[in] First .. Last;]}
637 @end{Example}
638
639 @ChgRef{Version=[5],Kind=[Added],ARef=[AI12-0144-1]}
640 @ChgAdded{Version=[5],Type=[Trailing],Text=[Obtains the @lquotes@;next@rquotes@;
641 random number from the given generator, relative to its current state, according
642 to an implementation-defined algorithm. If the range First .. Last is a null
643 range, Constraint_Error is
644 raised.]}
645
646 @begin{Example}
647 @key[procedure] Reset (Gen : @key[in] Generator;
648 Initiator : @key[in] Integer);
649 @key[procedure] Reset (Gen : @key[in] Generator);
650 @end{Example}
651 @Trailing@PDefn{unspecified}
652 Sets the state of the specified generator to one that is an unspecified
653 function of the value of the parameter Initiator (or to a time-dependent state,
654 if only a generator parameter is
655 specified).
656 @Defn2{Term=[Time-dependent Reset procedure],Sec=(of the random number generator)}
657 The latter form of the procedure is known as the @i{time-dependent Reset
658 procedure}.
659 @begin{ImplNote}
660 The time-dependent Reset procedure can be implemented by mapping the current
661 time and date as determined by the system clock into a state, but other
662 implementations are possible. For example, a white-noise generator or
663 a radioactive source can be used to generate time-dependent states.
664 @end{ImplNote}
665
666 @begin{Example}
667 @key[procedure] Save (Gen : @key[in] Generator;
668 To_State : @key[out] State);
669 @key[procedure] Reset (Gen : @key[in] Generator;
670 From_State : @key[in] State);
671 @end{Example}
672 @Trailing@;Save obtains the current state of a generator. Reset gives a
673 generator the specified state. A generator that is reset to a state previously
674 obtained by invoking Save is restored to the state it had when Save was
675 invoked.
676
677 @begin{Example}
678 @key[function] Image (Of_State : State) @key[return] String;
679 @key[function] Value (Coded_State : String) @key[return] State;
680 @end{Example}
681 Image provides a representation of a state coded (in an implementation-defined
682 way) as a string whose length is bounded by the value of Max_Image_Width.
683 Value is the inverse of Image: Value(Image(S)) = S for each state S that can be
684 obtained from a generator by invoking Save.
685 @ImplDef{The string representation of a random number generator's state.}
686 @end{DescribeCode}
687 @end{StaticSem}
688
689 @begin{RunTime}
690 Instantiation of Numerics.Discrete_Random with a subtype having a null range
691 raises Constraint_Error.
692
693 @ChgRef{Version=[1],Kind=[Deleted],Ref=[8652/0050],ARef=[AI95-00089]}
694 @ChgDeleted{Version=[1],Text=[Invoking Value with a string that is not the
695 image of any generator state raises Constraint_Error.]}
696 @end{RunTime}
697
698 @begin{Bounded}
699 @ChgRef{Version=[1],Kind=[Added],Ref=[8652/0050],ARef=[AI95-00089]}
700 @ChgAdded{Version=[1],Text=[It is a bounded error to invoke Value with a
701 string that is not the image of any generator
702 state.@PDefn2{Term=(bounded error),Sec=(cause)}
703 If the error is detected, Constraint_Error or
704 Program_Error is raised. Otherwise, a call to Reset with the resulting state
705 will produce a generator such that calls to Random with this generator will
706 produce a sequence of values of the appropriate subtype, but which might not
707 be random in character. That is, the sequence of values might not fulfill the
708 implementation requirements of this subclause.]}
709 @end{Bounded}
710
711 @begin{ImplReq}
712 @ChgRef{Version=[5],Kind=[Added],ARef=[AI12-0144-1]}
713 @ChgAdded{Version=[5],Text=[Each call of a Random function has a @i<result
714 range>;@Defn2{Term=[result range],Sec=[of a Random function]} this is the
715 range First .. Last for the version of Random with First and Last parameters
716 and the range of the result subtype of the function otherwise.]}
717
718 @ChgRef{Version=[5],Kind=[Revised],ARef=[AI12-0144-1]}
719 A sufficiently long sequence of random numbers obtained by
720 @Chg{Version=[5],New=[consecutive],Old=[successive]} calls to
721 Random @Chg{Version=[5],New=[that have the same generator and result
722 range ],Old=[]}is approximately uniformly distributed over the
723 @Chg{Version=[5],New=[result ],Old=[]}range@Chg{Version=[5],New=[],Old=[ of
724 the result subtype]}.
725
726 @begin{Discussion}
727 @ChgRef{Version=[5],Kind=[AddedNormal],ARef=[AI12-0144-1]}
728 @ChgAdded{Version=[5],Text=[In this rule, @lquotes@;consecutive@rquotes@;
729 means at least that there are
730 no intervening explicit calls involving the same generator. This restricts
731 the rule to only applying to cases where just the Random function changes
732 the generator. We don't mean to impose a requirement if there are
733 intervening calls to Reset, to Random with the same generator but a different
734 result range, or any other case that would affect the sequence of values
735 returned. Operations which use the resulting random values (for instance,
736 to store them somewhere) are not considered in determining if calls are
737 consecutive.]}
738 @end{Discussion}
739
740 @ChgRef{Version=[5],Kind=[Revised],ARef=[AI12-0144-1]}
741 @Chg{Version=[5],New=[A],Old=[The]} Random function in an instantiation of
742 Numerics.Discrete_Random is
743 guaranteed to yield each value in its result @Chg{Version=[5],New=[range],
744 Old=[subtype]} in a finite number of calls, provided that the number of such
745 values does not exceed 2 @+[15].
746
747 Other performance requirements for the random number generator, which apply
748 only in implementations conforming to the Numerics Annex, and then only in the
749 @lquotes@;strict@rquotes@; mode defined there (see @RefSecNum{Numeric Performance Requirements}),
750 are given in @RefSecNum{Performance Requirements for Random Number Generation}.
751 @end{ImplReq}
752
753 @begin{DocReq}
754 No one algorithm for random number generation is best for all applications. To
755 enable the user to determine the suitability of the random number generators
756 for the intended application, the implementation shall describe the algorithm
757 used and shall give its period, if known exactly, or a lower bound on the
758 period, if the exact period is unknown. Periods that are so long that the
759 periodicity is unobservable in practice can be described in such terms, without
760 giving a numerical bound.
761 @ChgDocReq{Version=[2],Kind=[AddedNormal],Text=[@ChgAdded{Version=[2],Text=[The
762 algorithm used for random number generation, including a description of its
763 period.]}]}
764
765 The implementation also shall document the minimum time interval between calls
766 to the time-dependent Reset procedure that are guaranteed to initiate
767 different sequences, and it shall document the nature of the strings that
768 Value will accept without raising Constraint_Error.
769 @ChgImplDef{Version=[2],Kind=[Deleted],InitialVersion=[0],
770 Text=[@ChgDeleted{Version=[2],Text=[The
771 minimum time interval between
772 calls to the time-dependent Reset procedure that are guaranteed to initiate
773 different random number sequences.]}]}
774 @ChgDocReq{Version=[2],Kind=[AddedNormal],Text=[@ChgAdded{Version=[2],Text=[The
775 minimum time interval between
776 calls to the time-dependent Reset procedure that is guaranteed to initiate
777 different random number sequences.]}]}
778 @end{DocReq}
779
780 @begin{ImplAdvice}
781 Any storage associated with an object of type Generator should be
782 reclaimed on exit from the scope of the object.
783 @ChgImplAdvice{Version=[2],Kind=[Added],Text=[@ChgAdded{Version=[2],Text=[Any
784 storage associated with an object of type Generator of the random
785 number packages should be reclaimed on exit from the scope of the object.]}]}
786 @begin{Ramification}
787 A level of indirection is implicit in the semantics of the
788 operations, given that they all take parameters of mode @key(in).
789 This implies that the full type of Generator probably should be a controlled
790 type, with appropriate finalization to reclaim any heap-allocated storage.
791 @end{Ramification}
792
793 If the generator period is sufficiently long in relation to the number of
794 distinct initiator values, then each possible value of Initiator passed to
795 Reset should initiate a sequence of random numbers that does not, in a
796 practical sense, overlap the sequence initiated by any other value. If this
797 is not possible, then the mapping between initiator values and generator states
798 should be a rapidly varying function of the initiator value.
799 @ChgImplAdvice{Version=[2],Kind=[AddedNormal],Text=[@ChgAdded{Version=[2],Text=[Each
800 value of Initiator passed to Reset for the random number packages should
801 initiate a distinct sequence of random numbers, or, if that is not possible,
802 be at least a rapidly varying function of the initiator value.]}]}
803 @end{ImplAdvice}
804
805 @begin{Notes}
806 If two or more tasks are to share the same generator, then the tasks have to
807 synchronize their access to the generator as for any shared variable
808 (see @RefSecNum(Shared Variables)).
809
810 Within a given implementation, a repeatable random number sequence can be
811 obtained by relying on the implicit initialization of generators or by
812 explicitly initializing a generator with a repeatable initiator value.
813 Different sequences of random numbers can be obtained from a given generator in
814 different program executions by explicitly initializing the generator to a
815 time-dependent state.
816
817 A given implementation of the Random function in Numerics.Float_Random may or
818 may not be capable of delivering the values 0.0 or 1.0. Portable applications
819 should assume that these values, or values sufficiently close to them to behave
820 indistinguishably from them, can occur. If a sequence of random integers from
821 some fixed range is needed, the application should use the Random function in
822 an appropriate instantiation of Numerics.Discrete_Random, rather than
823 transforming the result of the Random function in Numerics.Float_Random.
824 However, some applications with unusual requirements, such as for a sequence of
825 random integers each drawn from a different range, will find it more convenient
826 to transform the result of the floating point Random function. For
827 @R[M] @geq 1, the expression
828 @begin{Example}
829 Integer(Float(M) * Random(G)) mod M
830 @end{Example}
831
832 @NoPrefix@;transforms the result of Random(G) to an integer uniformly distributed over the
833 range 0 .. @R[M]@en@;1; it is valid even if Random delivers 0.0 or 1.0.
834 Each value of the result range is possible, provided that M is not too large.
835 Exponentially distributed (floating point) random numbers with mean and
836 standard deviation 1.0 can be obtained by the transformation
837 @begin{Example}
838 @ChgRef{Version=[2],Kind=[Revised],ARef=[AI95-00434-01]}
839 -Log(Random(G) + Float'Model_Small)@Chg{Version=[2],New=[],Old=[)]}
840 @end{Example}
841
842 @NoPrefix@;where Log comes from Numerics.Elementary_Functions
843 (see @RefSecNum{Elementary Functions});
844 in this expression, the addition of Float'Model_Small avoids the
845 exception that would be raised were Log to be given the value zero, without
846 affecting the result (in most implementations) when Random returns a nonzero
847 value.
848 @end{Notes}
849
850 @begin{Examples}
851 @Leading@Keepnext@i{Example of a program that plays a simulated dice game:}
852 @begin{Example}@Trailing
853 @key[with] Ada.Numerics.Discrete_Random;
854 @key[procedure] Dice_Game @key[is]@Softpage
855 @key[subtype] Die @key[is] Integer @key[range] 1 .. 6;
856 @key[subtype] Dice @key[is] Integer @key[range] 2*Die'First .. 2*Die'Last;
857 @key[package] Random_Die @key[is] @key[new] Ada.Numerics.Discrete_Random (Die);
858 @key[use] Random_Die;
859 G : Generator;
860 D : Dice;@Softpage
861 @key[begin]@Softpage
862 Reset (G); -- @RI{Start the generator in a unique state in each run}
863 @key[loop]
864 -- @RI{Roll a pair of dice; sum and process the results}
865 D := Random(G) + Random(G);
866 ...
867 @key[end] @key[loop];@Softpage
868 @key[end] Dice_Game;
869 @end{Example}
870
871 @Leading@Keepnext@i{Example of a program that simulates coin tosses:}
872 @begin{Example}@Trailing
873 @key[with] Ada.Numerics.Discrete_Random;
874 @key[procedure] Flip_A_Coin @key[is]@Softpage
875 @key[type] Coin @key[is] (Heads, Tails);
876 @key[package] Random_Coin @key[is] @key[new] Ada.Numerics.Discrete_Random (Coin);
877 @key[use] Random_Coin;
878 G : Generator;@Softpage
879 @key[begin]@Softpage
880 Reset (G); -- @RI{Start the generator in a unique state in each run}
881 @key[loop]
882 -- @RI{Toss a coin and process the result}
883 @key[case] Random(G) @key[is]
884 @key[when] Heads =>
885 ...
886 @key[when] Tails =>
887 ...
888 @key[end] @key[case];
889 ...
890 @key[end] @key[loop];@Softpage
891 @key[end] Flip_A_Coin;
892 @end{Example}
893
894 @Leading@Keepnext@i{Example of a parallel simulation of a physical system,
895 with a separate generator of event probabilities in each task:}
896 @begin{Example}
897 @key[with] Ada.Numerics.Float_Random;
898 @key[procedure] Parallel_Simulation @key[is]@Softpage
899 @key[use] Ada.Numerics.Float_Random;
900 @key[task] @key[type] Worker @key[is]
901 @key[entry] Initialize_Generator (Initiator : @key[in] Integer);
902 ...
903 @key[end] Worker;
904 W : @key[array] (1 .. 10) @key[of] Worker;@Softpage
905 @key[task] @key[body] Worker @key[is]
906 G : Generator;
907 Probability_Of_Event : Uniformly_Distributed;
908 @key[begin]@Softpage
909 @key[accept] Initialize_Generator (Initiator : @key[in] Integer) @key[do]
910 Reset (G, Initiator);
911 @key[end] Initialize_Generator;
912 @key[loop]
913 ...
914 Probability_Of_Event := Random(G);
915 ...
916 @key[end] @key[loop];
917 @key[end] Worker;@Softpage
918 @key[begin]@Softpage
919 -- @RI{Initialize the generators in the Worker tasks to different states}
920 @key[for] I @key[in] W'Range @key[loop]
921 W(I).Initialize_Generator (I);
922 @key[end] @key[loop];
923 ... -- @RI{Wait for the Worker tasks to terminate}@Softpage
924 @key[end] Parallel_Simulation;
925 @end{Example}
926 @end{Examples}
927
928 @begin{Notes}
929 @i{Notes on the last example:}
930 Although each Worker task initializes its generator to a different state, those
931 states will be the same in every execution of the program. The generator
932 states can be initialized uniquely in each program execution by instantiating
933 Ada.Numerics.Discrete_Random for the type Integer in the main procedure,
934 resetting the generator obtained from that instance to a time-dependent state,
935 and then using random integers obtained from that generator to initialize the
936 generators in each Worker task.
937 @end{Notes}
938
939 @begin{Incompatible95}
940 @ChgRef{Version=[2],Kind=[AddedNormal],ARef=[AI95-00360-01]}
941 @ChgAdded{Version=[2],Text=[@Defn{incompatibilities with Ada 95}
942 @b[Amendment Correction:] Type Generator in Numerics.Float_Random and in an
943 instance of Numerics.Discrete_Random is defined to need finalization. If the
944 restriction No_Nested_Finalization (see @RefSecNum{Tasking Restrictions})
945 applies to the partition, and Generator does not have a controlled part, it
946 will not be allowed in local objects in Ada 2005 whereas it would be allowed
947 in original Ada 95. Such code is not portable, as another Ada compiler may
948 have a controlled part in Generator, and thus would be illegal.]}
949 @end{Incompatible95}
950
951 @begin{DiffWord95}
952 @ChgRef{Version=[2],Kind=[AddedNormal],Ref=[8652/0050],ARef=[AI95-00089-01]}
953 @ChgRef{Version=[3],Kind=[Revised],ARef=[AI05-0005-1]}
954 @ChgAdded{Version=[2],Text=[@b<Corrigendum:> Made the passing of an incorrect
955 Image of a generator a bounded error, as it @Chg{Version=[3],New=[might],Old=[may]}
956 not be practical to check
957 for problems (if a generator consists of several related values).]}
958 @end{DiffWord95}
959
960 @begin{DiffWord2005}
961 @ChgRef{Version=[3],Kind=[AddedNormal],ARef=[AI05-0280-1]}
962 @ChgAdded{Version=[3],Text=[@b<Correction:> Specified the implicit initial
963 value for (sub)type State. This was unspecified in Ada 95 and Ada 2005,
964 so a program depending on some other initial value is very unlikely
965 and certainly was not portable. An implementation can use default expressions,
966 aspect Default_Value, or aspect Default_Component_Value to keep the
967 representation of the type unchanged while meeting this new requirement.]}
968 @end{DiffWord2005}
969
970 @begin{Extend2012}
971 @ChgRef{Version=[5],Kind=[AddedNormal],ARef=[AI12-0144-1]}
972 @ChgAdded{Version=[5],Text=[@Defn{extensions to Ada 2012} The function Random
973 with First and Last parameters is new.]}
974 @end{Extend2012}