00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026 #ifndef TAB_FN_H_IS_INCLUDED
00027 #define TAB_FN_H_IS_INCLUDED
00028
00029 #include <math.h>
00030 #include "std/error.H"
00031
00032 typedef double (*real_fn_t)(double);
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042 class TabulatedFunction {
00043 protected:
00044 double _a;
00045 double _b;
00046 double _len;
00047 int _res;
00048 double _rlen;
00049 double* _tab;
00050 real_fn_t _f;
00051
00052 public:
00053 TabulatedFunction(double a, double b, real_fn_t f, int res) :
00054 _tab(0) {
00055 init(a,b,f,res);
00056 }
00057 TabulatedFunction(double a, double b, double vals[], int res) :
00058 _tab(0) {
00059 init(a,b,vals,res);
00060 }
00061
00062 void init(double a, double b, double vals[], int res) {
00063 _a = a;
00064 _b = b;
00065 _len = (b-a);
00066 _f = 0;
00067 _res = res;
00068
00069 delete _tab;
00070 _tab = 0;
00071
00072 if (_len <= 0 ) {
00073 err_msg("TabulatedFunction::init: interval (%f,%f) is bad", a, b);
00074 } else if (_res < 1) {
00075 err_msg("TabulatedFunction::init: resolution (%d) is too small", _res);
00076 } else if ((_tab = new double [ _res + 1 ]) == 0) {
00077 err_ret("TabulatedFunction::init: can't allocate table");
00078 } else {
00079 _rlen = _res / _len;
00080 for (int n=0; n<=_res; n++) {
00081 _tab[n] = vals[n];
00082 }
00083 }
00084 }
00085
00086 void init(double a, double b, real_fn_t f, int res) {
00087 _a = a;
00088 _b = b;
00089 _len = (b - a);
00090 _f = f;
00091 _res = res;
00092
00093 delete _tab;
00094 _tab = 0;
00095
00096 if (_len <= 0 ) {
00097 err_msg("TabulatedFunction::init: interval (%f,%f) is bad", a, b);
00098 } else if (_res < 1) {
00099 err_msg("TabulatedFunction::init: resolution (%d) is too small", _res);
00100 } else if ((_tab = new double [ _res + 1 ]) == 0) {
00101 err_ret("TabulatedFunction::init: can't allocate table");
00102 } else {
00103 _rlen = _res / _len;
00104 for (int n=0; n<=_res; n++) {
00105 _tab[n] = (*_f)(n/_rlen + _a);
00106 }
00107 }
00108 }
00109
00110 double map(double x) const {
00111
00112
00113
00114 if (x<_a || x>=_b || !_tab)
00115 return _f ? (*_f)(x) : _tab ? _tab[x<_a? 0 : _res] : 0;
00116 else {
00117 double t = _rlen*(x - _a);
00118 int n = (int) floor(t);
00119 double d = t - n;
00120 return _tab[n] + (_tab[n+1] - _tab[n])*d;
00121 }
00122 }
00123 };
00124
00125 #endif // TAB_FN_H_IS_INCLUDED
00126
00127