Class SafeFloat, which is similar to SafeInt, allows control over floating point numbers. Beyond the concerns with integers, floating point numbers are subject to rounding errors. For example, tests such as ``0.4 == 0.004 * 100'' incorrectly return false on many systems. The definitions of operator==, operator<, and operator> in class SafeFloat account for this by including a tolerance for equality testing; they also preserve the relation that at most one of a==b, a<b, and a>b is true. (Missing definitions parallel those of SafeInt except for the inclusion of TOLERANCE). In this example, absolute tolerance is used because it is easier to understand. A production version would use relative tolerance, where TOLERANCE is expressed as a fraction of the numbers involved and thus depends on the magnitude of those numbers. For example comparing SafeFloats a and b as in
if (a == b)
is equivalent to
if (((b - TOLERANCE) <= a) && (a <= (b + TOLERANCE)))
[ 1] class SafeFloat
[ 2] {
[ 3] private:
[ 4] double d;
[ 5] const float TOLERANCE = 0.00001;
[ 6]
[ 7] public:
[ 8] SafeFloat(double initial_value);
[ 9] SafeFloat(SafeFloat &initial_value);
[10] SafeFloat() { d = 0;}
[11]
[12] int operator==(const SafeFloat value)
[13] { return ((d <= value.d+TOLERANCE) &&
(d >= value.d - TOLERANCE));}
[14] int operator< (const SafeFloat other)
[15] { return (d < other.d - TOLERANCE);}
[16] int operator> (const SafeFloat other)
[17] { return (d > other.d + TOLERANCE);}
[18] };