Richards
Solving The Richards equation with temporally periodic surface boundary conditions
util.h
Go to the documentation of this file.
1 #ifndef UTIL_H_
2 #define UTIL_H_
3 
5 
6 #include <cmath>
7 #include <vector>
8 #include <cstdio>
9 #include <cstdlib>
10 
12 template <class T>
13 void swap (T *a, T *b) {
14  T c;
15  c = *a;
16  *a = *b;
17  *b = c;
18 }
19 
21 double max (double *a, long n);
22 
24 double absmax (double *a, long n);
25 
27 double min (double *a, long n);
28 
30 template <class T>
31 double maxreldif (T a, T b, long n) {
32  double rd, mrd = 0;
33  for (long i=0; i<n; i++) {
34  rd = fabs(a[i] - b[i])/fabs(b[i]);
35  if ( rd > mrd )
36  mrd = rd;
37  }
38  return(mrd);
39 }
40 
42 template <class T>
43 long argclose (T a, double b, long n) {
44 
45  double m = INFINITY;
46  long i;
47  //find min and its index
48  long idx = 0;
49  for (i=0; i<n; i++) {
50  if (fabs(a[i] - b) < m) {
51  m = fabs(a[i] - b);
52  idx = i;
53  }
54  }
55 
56  return(idx);
57 }
58 
60 std::vector<double> linspace (double a, double b, long n);
61 
63 std::vector<double> logspace (double a, double b, long n);
64 
66 
70 template <class T>
71 std::vector<T> subsample (std::vector<T> v, unsigned long n) {
72 
73  //calculate the approximate interval size
74  unsigned long size = v.size();
75  unsigned long step = size/n;
76  //fill a new vector
77  if ( (step == 0) || (step == 1) ) {
78  //just copy the vector
79  std::vector<T> r(v.begin(), v.end());
80  //finish
81  return(r);
82  } else {
83  //step is not zero, subsample the vector
84  std::vector<T> r;
85  r.push_back( v[0] );
86  unsigned long i;
87  for (i=step; i<size; i+=step) r.push_back(v[i]);
88  if (i < size - 1) r.push_back( v.back() );
89  //finish
90  return(r);
91  }
92 }
93 
94 #endif
logspace
std::vector< double > logspace(double a, double b, long n)
create an logarithmically spaced vector of values over a range
Definition: util.cc:57
linspace
std::vector< double > linspace(double a, double b, long n)
create an evenly spaced vector of values over a range
Definition: util.cc:36
max
double max(double *a, long n)
find max of array
Definition: util.cc:8
min
double min(double *a, long n)
find min of array
Definition: util.cc:26
absmax
double absmax(double *a, long n)
find max magnitude of array
Definition: util.cc:18
swap
void swap(T *a, T *b)
swaps two variables
Definition: util.h:13
subsample
std::vector< T > subsample(std::vector< T > v, unsigned long n)
subsample a vector, keeping first and last elements
Definition: util.h:71
maxreldif
double maxreldif(T a, T b, long n)
finds the maximum relative difference between two arrays/vectors
Definition: util.h:31
argclose
long argclose(T a, double b, long n)
find index of value in array closest to a number
Definition: util.h:43