GRASS 8 Programmer's Manual 8.6.0dev(2026)-000a00fca6
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/* Advance a generator of the program's own by one step. The
371 * multiplication may wrap around at 2^64; that does not change the result
372 * modulo 2^48. */
373static uint64_t lcg_step(uint64_t x)
374{
375 return (LCG_A * x + LCG_B) & MASK48;
376}
377
378/* Turn a seed into a generator state the way G_srand48() does: only the
379 * low 32 bits are used, so a negative seed gives the state of its two's
380 * complement 32-bit value. */
381static uint64_t lcg_seed(int64_t seed)
382{
383 return (((uint64_t)seed & 0xFFFFFFFF) << 16) | 0x330E;
384}
385
386/* Advance the generator by an arbitrary number of steps without taking
387 * them one at a time. One step is the affine map x -> a * x + c, and
388 * composing two such maps gives another, so the map for `steps` steps is
389 * built by repeated squaring, as an integer power would be. */
390static uint64_t lcg_jump(uint64_t x, uint64_t steps)
391{
392 uint64_t a_total = 1, c_total = 0; /* the identity map */
393 uint64_t a = LCG_A, c = LCG_B; /* one step */
394
395 while (steps) {
396 if (steps & 1) {
397 c_total = (a * c_total + c) & MASK48;
398 a_total = (a * a_total) & MASK48;
399 }
400 /* Square the map, so a and c then describe twice as many steps. */
401 c = (a * c + c) & MASK48;
402 a = (a * a) & MASK48;
403 steps >>= 1;
404 }
405
406 return (a_total * x + c_total) & MASK48;
407}
408
409/* The generator tells seeds apart by their low 32 bits only. Seeds read
410 * as signed or as unsigned 32-bit values are accepted, so -1 and
411 * 4294967295 are both accepted and are the same seed; anything else is
412 * rejected rather than silently losing its high bits. */
413static void check_seed(int64_t seed)
414{
415 if (!seed_in_range(seed))
416 G_fatal_error(_("Random number seed %" PRId64 " is outside the range "
417 "from -2147483648 to 4294967295 the generator can use"),
418 seed);
419}
420
421static void check_units(int64_t units)
422{
423 if (units <= 0)
424 G_fatal_error(_("The number of units of a random number layout must "
425 "be positive, not %" PRId64),
426 units);
427}
428
429/* The draws from the start of one batch to the start of the next: those of
430 * one batch, units * stride, or one more when that number is even. With an
431 * odd distance, as with an odd stride between units, the same draw of
432 * different batches is as unrelated as the generator allows; an even
433 * distance would relate those draws, the more simply the more often 2
434 * divides it. */
435static uint64_t batch_distance(const struct G_random_layout *layout)
436{
437 return ((uint64_t)layout->units * (uint64_t)layout->stride) | 1;
438}
439
440/* Fill in a layout of units of the given stride, all of one batch first,
441 * then those of the next batch. The batches that fit are those whose last
442 * stream ends within the span. Callers must check beforehand that
443 * units * stride does not overflow. */
444static void fill_layout(struct G_random_layout *layout, int64_t seed,
445 int64_t units, int64_t stride)
446{
447 uint64_t draws = (uint64_t)units * (uint64_t)stride;
448
449 layout->start = lcg_seed(seed);
450 layout->units = units;
451 layout->stride = stride;
452 layout->batches = 0;
453 if (draws <= LCG_SPAN)
454 layout->batches =
455 (int64_t)((LCG_SPAN - draws) / batch_distance(layout) + 1);
456 layout->whole_span = false;
457}
458
459/*!
460 * \brief Seed a pseudo-random number generator of the program's own
461 *
462 * Puts the state at the seed: it then produces the sequence G_srand48()
463 * followed by G_drand48() produces for the same seed, so code moving from
464 * the shared generator to one of its own reproduces its existing results.
465 * Use it for a single sequence, which then has the whole span to itself;
466 * for one sequence per unit of work, use a layout and
467 * G_random_state_for_unit().
468 *
469 * A seed outside -2^31 to 2^32 - 1 is a fatal error. A negative seed
470 * means its two's complement 32-bit value, as for G_srand48().
471 *
472 * Thread-safe as long as no two threads seed the same state.
473 *
474 * \param[out] state generator state to seed
475 * \param[in] seed seed, from -2^31 to 2^32 - 1
476 */
478{
479 check_seed(seed);
480 state->state = lcg_seed(seed);
481}
482
483/*!
484 * \brief Initialize a layout whose units draw an exact number of values
485 *
486 * The span is cut into streams of exactly \p draws_per_unit draws, one per
487 * unit, placed one after another from the seed. Unit u of batch 0 therefore
488 * draws what a single sequence from G_random_state_from_seed() draws at
489 * positions u * \p draws_per_unit to (u + 1) * \p draws_per_unit - 1, so
490 * the units together reproduce a serial run whatever order they are
491 * processed in. Further batches follow, see G_random_state_for_batch().
492 * A unit which draws more than \p draws_per_unit values runs into the
493 * next unit's stream; when the number of draws is only bounded, use
494 * G_random_init_layout_bounded().
495 *
496 * The stride is \p draws_per_unit. G_random_layout_length() returns it,
497 * and G_random_layout_batches() returns the batches that fit, which is 0
498 * when \p units * \p draws_per_unit draws do not fit into the span. See \ref
499 * gislib_random_streams.
500 *
501 * A seed outside -2^31 to 2^32 - 1, a number of units or of draws which
502 * is not positive, or a product of the two beyond the range of int64_t
503 * is a fatal error.
504 *
505 * \param[out] layout layout to initialize
506 * \param[in] seed seed, see G_random_state_from_seed()
507 * \param[in] units number of units of work, positive
508 * \param[in] draws_per_unit number of values each unit draws, positive
509 */
512{
513 check_seed(seed);
514 check_units(units);
515 if (draws_per_unit <= 0)
516 G_fatal_error(_("The number of random numbers a unit draws must be "
517 "positive, not %" PRId64),
519 if (units > INT64_MAX / draws_per_unit)
520 G_fatal_error(_("A random number layout of %" PRId64 " units of "
521 "%" PRId64 " draws each is too large (the number of "
522 "draws must not exceed %" PRId64 ")"),
523 units, draws_per_unit, INT64_MAX);
524 fill_layout(layout, seed, units, draws_per_unit);
525}
526
527/*!
528 * \brief Initialize a layout whose units draw at most a number of values
529 *
530 * As G_random_init_layout_exact(), but each unit may draw any number of
531 * values up to \p max_draws: the streams are \p max_draws draws long, or
532 * \p max_draws + 1 when \p max_draws is even. With an odd stride, units
533 * 2^i apart in number start an odd multiple of 2^i draws apart, so the
534 * differences of their states are fixed in the low i + 2 bits only; an
535 * even stride would add its own power of two to that count.
536 *
537 * The stride is \p max_draws rounded up to odd. G_random_layout_length()
538 * returns it, and G_random_layout_batches() returns the batches that fit,
539 * which is 0 when \p units times the stride draws do not fit into the span. See
540 * \ref gislib_random_streams.
541 *
542 * A seed outside -2^31 to 2^32 - 1, a number of units or a bound which is
543 * not positive, or a product of the units and the stride beyond the range
544 * of int64_t is a fatal error.
545 *
546 * \param[out] layout layout to initialize
547 * \param[in] seed seed, see G_random_state_from_seed()
548 * \param[in] units number of units of work, positive
549 * \param[in] max_draws most values any unit draws, positive
550 */
553{
554 int64_t stride;
555
556 check_seed(seed);
557 check_units(units);
558 if (max_draws <= 0)
559 G_fatal_error(_("The most random numbers a unit draws must be "
560 "positive, not %" PRId64),
561 max_draws);
562 /* INT64_MAX is odd, so an even bound can be rounded up. */
563 stride = max_draws % 2 == 0 ? max_draws + 1 : max_draws;
564 if (units > INT64_MAX / stride)
565 G_fatal_error(_("A random number layout of %" PRId64 " units of at "
566 "most %" PRId64 " draws each is too large (the number "
567 "of units times the bound rounded up to odd must not "
568 "exceed %" PRId64 ")"),
569 units, max_draws, INT64_MAX);
570 fill_layout(layout, seed, units, stride);
571}
572
573/*!
574 * \brief Initialize a layout which gives the units the whole span
575 *
576 * For units whose number of draws is not known in advance. The span is
577 * divided into parts, as many as there are units, or one more when that
578 * number is even. The stride is 2^46 / parts rounded down, and then down
579 * to odd when there is more than one part, and unit u starts u * stride
580 * draws after the seed. The odd number of parts keeps the unit halfway or
581 * a quarter of the way along from starting 2^45 or 2^44 draws after unit
582 * 0, distances at which this generator's values relate (see
583 * \ref gislib_random_streams): the unit nearest to 2^45 starts at least
584 * 0.48 of a stride away from it and the unit nearest to 2^44 at least
585 * 0.24, so a unit meets such a relation only after drawing about a
586 * quarter of its stride. The odd stride puts units 2^i apart in number an
587 * odd multiple of 2^i draws apart, as in a bounded layout. A single unit
588 * keeps the whole span of 2^46 draws, as a state from
589 * G_random_state_from_seed() does. The layout holds a single batch.
590 *
591 * The number of units is limited to 2^20: the rounded stride loses up to
592 * two draws per unit, which accumulate along the span, so beyond that
593 * count the units nearest to 2^45 and 2^44 would drift toward them. A
594 * bounded layout serves any number of units.
595 *
596 * The stride is the length of a part. G_random_layout_length() returns
597 * it, and G_random_layout_batches() returns 1.
598 *
599 * A seed outside -2^31 to 2^32 - 1, or a number of units which is not
600 * positive or above 2^20, is a fatal error.
601 *
602 * \param[out] layout layout to initialize
603 * \param[in] seed seed, see G_random_state_from_seed()
604 * \param[in] units number of units of work, from 1 to 2^20
605 */
607 int64_t units)
608{
609 uint64_t parts, stride;
610
611 check_seed(seed);
612 check_units(units);
613 if (units > WHOLE_SPAN_MAX_UNITS)
614 G_fatal_error(_("A random number layout of the whole span takes at "
615 "most %" PRId64 " units, not %" PRId64 "; a bounded "
616 "layout serves any number of units"),
617 WHOLE_SPAN_MAX_UNITS, units);
618 parts = (uint64_t)units | 1;
619 stride = LCG_SPAN / parts;
620 if (parts > 1 && stride % 2 == 0)
621 stride--;
622 layout->start = lcg_seed(seed);
623 layout->units = units;
624 layout->stride = (int64_t)stride;
625 layout->batches = 1;
626 layout->whole_span = true;
627}
628
629/*!
630 * \brief Return the number of batches that fit into the span
631 *
632 * \param[in] layout an initialized layout
633 *
634 * \return the batches that fit, 1 for a layout of the whole span, 0 when
635 * one batch of the layout does not fit into the span
636 */
638{
639 return layout->batches;
640}
641
642/*!
643 * \brief Return the number of values a unit may draw
644 *
645 * \param[in] layout an initialized layout
646 *
647 * \return the stride of the layout, the number of values every unit may
648 * draw without running into the next unit's stream
649 */
651{
652 return layout->stride;
653}
654
655/*!
656 * \brief Put a generator state at the start of a unit's stream in a batch
657 *
658 * A batch is one stream for every unit of the layout, and the batches
659 * follow one another along the span. They start units * stride draws
660 * apart, or one more when that number is even, and the stream of \p unit
661 * in \p batch starts \p unit * stride draws after the start of the batch.
662 * With the odd distance, as with an odd stride, the same draw of different
663 * batches is as unrelated as the generator allows; what an even distance
664 * would relate there is related between draws whose numbers differ
665 * instead. The state is set whatever it held before, so the same call
666 * always restarts the same sequence. See \ref gislib_random_streams.
667 *
668 * A \p unit outside 0 to units - 1, a negative \p batch, a \p batch other
669 * than 0 of a layout of the whole span, or a \p batch beyond the batches
670 * that fit is a fatal error. When no batch fits, batch 0 is still allowed,
671 * and only batch 0: a tool which warned that its layout does not fit into
672 * the span may use it as earlier versions did.
673 *
674 * Thread-safe as long as no two threads use the same state; the layout
675 * is only read.
676 *
677 * \param[out] state generator state to set
678 * \param[in] layout an initialized layout
679 * \param[in] batch number of the batch, from 0
680 * \param[in] unit number of the unit, from 0 to units - 1
681 */
683 const struct G_random_layout *layout,
684 int64_t batch, int64_t unit)
685{
686 uint64_t offset;
687
688 if (unit < 0 || unit >= layout->units)
689 G_fatal_error(_("Random number unit %" PRId64 " is out of range "
690 "(must be between 0 and %" PRId64 ")"),
691 unit, layout->units - 1);
692 if (batch < 0)
693 G_fatal_error(_("Random number batch %" PRId64 " is out of range "
694 "(must not be negative)"),
695 batch);
696 if (batch > 0 && layout->whole_span)
697 G_fatal_error(_("Random number batch %" PRId64 " is out of range "
698 "(a layout of the whole span holds a single batch)"),
699 batch);
700 if (layout->batches >= 1 && batch >= layout->batches)
701 G_fatal_error(n_("Random number batch %" PRId64 " is out of range "
702 "(%" PRId64 " batch fits into the generator's span)",
703 "Random number batch %" PRId64 " is out of range "
704 "(%" PRId64 " batches fit into the generator's span)",
705 (unsigned long)layout->batches),
706 batch, layout->batches);
707 if (layout->batches == 0 && batch > 0)
708 G_fatal_error(_("Random number batch %" PRId64 " is out of range "
709 "(no batch fits into the generator's span, only batch "
710 "0 can be used)"),
711 batch);
712
713 /* With batch below the batches that fit, the offset is below 2^46; with
714 * batch 0 of a layout which does not fit, it may reach past the span.
715 * It is below 2^63 either way, since units times stride is. */
716 offset = (uint64_t)batch * batch_distance(layout) +
717 (uint64_t)unit * (uint64_t)layout->stride;
718 state->state = lcg_jump(layout->start, offset);
719}
720
721/*!
722 * \brief Put a generator state at the start of a unit's stream
723 *
724 * The same as G_random_state_for_batch() with batch 0.
725 *
726 * \param[out] state generator state to set
727 * \param[in] layout an initialized layout
728 * \param[in] unit number of the unit, from 0 to units - 1
729 */
731 const struct G_random_layout *layout, int64_t unit)
732{
734}
735
736/*!
737 * \brief Advance a generator of the program's own as if values had been drawn
738 *
739 * Moves the state by \p draws draws without taking them one at a time,
740 * so that the next G_random_double() returns what the draw after those
741 * would have returned.
742 *
743 * A negative \p draws is a fatal error.
744 *
745 * \param[in,out] state a seeded generator state
746 * \param[in] draws number of values to skip, not negative
747 */
749{
750 if (draws < 0)
751 G_fatal_error(_("Cannot advance a random number generator by "
752 "%" PRId64 " draws (the number must not be negative)"),
753 draws);
754 state->state = lcg_jump(state->state, (uint64_t)draws);
755}
756
757/*!
758 * \brief Generate a floating-point value in the range [0,1) from a
759 * generator of the program's own
760 *
761 * Thread-safe as long as no two threads share a state. Unlike
762 * G_drand48(), this needs no atomics and so behaves identically on every
763 * build.
764 *
765 * \param[in,out] state generator state, set with
766 * G_random_state_from_seed(), G_random_state_for_unit() or
767 * G_random_state_for_batch()
768 *
769 * \return the generated value
770 */
771double G_random_double(struct G_random_state *state)
772{
773 state->state = lcg_step(state->state);
774 /* The state is below 2^53, so the conversion to double is exact. */
775 return (double)state->state / 281474976710656.0; /* 2^48 */
776}
777
778/*
779
780 Test program
781
782 int main(int argc, char **argv)
783 {
784 long s = (argc > 1) ? atol(argv[1]) : 0;
785 int i;
786
787 srand48(s);
788 G_srand48(s);
789
790 for (i = 0; i < 100; i++) {
791 printf("%.50f %.50f\n", drand48(), G_drand48());
792 printf("%lu %lu\n", lrand48(), G_lrand48());
793 printf("%ld %ld\n", mrand48(), G_mrand48());
794 }
795
796 return 0;
797 }
798
799 */
#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:748
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:551
#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:510
int64_t G_random_layout_length(const struct G_random_layout *layout)
Return the number of values a unit may draw.
Definition lrand48.c:650
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:477
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:637
#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:606
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:771
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:730
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:682
const char * name
Definition named_colr.c:6
struct state state
Definition parser.c:101
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