aboutsummaryrefslogtreecommitdiff
path: root/src/jtutil/fuzzy.cc
blob: e6b598dbc305d9f2ef5b73b79246328584b7a5f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// fuzzy.cc -- template for fuzzy comparisons et al on floating point values
// $Header$
//
// jtutil::fuzzy::tolerance - comparison tolerance
// jtutil::fuzzy::EQ
// jtutil::fuzzy::is_integer
// jtutil::fuzzy::floor
// jtutil::fuzzy::ceiling
//
// ***** template instantiations *****
//

#include <algorithm>
#include "stdc.h"
#include "util.hh"

//******************************************************************************

namespace jtutil
	  {
template <typename fp>
bool fuzzy<fp>::EQ(fp x, fp y)
{
fp max_abs = std::max(jtutil::abs(x), jtutil::abs(y));
fp epsilon = std::max(tolerance, tolerance*max_abs);

return jtutil::abs(x-y) <= epsilon;
}
	  }	// namespace jtutil::

//******************************************************************************

namespace jtutil
	  {
template <typename fp>
bool fuzzy<fp>::is_integer(fp x)
{
int i = round<fp>::to_integer(x);
return EQ(x, fp(i));
}
	  }	// namespace jtutil::

//******************************************************************************

namespace jtutil
	  {
template <typename fp>
int fuzzy<fp>::floor(fp x)
{
return fuzzy<fp>::is_integer(x)
       ? round<fp>::to_integer(x)
       : round<fp>::floor(x);
}
	  }	// namespace jtutil::

//******************************************************************************

namespace jtutil
	  {
template <typename fp>
int fuzzy<fp>::ceiling(fp x)
{
return fuzzy<fp>::is_integer(x)
       ? round<fp>::to_integer(x)
       : round<fp>::ceiling(x);
}
	  }	// namespace jtutil::

//******************************************************************************
//******************************************************************************
//******************************************************************************

//
// ***** template instantiations *****
//

// instantiation for <float>
template class jtutil::fuzzy<float>;
float jtutil::fuzzy<float>::tolerance = 1.0e-5;	     // about 100 * FLT_EPSILON

// instantiations for <double>
template class jtutil::fuzzy<double>;
double jtutil::fuzzy<double>::tolerance = 1.0e-12;   // about 1e4 * DBL_EPSILON