GRASS GIS 8 Programmer's Manual  8.4.0dev(2024)-f8115df121
xrand.c
Go to the documentation of this file.
1 #include <stdlib.h>
2 
3 #include <grass/config.h>
4 #include <grass/gis.h>
5 #include <grass/raster.h>
6 #include <grass/calc.h>
7 
8 /****************************************************************
9 rand(lo,hi) random values between a and b
10 ****************************************************************/
11 
12 int f_rand(int argc, const int *argt, void **args)
13 {
14  int i;
15 
16  if (argc < 2)
17  return E_ARG_LO;
18  if (argc > 2)
19  return E_ARG_HI;
20 
21  switch (argt[0]) {
22  case CELL_TYPE: {
23  CELL *res = args[0];
24  CELL *arg1 = args[1];
25  CELL *arg2 = args[2];
26 
27  for (i = 0; i < columns; i++) {
28  unsigned int x = (unsigned int)G_mrand48();
29  int lo = arg1[i];
30  int hi = arg2[i];
31 
32  if (lo > hi) {
33  int tmp = lo;
34 
35  lo = hi;
36  hi = tmp;
37  }
38  res[i] = (lo == hi) ? lo : (int)(lo + x % (unsigned int)(hi - lo));
39  }
40  return 0;
41  }
42  case FCELL_TYPE: {
43  FCELL *res = args[0];
44  FCELL *arg1 = args[1];
45  FCELL *arg2 = args[2];
46 
47  for (i = 0; i < columns; i++) {
48  double x = G_drand48();
49  FCELL lo = arg1[i];
50  FCELL hi = arg2[i];
51 
52  if (lo > hi) {
53  FCELL tmp = lo;
54 
55  lo = hi;
56  hi = tmp;
57  }
58  res[i] = (FCELL)(lo + x * (hi - lo));
59  }
60  return 0;
61  }
62  case DCELL_TYPE: {
63  DCELL *res = args[0];
64  DCELL *arg1 = args[1];
65  DCELL *arg2 = args[2];
66 
67  for (i = 0; i < columns; i++) {
68  double x = G_drand48();
69  DCELL lo = arg1[i];
70  DCELL hi = arg2[i];
71 
72  if (lo > hi) {
73  DCELL tmp = lo;
74 
75  lo = hi;
76  hi = tmp;
77  }
78  res[i] = lo + x * (hi - lo);
79  }
80  return 0;
81  }
82  default:
83  return E_INV_TYPE;
84  }
85 }
@ E_INV_TYPE
Definition: calc.h:15
@ E_ARG_HI
Definition: calc.h:12
@ E_ARG_LO
Definition: calc.h:11
int columns
Definition: calc.c:11
long G_mrand48(void)
Generate an integer in the range [-2^31, 2^31)
Definition: lrand48.c:151
double G_drand48(void)
Generate a floating-point value in the range [0,1)
Definition: lrand48.c:166
float FCELL
Definition: gis.h:627
double DCELL
Definition: gis.h:626
int CELL
Definition: gis.h:625
#define FCELL_TYPE
Definition: raster.h:12
#define DCELL_TYPE
Definition: raster.h:13
#define CELL_TYPE
Definition: raster.h:11
#define x
int f_rand(int argc, const int *argt, void **args)
Definition: xrand.c:12