GRASS 8 Programmer's Manual 8.6.0dev(2026)-2af89852bc
Loading...
Searching...
No Matches
lrand48.c
Go to the documentation of this file.
1/*!
2 * \file lib/gis/lrand48.c
3 *
4 * \brief GIS Library - Pseudo-random number generation
5 *
6 * The generator is the standard drand48 linear congruential generator
7 * X' = (A * X + B) mod 2^48 with A = 0x5DEECE66D and B = 0xB.
8 *
9 * When C11 atomic operations are available, the generator state is
10 * advanced with an atomic compare-and-swap and the generating functions
11 * are thread-safe: the sequence of generated values for a given seed is
12 * the same as in a single-threaded run. Which thread receives which
13 * value depends on scheduling, so results are fully reproducible only
14 * with single-threaded execution. Without C11 atomics (notably MSVC,
15 * which defines __STDC_NO_ATOMICS__), the generator falls back to plain
16 * state updates, so multi-threaded usage is safe only when compiled
17 * with C11 atomics.
18 *
19 * The seeding functions are not thread-safe; see G_srand48().
20 *
21 * The G_random_*() functions instead advance generators owned by the
22 * program, one struct G_random_state per unit of work. The program keeps
23 * a state to one thread at a time; the functions then need neither
24 * atomics nor locks, behave identically on every build, and give each
25 * unit a sequence fixed by the seed and the unit's number, not by the
26 * thread that draws it. The library places the units within the
27 * span, the first 2^46 draws after the seed, a quarter of the generator's
28 * cycle: a layout gives every unit of every batch a stream of stride draws
29 * in it, and a state is put at the start of its unit's stream. See \ref
30 * gislib_random_streams for the model.
31 *
32 * SPDX-FileCopyrightText: 2014-2026 GRASS Development Team
33 * SPDX-License-Identifier: GPL-2.0-or-later
34 *
35 * \authors Glynn Clements, Maris Nartiss, Vaclav Petras
36 */
37
38#include <errno.h>
39#include <inttypes.h>
40#include <stdint.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44
45#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && \
46 !defined(__STDC_NO_ATOMICS__)
47#include <stdatomic.h>
48#define LRAND48_ATOMIC 1
49#else
50#define LRAND48_ATOMIC 0
51#endif
52
53#include <grass/gis.h>
54#include <grass/glocale.h>
55
56#ifdef HAVE_GETTIMEOFDAY
57#include <sys/time.h>
58#else
59#include <time.h>
60#endif
61
62#include <sys/types.h>
63#include <unistd.h>
64
65typedef unsigned short uint16;
66typedef unsigned int uint32;
67typedef signed int int32;
68
69#define LCG_A UINT64_C(0x5DEECE66D)
70#define LCG_B UINT64_C(0xB)
71#define MASK48 UINT64_C(0xFFFFFFFFFFFF)
72
73/* The multiplier has order 2^46 modulo 2^48, so two states 2^46, 2^47 or
74 * 3 * 2^46 draws apart give values which differ by a constant for as long
75 * as they run. The layouts therefore place all their units within the
76 * first 2^46 draws after the seed, the span. */
77#define LCG_SPAN (UINT64_C(1) << 46)
78
79/* The most units a layout of the whole span takes; see
80 * G_random_init_layout() for why. */
81#define WHOLE_SPAN_MAX_UNITS (INT64_C(1) << 20)
82
83#if LRAND48_ATOMIC
84
85/* The whole 48-bit state is kept in one atomic integer so that it can be
86 * advanced in one compare-and-swap: a successful swap is exactly one
87 * generator step, giving the same sequence of states as a single-threaded
88 * run. The multiplication may wrap around at 2^64; that does not change
89 * the result modulo 2^48. */
91
92#else
93
94static uint16 x0, x1, x2;
95static const uint32 a0 = 0xE66D;
96static const uint32 a1 = 0xDEEC;
97static const uint32 a2 = 0x5;
98
99static const uint32 b0 = 0xB;
100
101#endif /* LRAND48_ATOMIC */
102
103static int seeded;
104
105#define LO(x) ((x) & 0xFFFFU)
106#define HI(x) ((x) >> 16)
107
108/*!
109 * \brief Seed the pseudo-random number generator
110 *
111 * This function is not thread-safe. In a multi-threaded program, call
112 * `G_srand48()` once *before* starting the worker threads; it must not
113 * run concurrently with another thread seeding or generating values.
114 *
115 * \param[in] seedval 32-bit integer used to seed the PRNG
116 */
118{
119 uint32 x = (uint32) * (unsigned long *)&seedval;
120
121#if LRAND48_ATOMIC
122 atomic_store(&state, ((uint_least64_t)x << 16) | 0x330E);
123#else
124 x2 = (uint16)HI(x);
125 x1 = (uint16)LO(x);
126 x0 = (uint16)0x330E;
127#endif
128 seeded = 1;
129}
130
131/* The seeds the generator tells apart: G_srand48() uses the low 32 bits of
132 * the seed, and this range names every such seed once, as a signed or an
133 * unsigned 32-bit value. */
134static int seed_in_range(int64_t seed)
135{
136 return seed >= -(INT64_C(1) << 31) && seed <= (INT64_C(1) << 32) - 1;
137}
138
139/* Read a seed from an environment variable. An unset or empty variable
140 * gives no seed, so that the caller can try the next source. */
141static int seed_from_environment(const char *name, int64_t *seed)
142{
143 const char *text = getenv(name);
144 char *end;
145 int64_t value;
146
147 if (!text || !*text)
148 return 0;
149 errno = 0;
150 value = strtoll(text, &end, 10);
151 if (errno == ERANGE)
153 _("Random number seed %s from %s is too large in magnitude "
154 "to be read"),
155 text, name);
156 if (end == text || *end != '\0')
157 G_fatal_error(_("Random number seed %s from %s is not an integer"),
158 text, name);
159 if (!seed_in_range(value)) {
160 int64_t reduced = (int64_t)((uint64_t)value & 0xFFFFFFFF);
161
162 G_warning(_("Random number seed %s from %s is used as %" PRId64 ", "
163 "its low 32 bits"),
164 text, name, reduced);
165 value = reduced;
166 }
167 *seed = value;
168 return 1;
169}
170
171/*!
172 * \brief Generate a seed for a random number generator
173 *
174 * The seed is the value of the environment variable GRASS_RANDOM_SEED, or
175 * of SOURCE_DATE_EPOCH when GRASS_RANDOM_SEED is not set or empty, and
176 * otherwise a weak hash of the current time and process ID. A value from
177 * the environment must be a decimal integer within the range of int64_t,
178 * with nothing after it (leading white space and a sign are allowed);
179 * anything else is a fatal error naming the variable. A value from -2^31
180 * to 2^32 - 1 is returned as it is, and a value outside that range is
181 * reduced to its low 32 bits, between 0 and 2^32 - 1, with a warning. The
182 * result is therefore a seed G_random_state_from_seed(), the layout
183 * functions and G_srand48() accept. Record it, for example in the history of
184 * the output map, so that the run can be repeated with it as the seed.
185 *
186 * The hash of the time and process ID lies between 0 and 2^32 - 1. Two
187 * calls in one process within the same microsecond, or within the same
188 * second on systems without gettimeofday(), return the same value, and
189 * two processes can get the same value too.
190 *
191 * The function reads the environment and the clock and changes no
192 * generator; it may issue a warning or end with a fatal error.
193 *
194 * \return the seed
195 */
197{
200
201 if (seed_from_environment("GRASS_RANDOM_SEED", &given) ||
202 seed_from_environment("SOURCE_DATE_EPOCH", &given))
203 return given;
204
205 seed = (uint64_t)getpid();
206
207#ifdef HAVE_GETTIMEOFDAY
208 {
209 struct timeval tv;
210
211 if (gettimeofday(&tv, NULL) < 0)
212 G_fatal_error(_("gettimeofday failed: %s"), strerror(errno));
213 seed += (uint64_t)tv.tv_sec;
214 seed += (uint64_t)tv.tv_usec;
215 }
216#else
217 {
218 time_t t = time(NULL);
219
220 seed += (uint64_t)t;
221 }
222#endif
223
224 return (int64_t)(seed & 0xFFFFFFFF);
225}
226
227/*!
228 * \brief Seed the pseudo-random number generator from the time and PID
229 *
230 * The seed is what G_random_generate_seed() returns: the value of
231 * GRASS_RANDOM_SEED or SOURCE_DATE_EPOCH, or a weak hash of the current
232 * time and PID.
233 *
234 * This function is not thread-safe. In a multi-threaded program, call
235 * `G_srand48_auto()` once *before* starting the worker threads; it must
236 * not run concurrently with another thread seeding or generating values.
237 *
238 * \return the seed passed to G_srand48(), between -2^31 and 2^32 - 1;
239 * where long has 32 bits, a value of 2^31 or more comes back
240 * negative, which G_srand48() and G_random_state_from_seed() read
241 * as the same seed
242 */
244{
246
247 G_srand48((long)seed);
248 return (long)seed;
249}
250
251#if LRAND48_ATOMIC
252
253/* Advance the generator by one step and return the new state. Callers
254 * derive their result from the returned value, not from shared state, so
255 * concurrent calls each get a distinct step of the sequence. */
256static uint_least64_t G__next(void)
257{
259 uint_least64_t next;
260
261 if (!seeded)
262 G_fatal_error(_("Pseudo-random number generator not seeded"));
263
264 do {
265 next = (LCG_A * cur + LCG_B) & MASK48;
267 &state, &cur, next, memory_order_relaxed, memory_order_relaxed));
268
269 return next;
270}
271
272#else
273
274static void G__next(void)
275{
276 uint32 a0x0 = a0 * x0;
277 uint32 a0x1 = a0 * x1;
278 uint32 a0x2 = a0 * x2;
279 uint32 a1x0 = a1 * x0;
280 uint32 a1x1 = a1 * x1;
281 uint32 a2x0 = a2 * x0;
282
283 uint32 y0 = LO(a0x0) + b0;
284 uint32 y1 = LO(a0x1) + LO(a1x0) + HI(a0x0);
285 uint32 y2 = LO(a0x2) + LO(a1x1) + LO(a2x0) + HI(a0x1) + HI(a1x0);
286
287 if (!seeded)
288 G_fatal_error(_("Pseudo-random number generator not seeded"));
289
290 x0 = (uint16)LO(y0);
291 y1 += HI(y0);
292 x1 = (uint16)LO(y1);
293 y2 += HI(y1);
294 x2 = (uint16)LO(y2);
295}
296
297#endif /* LRAND48_ATOMIC */
298
299/*!
300 * \brief Generate an integer in the range [0, 2^31)
301 *
302 * This function is thread-safe only when compiled with C11 atomics
303 * (see the comment at the top of the file).
304 *
305 * \return the generated value
306 */
307long G_lrand48(void)
308{
309#if LRAND48_ATOMIC
310 return (long)(G__next() >> 17);
311#else
312 uint32 r;
313
314 G__next();
315 r = ((uint32)x2 << 15) | ((uint32)x1 >> 1);
316 return (long)r;
317#endif
318}
319
320/*!
321 * \brief Generate an integer in the range [-2^31, 2^31)
322 *
323 * This function is thread-safe only when compiled with C11 atomics
324 * (see the comment at the top of the file).
325 *
326 * \return the generated value
327 */
328long G_mrand48(void)
329{
330#if LRAND48_ATOMIC
331 uint32 r = (uint32)(G__next() >> 16);
332
333 return (long)(int32)r;
334#else
335 uint32 r;
336
337 G__next();
338 r = ((uint32)x2 << 16) | ((uint32)x1);
339 return (long)(int32)r;
340#endif
341}
342
343/*!
344 * \brief Generate a floating-point value in the range [0,1)
345 *
346 * This function is thread-safe only when compiled with C11 atomics
347 * (see the comment at the top of the file).
348 *
349 * \return the generated value
350 */
351double G_drand48(void)
352{
353#if LRAND48_ATOMIC
354 /* The state is below 2^53, so the conversion to double is exact. */
355 return (double)G__next() / 281474976710656.0; /* 2^48 */
356#else
357 double r = 0.0;
358
359 G__next();
360 r += x2;
361 r *= 0x10000;
362 r += x1;
363 r *= 0x10000;
364 r += x0;
365 r /= 281474976710656.0; /* 2^48 */
366 return r;
367#endif
368}
369
370/* Multiply two values modulo 2^48. The unsigned multiplication may wrap
371 * around modulo 2^64. This is intentional and does not change the result:
372 * since 2^48 divides 2^64, masking the wrapped product to 48 bits gives
373 * the same result as computing the full product modulo 2^48. */
374static uint64_t mul48(uint64_t a, uint64_t b)
375{
376 /* coverity[integer_overflow] */
377 return (a * b) & MASK48;
378}
379
380/* Advance a generator of the program's own by one step. All generator
381 * arithmetic is modulo 2^48; mul48() performs multiplication with
382 * intentional unsigned wraparound as described above. */
383static uint64_t lcg_step(uint64_t x)
384{
385 return (mul48(LCG_A, x) + LCG_B) & MASK48;
386}
387
388/* Turn a seed into a generator state the way G_srand48() does: only the
389 * low 32 bits are used, so a negative seed gives the state of its two's
390 * complement 32-bit value. */
391static uint64_t lcg_seed(int64_t seed)
392{
393 return (((uint64_t)seed & 0xFFFFFFFF) << 16) | 0x330E;
394}
395
396/* Advance the generator by an arbitrary number of steps without taking
397 * them one at a time. One step is the affine map x -> a * x + c, and
398 * composing two such maps gives another, so the map for `steps` steps is
399 * built by repeated squaring, as an integer power would be. All
400 * multiplication is modulo 2^48; see mul48(). */
401static uint64_t lcg_jump(uint64_t x, uint64_t steps)
402{
403 uint64_t a_total = 1, c_total = 0; /* the identity map */
404 uint64_t a = LCG_A, c = LCG_B; /* one step */
405
406 while (steps) {
407 if (steps & 1) {
408 c_total = (mul48(a, c_total) + c) & MASK48;
409 a_total = mul48(a, a_total);
410 }
411 /* Square the map, so a and c then describe twice as many steps. */
412 c = (mul48(a, c) + c) & MASK48;
413 a = mul48(a, a);
414 steps >>= 1;
415 }
416
417 return (mul48(a_total, x) + c_total) & MASK48;
418}
419
420/* The generator tells seeds apart by their low 32 bits only. Seeds read
421 * as signed or as unsigned 32-bit values are accepted, so -1 and
422 * 4294967295 are both accepted and are the same seed; anything else is
423 * rejected rather than silently losing its high bits. */
424static void check_seed(int64_t seed)
425{
426 if (!seed_in_range(seed))
427 G_fatal_error(_("Random number seed %" PRId64 " is outside the range "
428 "from -2147483648 to 4294967295 the generator can use"),
429 seed);
430}
431
432static void check_units(int64_t units)
433{
434 if (units <= 0)
435 G_fatal_error(_("The number of units of a random number layout must "
436 "be positive, not %" PRId64),
437 units);
438}
439
440/* The draws from the start of one batch to the start of the next: those of
441 * one batch, units * stride, or one more when that number is even. With an
442 * odd distance, as with an odd stride between units, the same draw of
443 * different batches is as unrelated as the generator allows; an even
444 * distance would relate those draws, the more simply the more often 2
445 * divides it. */
446static uint64_t batch_distance(const struct G_random_layout *layout)
447{
448 return ((uint64_t)layout->units * (uint64_t)layout->stride) | 1;
449}
450
451/* Fill in a layout of units of the given stride, all of one batch first,
452 * then those of the next batch. The batches that fit are those whose last
453 * stream ends within the span. Callers must check beforehand that
454 * units * stride does not overflow. */
455static void fill_layout(struct G_random_layout *layout, int64_t seed,
456 int64_t units, int64_t stride)
457{
458 uint64_t draws = (uint64_t)units * (uint64_t)stride;
459
460 layout->start = lcg_seed(seed);
461 layout->units = units;
462 layout->stride = stride;
463 layout->batches = 0;
464 if (draws <= LCG_SPAN)
465 layout->batches =
466 (int64_t)((LCG_SPAN - draws) / batch_distance(layout) + 1);
467 layout->whole_span = false;
468}
469
470/*!
471 * \brief Seed a pseudo-random number generator of the program's own
472 *
473 * Puts the state at the seed: it then produces the sequence G_srand48()
474 * followed by G_drand48() produces for the same seed, so code moving from
475 * the shared generator to one of its own reproduces its existing results.
476 * Use it for a single sequence, which then has the whole span to itself;
477 * for one sequence per unit of work, use a layout and
478 * G_random_state_for_unit().
479 *
480 * A seed outside -2^31 to 2^32 - 1 is a fatal error. A negative seed
481 * means its two's complement 32-bit value, as for G_srand48().
482 *
483 * Thread-safe as long as no two threads seed the same state.
484 *
485 * \param[out] state generator state to seed
486 * \param[in] seed seed, from -2^31 to 2^32 - 1
487 */
489{
490 check_seed(seed);
491 state->state = lcg_seed(seed);
492}
493
494/*!
495 * \brief Initialize a layout whose units draw an exact number of values
496 *
497 * The span is cut into streams of exactly \p draws_per_unit draws, one per
498 * unit, placed one after another from the seed. Unit u of batch 0 therefore
499 * draws what a single sequence from G_random_state_from_seed() draws at
500 * positions u * \p draws_per_unit to (u + 1) * \p draws_per_unit - 1, so
501 * the units together reproduce a serial run whatever order they are
502 * processed in. Further batches follow, see G_random_state_for_batch().
503 * A unit which draws more than \p draws_per_unit values runs into the
504 * next unit's stream; when the number of draws is only bounded, use
505 * G_random_init_layout_bounded().
506 *
507 * The stride is \p draws_per_unit. G_random_layout_length() returns it,
508 * and G_random_layout_batches() returns the batches that fit, which is 0
509 * when \p units * \p draws_per_unit draws do not fit into the span. See \ref
510 * gislib_random_streams.
511 *
512 * A seed outside -2^31 to 2^32 - 1, a number of units or of draws which
513 * is not positive, or a product of the two beyond the range of int64_t
514 * is a fatal error.
515 *
516 * \param[out] layout layout to initialize
517 * \param[in] seed seed, see G_random_state_from_seed()
518 * \param[in] units number of units of work, positive
519 * \param[in] draws_per_unit number of values each unit draws, positive
520 */
523{
524 check_seed(seed);
525 check_units(units);
526 if (draws_per_unit <= 0)
527 G_fatal_error(_("The number of random numbers a unit draws must be "
528 "positive, not %" PRId64),
530 if (units > INT64_MAX / draws_per_unit)
531 G_fatal_error(_("A random number layout of %" PRId64 " units of "
532 "%" PRId64 " draws each is too large (the number of "
533 "draws must not exceed %" PRId64 ")"),
534 units, draws_per_unit, INT64_MAX);
535 fill_layout(layout, seed, units, draws_per_unit);
536}
537
538/*!
539 * \brief Initialize a layout whose units draw at most a number of values
540 *
541 * As G_random_init_layout_exact(), but each unit may draw any number of
542 * values up to \p max_draws: the streams are \p max_draws draws long, or
543 * \p max_draws + 1 when \p max_draws is even. With an odd stride, units
544 * 2^i apart in number start an odd multiple of 2^i draws apart, so the
545 * differences of their states are fixed in the low i + 2 bits only; an
546 * even stride would add its own power of two to that count.
547 *
548 * The stride is \p max_draws rounded up to odd. G_random_layout_length()
549 * returns it, and G_random_layout_batches() returns the batches that fit,
550 * which is 0 when \p units times the stride draws do not fit into the span. See
551 * \ref gislib_random_streams.
552 *
553 * A seed outside -2^31 to 2^32 - 1, a number of units or a bound which is
554 * not positive, or a product of the units and the stride beyond the range
555 * of int64_t is a fatal error.
556 *
557 * \param[out] layout layout to initialize
558 * \param[in] seed seed, see G_random_state_from_seed()
559 * \param[in] units number of units of work, positive
560 * \param[in] max_draws most values any unit draws, positive
561 */
564{
565 int64_t stride;
566
567 check_seed(seed);
568 check_units(units);
569 if (max_draws <= 0)
570 G_fatal_error(_("The most random numbers a unit draws must be "
571 "positive, not %" PRId64),
572 max_draws);
573 /* INT64_MAX is odd, so an even bound can be rounded up. */
574 stride = max_draws % 2 == 0 ? max_draws + 1 : max_draws;
575 if (units > INT64_MAX / stride)
576 G_fatal_error(_("A random number layout of %" PRId64 " units of at "
577 "most %" PRId64 " draws each is too large (the number "
578 "of units times the bound rounded up to odd must not "
579 "exceed %" PRId64 ")"),
580 units, max_draws, INT64_MAX);
581 fill_layout(layout, seed, units, stride);
582}
583
584/*!
585 * \brief Initialize a layout which gives the units the whole span
586 *
587 * For units whose number of draws is not known in advance. The span is
588 * divided into parts, as many as there are units, or one more when that
589 * number is even. The stride is 2^46 / parts rounded down, and then down
590 * to odd when there is more than one part, and unit u starts u * stride
591 * draws after the seed. The odd number of parts keeps the unit halfway or
592 * a quarter of the way along from starting 2^45 or 2^44 draws after unit
593 * 0, distances at which this generator's values relate (see
594 * \ref gislib_random_streams): the unit nearest to 2^45 starts at least
595 * 0.48 of a stride away from it and the unit nearest to 2^44 at least
596 * 0.24, so a unit meets such a relation only after drawing about a
597 * quarter of its stride. The odd stride puts units 2^i apart in number an
598 * odd multiple of 2^i draws apart, as in a bounded layout. A single unit
599 * keeps the whole span of 2^46 draws, as a state from
600 * G_random_state_from_seed() does. The layout holds a single batch.
601 *
602 * The number of units is limited to 2^20: the rounded stride loses up to
603 * two draws per unit, which accumulate along the span, so beyond that
604 * count the units nearest to 2^45 and 2^44 would drift toward them. A
605 * bounded layout serves any number of units.
606 *
607 * The stride is the length of a part. G_random_layout_length() returns
608 * it, and G_random_layout_batches() returns 1.
609 *
610 * A seed outside -2^31 to 2^32 - 1, or a number of units which is not
611 * positive or above 2^20, is a fatal error.
612 *
613 * \param[out] layout layout to initialize
614 * \param[in] seed seed, see G_random_state_from_seed()
615 * \param[in] units number of units of work, from 1 to 2^20
616 */
618 int64_t units)
619{
620 uint64_t parts, stride;
621
622 check_seed(seed);
623 check_units(units);
624 if (units > WHOLE_SPAN_MAX_UNITS)
625 G_fatal_error(_("A random number layout of the whole span takes at "
626 "most %" PRId64 " units, not %" PRId64 "; a bounded "
627 "layout serves any number of units"),
628 WHOLE_SPAN_MAX_UNITS, units);
629 parts = (uint64_t)units | 1;
630 stride = LCG_SPAN / parts;
631 if (parts > 1 && stride % 2 == 0)
632 stride--;
633 layout->start = lcg_seed(seed);
634 layout->units = units;
635 layout->stride = (int64_t)stride;
636 layout->batches = 1;
637 layout->whole_span = true;
638}
639
640/*!
641 * \brief Return the number of batches that fit into the span
642 *
643 * \param[in] layout an initialized layout
644 *
645 * \return the batches that fit, 1 for a layout of the whole span, 0 when
646 * one batch of the layout does not fit into the span
647 */
649{
650 return layout->batches;
651}
652
653/*!
654 * \brief Return the number of values a unit may draw
655 *
656 * \param[in] layout an initialized layout
657 *
658 * \return the stride of the layout, the number of values every unit may
659 * draw without running into the next unit's stream
660 */
662{
663 return layout->stride;
664}
665
666/*!
667 * \brief Put a generator state at the start of a unit's stream in a batch
668 *
669 * A batch is one stream for every unit of the layout, and the batches
670 * follow one another along the span. They start units * stride draws
671 * apart, or one more when that number is even, and the stream of \p unit
672 * in \p batch starts \p unit * stride draws after the start of the batch.
673 * With the odd distance, as with an odd stride, the same draw of different
674 * batches is as unrelated as the generator allows; what an even distance
675 * would relate there is related between draws whose numbers differ
676 * instead. The state is set whatever it held before, so the same call
677 * always restarts the same sequence. See \ref gislib_random_streams.
678 *
679 * A \p unit outside 0 to units - 1, a negative \p batch, a \p batch other
680 * than 0 of a layout of the whole span, or a \p batch beyond the batches
681 * that fit is a fatal error. When no batch fits, batch 0 is still allowed,
682 * and only batch 0: a tool which warned that its layout does not fit into
683 * the span may use it as earlier versions did.
684 *
685 * Thread-safe as long as no two threads use the same state; the layout
686 * is only read.
687 *
688 * \param[out] state generator state to set
689 * \param[in] layout an initialized layout
690 * \param[in] batch number of the batch, from 0
691 * \param[in] unit number of the unit, from 0 to units - 1
692 */
694 const struct G_random_layout *layout,
695 int64_t batch, int64_t unit)
696{
697 uint64_t offset;
698
699 if (unit < 0 || unit >= layout->units)
700 G_fatal_error(_("Random number unit %" PRId64 " is out of range "
701 "(must be between 0 and %" PRId64 ")"),
702 unit, layout->units - 1);
703 if (batch < 0)
704 G_fatal_error(_("Random number batch %" PRId64 " is out of range "
705 "(must not be negative)"),
706 batch);
707 if (batch > 0 && layout->whole_span)
708 G_fatal_error(_("Random number batch %" PRId64 " is out of range "
709 "(a layout of the whole span holds a single batch)"),
710 batch);
711 if (layout->batches >= 1 && batch >= layout->batches)
712 G_fatal_error(n_("Random number batch %" PRId64 " is out of range "
713 "(%" PRId64 " batch fits into the generator's span)",
714 "Random number batch %" PRId64 " is out of range "
715 "(%" PRId64 " batches fit into the generator's span)",
716 (unsigned long)layout->batches),
717 batch, layout->batches);
718 if (layout->batches == 0 && batch > 0)
719 G_fatal_error(_("Random number batch %" PRId64 " is out of range "
720 "(no batch fits into the generator's span, only batch "
721 "0 can be used)"),
722 batch);
723
724 /* With batch below the batches that fit, the offset is below 2^46; with
725 * batch 0 of a layout which does not fit, it may reach past the span.
726 * It is below 2^63 either way, since units times stride is. */
727 offset = (uint64_t)batch * batch_distance(layout) +
728 (uint64_t)unit * (uint64_t)layout->stride;
729 state->state = lcg_jump(layout->start, offset);
730}
731
732/*!
733 * \brief Put a generator state at the start of a unit's stream
734 *
735 * The same as G_random_state_for_batch() with batch 0.
736 *
737 * \param[out] state generator state to set
738 * \param[in] layout an initialized layout
739 * \param[in] unit number of the unit, from 0 to units - 1
740 */
742 const struct G_random_layout *layout, int64_t unit)
743{
745}
746
747/*!
748 * \brief Advance a generator of the program's own as if values had been drawn
749 *
750 * Moves the state by \p draws draws without taking them one at a time,
751 * so that the next G_random_double() returns what the draw after those
752 * would have returned.
753 *
754 * A negative \p draws is a fatal error.
755 *
756 * \param[in,out] state a seeded generator state
757 * \param[in] draws number of values to skip, not negative
758 */
760{
761 if (draws < 0)
762 G_fatal_error(_("Cannot advance a random number generator by "
763 "%" PRId64 " draws (the number must not be negative)"),
764 draws);
765 state->state = lcg_jump(state->state, (uint64_t)draws);
766}
767
768/*!
769 * \brief Generate a floating-point value in the range [0,1) from a
770 * generator of the program's own
771 *
772 * Thread-safe as long as no two threads share a state. Unlike
773 * G_drand48(), this needs no atomics and so behaves identically on every
774 * build.
775 *
776 * \param[in,out] state generator state, set with
777 * G_random_state_from_seed(), G_random_state_for_unit() or
778 * G_random_state_for_batch()
779 *
780 * \return the generated value
781 */
782double G_random_double(struct G_random_state *state)
783{
784 state->state = lcg_step(state->state);
785 /* The state is below 2^53, so the conversion to double is exact. */
786 return (double)state->state / 281474976710656.0; /* 2^48 */
787}
788
789/*
790
791 Test program
792
793 int main(int argc, char **argv)
794 {
795 long s = (argc > 1) ? atol(argv[1]) : 0;
796 int i;
797
798 srand48(s);
799 G_srand48(s);
800
801 for (i = 0; i < 100; i++) {
802 printf("%.50f %.50f\n", drand48(), G_drand48());
803 printf("%lu %lu\n", lrand48(), G_lrand48());
804 printf("%ld %ld\n", mrand48(), G_mrand48());
805 }
806
807 return 0;
808 }
809
810 */
#define NULL
Definition ccmath.h:32
void void void void G_fatal_error(const char *,...) __attribute__((format(printf
void G_warning(const char *,...) __attribute__((format(printf
#define n_(strs, strp, num)
Definition glocale.h:11
#define _(str)
Definition glocale.h:10
unsigned short uint16
Definition lrand48.c:65
void G_random_advance(struct G_random_state *state, int64_t draws)
Advance a generator of the program's own as if values had been drawn.
Definition lrand48.c:759
unsigned int uint32
Definition lrand48.c:66
void G_random_init_layout_bounded(struct G_random_layout *layout, int64_t seed, int64_t units, int64_t max_draws)
Initialize a layout whose units draw at most a number of values.
Definition lrand48.c:562
#define MASK48
Definition lrand48.c:71
long G_mrand48(void)
Generate an integer in the range [-2^31, 2^31)
Definition lrand48.c:328
#define LCG_A
Definition lrand48.c:69
long G_lrand48(void)
Generate an integer in the range [0, 2^31)
Definition lrand48.c:307
#define WHOLE_SPAN_MAX_UNITS
Definition lrand48.c:81
long G_srand48_auto(void)
Seed the pseudo-random number generator from the time and PID.
Definition lrand48.c:243
signed int int32
Definition lrand48.c:67
#define HI(x)
Definition lrand48.c:106
void G_random_init_layout_exact(struct G_random_layout *layout, int64_t seed, int64_t units, int64_t draws_per_unit)
Initialize a layout whose units draw an exact number of values.
Definition lrand48.c:521
int64_t G_random_layout_length(const struct G_random_layout *layout)
Return the number of values a unit may draw.
Definition lrand48.c:661
void G_random_state_from_seed(struct G_random_state *state, int64_t seed)
Seed a pseudo-random number generator of the program's own.
Definition lrand48.c:488
void G_srand48(long seedval)
Seed the pseudo-random number generator.
Definition lrand48.c:117
int64_t G_random_layout_batches(const struct G_random_layout *layout)
Return the number of batches that fit into the span.
Definition lrand48.c:648
#define LCG_SPAN
Definition lrand48.c:77
#define LO(x)
Definition lrand48.c:105
#define LCG_B
Definition lrand48.c:70
double G_drand48(void)
Generate a floating-point value in the range [0,1)
Definition lrand48.c:351
void G_random_init_layout(struct G_random_layout *layout, int64_t seed, int64_t units)
Initialize a layout which gives the units the whole span.
Definition lrand48.c:617
double G_random_double(struct G_random_state *state)
Generate a floating-point value in the range [0,1) from a generator of the program's own.
Definition lrand48.c:782
void G_random_state_for_unit(struct G_random_state *state, const struct G_random_layout *layout, int64_t unit)
Put a generator state at the start of a unit's stream.
Definition lrand48.c:741
int64_t G_random_generate_seed(void)
Generate a seed for a random number generator.
Definition lrand48.c:196
void G_random_state_for_batch(struct G_random_state *state, const struct G_random_layout *layout, int64_t batch, int64_t unit)
Put a generator state at the start of a unit's stream in a batch.
Definition lrand48.c:693
const char * name
Definition named_colr.c:6
struct state state
Definition parser.c:101
double b
Definition r_raster.c:37
double t
Definition r_raster.c:37
double r
Definition r_raster.c:37
int gettimeofday(struct timeval *, struct timezone *)
#define getpid
Definition unistd.h:20
#define x