diff options
Diffstat (limited to 'src/jtutil/fuzzy.cc')
-rw-r--r-- | src/jtutil/fuzzy.cc | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/src/jtutil/fuzzy.cc b/src/jtutil/fuzzy.cc new file mode 100644 index 0000000..9706852 --- /dev/null +++ b/src/jtutil/fuzzy.cc @@ -0,0 +1,66 @@ +// fuzzy.cc -- template for fuzzy comparisons et al on floating point values +// $Id$ +// +// fuzzy::tolerance - comparison tolerance +// fuzzy::EQ +// fuzzy::is_integer +// fuzzy::floor +// fuzzy::ceiling +// +// *** instantiations of fuzzy template for <float> and <double> +// + +#include "stdc.h" +#include "util++.hh" + +//***************************************************************************** + +template <class fpt> +bool fuzzy<fpt>::EQ(fpt x, fpt y) +{ +fpt max_abs = jtutil::max(jtutil::abs(x), jtutil::abs(y)); +fpt epsilon = jtutil::max(tolerance, tolerance*max_abs); + +return jtutil::abs<fpt>(x-y) <= epsilon; +} + +//***************************************************************************** + +template <class fpt> +bool fuzzy<fpt>::is_integer(fpt x) +{ +int i = round<fpt>::to_integer(x); +return EQ(x, fpt(i)); +} + +//***************************************************************************** + +template <class fpt> +int fuzzy<fpt>::floor(fpt x) +{ +return fuzzy<fpt>::is_integer(x) + ? round<fpt>::to_integer(x) + : round<fpt>::floor(x); +} + +//***************************************************************************** + +template <class fpt> +int fuzzy<fpt>::ceiling(fpt x) +{ +return fuzzy<fpt>::is_integer(x) + ? round<fpt>::to_integer(x) + : round<fpt>::ceiling(x); +} + +//***************************************************************************** +// *** instantiations of fuzzy template for <float> and <double> +//***************************************************************************** + +// instantiation for <float> +template class fuzzy<float>; +float fuzzy<float>::tolerance = 1.0e-5; // about 100 * FLT_EPSILON + +// instantiations for <double> +template class fuzzy<double>; +double fuzzy<double>::tolerance = 1.0e-12; // about 1e4 * DBL_EPSILON |