00001
00002
00003 #ifndef MISC_H
00004 #define MISC_H
00005
00006 #include <vector>
00007 #include <math.h>
00008 #include <stdlib.h>
00009
00010
00011 #ifndef M_PI
00012 #define M_PI 3.14159265358979323846
00013 #endif
00014
00015 namespace FD {
00016
00018 template <class T>
00019 T &max(T &a, T &b) {return a > b ? a : b;}
00020
00021 inline int max(int a, int b) {return a > b ? a : b;}
00022 inline float max(float a, float b) {return a > b ? a : b;}
00023 inline double max(double a, double b) {return a > b ? a : b;}
00024
00026 template <class T>
00027 T &min(T &a, T &b) {return a < b ? a : b;}
00028
00029 inline int min(int a, int b) {return a < b ? a : b;}
00030 inline float min(float a, float b) {return a < b ? a : b;}
00031 inline double min(double a, double b) {return a < b ? a : b;}
00032
00034 template <class T>
00035 inline T sqr(T x) {return x*x;}
00036
00038 template <class T>
00039 inline T abs(T x) {return x >= 0 ? x : -x;}
00040
00041
00042 #ifdef __GNUC__
00043 #define VAR_ARRAY
00044 #endif
00045
00046
00047 #if defined (VAR_ARRAY)
00048
00049 #define DYN_VEC(type, num, var) type var[num];
00050
00051 #elif defined (HAVE_ALLOCA_H)
00052
00053 #include <alloca.h>
00054
00055 #define DYN_VEC(type, num, var) type *var=(type*)alloca((num)*sizeof(type));
00056
00057 #elif defined WIN32
00058
00059 #include <malloc.h>
00060 #define DYN_VEC(type, num, var) type *var=(type*)_alloca((num)*sizeof(type));
00061
00062 #else
00063
00064
00065 template <class T>
00066 class DynVec_ {
00067 T *array;
00068 public:
00069 explicit DynVec_(int n) : array(new T[n]) {}
00070 ~DynVec_() {delete [] array;}
00071
00072 operator T* () {return array;}
00073 };
00074 #define DYN_VEC(type, num, var) DynVec_<type> var(num);
00075
00076 #endif
00077
00078
00079
00080
00081
00082
00083 template<int M2>
00084 inline int _log2(int i)
00085 {
00086 if (i>>M2)
00087 {
00088 return M2+_log2<M2/2>(i>>M2);
00089 } else {
00090 return _log2<M2/2>(i);
00091 }
00092 }
00093
00094 template<>
00095 inline int _log2<1>(int i)
00096 {
00097 if (i&2)
00098 return 1;
00099 else
00100 return 0;
00101 }
00102
00103 #ifndef __CYGWIN__
00104 inline int log2(int i)
00105 {
00106 return _log2<16>(i);
00107 }
00108 #else
00109 #warning log2(inti) not implemented yet for CYGWIN
00110 #endif
00111
00112
00113
00115
00116 inline float gauss_rand(float sd)
00117 {
00118 float U1, U2, S, x;
00119 do {
00120 U1 = float(rand())/float(RAND_MAX);
00121 U2 = float(rand())/float(RAND_MAX);
00122 U1 = 2*U1-1;
00123 U2 = 2*U2-1;
00124 S = U1*U1 + U2*U2;
00125 } while (S >= 1 || S == 0.0f);
00126 x = sd*sqrt(-2 * log(S) / S) * U1;
00127
00128
00129
00130
00131 return x;
00132 }
00133 }
00134
00135 #endif