SOURCE FILE: 5.13.3.precision.cpp
#include <iostream.h> // input/output functions
#include <iomanip.h> // for formatting directives
#include <math.h> // math constants and functions
#include <limits.h> // integer-oriented limits.
#include <float.h> // float-oriented limits like FLT_EPSILON
int main ()
{
double x ;
cout << "This example shows that we can get reasonable" << endl ;
cout << "results by testing for equality within a" << endl ;
cout << "\"tolerance\" determined by FLT_EPSILON -- a" << endl ;
cout << "constant that measures the smallest" << endl ;
cout << "difference between numbers that the compiler" << endl ;
cout << "can accurately detect." << endl << endl ;
cout << setprecision(7)
<< setiosflags(ios::showpoint | ios::fixed) ;
cout << "FLT_EPSILON is: " << FLT_EPSILON << endl << endl ;
int i, j ;
for (i=1; i<100; i++)
for (j=1; j<i; j++)
{
x = float(j)/i ;
// cout << j << "/" << i << " is: " << x << endl ;
cout << "x is float(" << j << ")/" << i
<< " = " << x << " and "
<< i << "*x should be " << j ;
if (fabs (float(j)- i*x) > 100*FLT_EPSILON)
/* if the test is "good" we will not see the message below
at all in the output. */
cout << " ==> they do NOT test equal!" ;
cout << endl ;
}
return 0 ;
}