GRASS GIS 8 Programmer's Manual  8.2.2dev(2023)-3d2c704037
xpow.c
Go to the documentation of this file.
1 
2 #include <math.h>
3 
4 #include <grass/gis.h>
5 #include <grass/raster.h>
6 #include <grass/calc.h>
7 
8 /****************************************************************
9 pow(a,b)
10  a raised to the power b
11 ****************************************************************/
12 
13 static int ipow(int x, int y)
14 {
15  int res = 1;
16 
17  while (y) {
18  if (y & 1)
19  res *= x;
20  y >>= 1;
21  x *= x;
22  }
23  return res;
24 }
25 
26 int f_pow(int argc, const int *argt, void **args)
27 {
28  int i;
29 
30  if (argc < 2)
31  return E_ARG_LO;
32  if (argc > 2)
33  return E_ARG_HI;
34 
35  if (argt[1] != argt[0] || argt[2] != argt[0])
36  return E_ARG_TYPE;
37 
38  switch (argt[0]) {
39  case CELL_TYPE:
40  {
41  CELL *res = args[0];
42  CELL *arg1 = args[1];
43  CELL *arg2 = args[2];
44 
45  for (i = 0; i < columns; i++) {
46  if (IS_NULL_C(&arg1[i]) || IS_NULL_C(&arg2[i]) || arg2[i] < 0)
47  SET_NULL_C(&res[i]);
48  else
49  res[i] = ipow(arg1[i], arg2[i]);
50  }
51  return 0;
52  }
53  case FCELL_TYPE:
54  {
55  FCELL *res = args[0];
56  FCELL *arg1 = args[1];
57  FCELL *arg2 = args[2];
58 
59  for (i = 0; i < columns; i++) {
60  if (IS_NULL_F(&arg1[i]) || IS_NULL_F(&arg2[i]))
61  SET_NULL_F(&res[i]);
62  else if (arg1[i] < 0 && arg2[i] != ceil(arg2[i]))
63  SET_NULL_F(&res[i]);
64  else {
66  res[i] = pow(arg1[i], arg2[i]);
68  SET_NULL_F(&res[i]);
69  }
70  }
71  return 0;
72  }
73  case DCELL_TYPE:
74  {
75  DCELL *res = args[0];
76  DCELL *arg1 = args[1];
77  DCELL *arg2 = args[2];
78 
79  for (i = 0; i < columns; i++) {
80  if (IS_NULL_D(&arg1[i]) || IS_NULL_D(&arg2[i]))
81  SET_NULL_D(&res[i]);
82  else if (arg1[i] < 0 && arg2[i] != ceil(arg2[i]))
83  SET_NULL_D(&res[i]);
84  else {
86  res[i] = pow(arg1[i], arg2[i]);
88  SET_NULL_D(&res[i]);
89  }
90  }
91  return 0;
92  }
93  default:
94  return E_INV_TYPE;
95  }
96 }
#define CELL_TYPE
Definition: raster.h:11
#define SET_NULL_C(x)
Definition: calc.h:32
double DCELL
Definition: gis.h:614
#define IS_NULL_F(x)
Definition: calc.h:29
#define x
#define IS_NULL_C(x)
Definition: calc.h:28
Definition: calc.h:13
int columns
Definition: calc.c:12
volatile int floating_point_exception
Definition: calc.c:9
#define DCELL_TYPE
Definition: raster.h:13
Definition: calc.h:12
float FCELL
Definition: gis.h:615
#define IS_NULL_D(x)
Definition: calc.h:30
int f_pow(int argc, const int *argt, void **args)
Definition: xpow.c:26
int CELL
Definition: gis.h:613
#define FCELL_TYPE
Definition: raster.h:12
#define SET_NULL_F(x)
Definition: calc.h:33
#define SET_NULL_D(x)
Definition: calc.h:34