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