#027 – Floats or doubles?

Introduction

Integers are great and all but if you want to store numbers with a fractional component. This is often what you see in the real world. Temperature, distance, currency all contain a fractional component.

In these applications, you must use the floating point type.

Types of floats

  1. float
  2. double
  3. long double

For this article, I’ll be discussing the first two.

A float is usually 4 bytes, a double 8 bytes. Since a double occupies more memory, it has more range and precision.

To be precise, a float as 6-9 digits of precision (typically 7) whilst a double has 15 – 18 digits of precision (typically 16). This is according to the IEEE 754 standard. This is what computers use to store floating-point numbers. In this model, float corresponds to single precision, while double corresponds to double precision.

We can demonstrate this with an example:

The example

NOTE: std::cout defaults to a precision of 6. This will truncate our values. Thus, std::setprecision() is used to adjust the precision

#include <iomanip> // for output manipulator std::setprecision()
#include <iostream>

int main()
{
    std::cout << std::setprecision(17); 
    std::cout << 0.33333333333333333333333333333333333333f <<'\\n'; 
    std::cout << 0.33333333333333333333333333333333333333 << '\\n'; 
}

// Output
0.333333343267440
0.3333333333333333 // // Immense precision. That's more like it

The precision of the float begins to drift away after ~7 digits. The compiler isn’t being negligent rather it cannot store EXACTLY that floating-point number. It merely stores an approximation. Thus, it is only accurate to a certain significant figure.

However, the double is accurate to 16 digits That’s more than double the precision!

In Closing

Select double over float unless memory is a luxury. The lack of precision in a float will often lead to inaccuracies.

Leave a Reply

Your email address will not be published. Required fields are marked *