Representation of Floating Point Numbers

Representation of Floating Point Numbers

People sometimes complain about the inaccuracy of floating point arithmetic. To demonstrate the level of floating pint inaccuracy, consider the following program:

   #include    using namespace std;  int main()  {    float f1 = 2000.58;    float f2 =  2000.0;    cout << f1 - f2 << endl;  }  

On my machine, this program prints 0.579956 instead of 0.58. More complex calculations yield higher inaccuracy. What is going on here?

First, remember that rounding, approximation and truncation are not the responsibility of C++ but rather, they depend on the particular hardware that your machine uses. Note also that floating point numbers are merely an approximation based on the IEEE standard. On most machines, type float occupies 32 bits. The IEEE standard requires that 1 bit be used for the sign representation (i.e., negative/positive values), 8 bits for exponent, and the remaining 23 bits are for the mantissa. Because a mantissa always has the form 1.nnnn

See also  5 Ways to Improve Customer Experience

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist