aboutsummaryrefslogtreecommitdiff
path: root/src/jtutil/fuzzy.cc
blob: 97068524973355f002e1d6bdddf6b951e8e7b975 (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
// 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