19.8 Determining Accuracy

I l @ ve RuBoard

There is a simple way of determining how accurate your floating point is (for simple calculations). The method used in the following program is to add 1.0 + 0.1, 1.0 + 0.01, 1.0 + 0.001, and so on until the second number gets so small that it makes no difference in the result.

The old C language specified that all floating-point numbers were to be done in double . C++ removed that restriction, but because many C++ compilers are really front-ends to a C compiler, frequently C++ arithmetic is done in double . This means that if number1 and number2 are declared as float , the expression:

 while (number1 + number2 != number1) 

is equivalent to:

 while (double(number1) + double(number2) != double(number1)) 

If you use the 1 + 0.001 trick, the automatic conversion of float to double may give a distorted picture of the accuracy of your machine. (In one case, 84 bits of accuracy were reported for a 32-bit format.) Example 19-1 computes the accuracy of both floating point as used in equations and floating point as stored in memory. Note the trick used to determine the accuracy of the floating-point numbers in storage.

Example 19-1. float/float.cpp
 #include <iostream> #include <iomanip> int main(  ) {     // two number to work with      float number1, number2;     float result;               // result of calculation      int   counter;              // loop counter and accuracy check      number1 = 1.0;     number2 = 1.0;     counter = 0;     while (number1 + number2 != number1) {         ++counter;         number2 = number2 / 10.0;     }     std::cout << std::setw(2) << counter <<          " digits accuracy in calculations\n";     number2 = 1.0;     counter = 0;     while (true) {         result = number1 + number2;         if (result == number1)             break;         ++counter;         number2 = number2 / 10.0;     }     std::cout << std::setw(2) << counter <<          " digits accuracy in storage\n";     return (0); } 

The results are as follows :

 20 digits accuracy in calculations  8 digits accuracy in storage 

This program gives only an approximation of the floating-point precision arithmetic. A more accurate definition can be found in the standard include file float.h .

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net