Floating point arithmetic

suggest change

Floating point numbers are weird.

The first mistake that nearly every single programmer makes is presuming that this code will work as intended:

float total = 0;
for (float a = 0; a != 2; a += 0.01f) {
    total += a;
}

The novice programmer assumes that this will sum up every single number in the range 0, 0.01, 0.02, 0.03, ..., 1.97, 1.98, 1.99, to yield the result 199—the mathematically correct answer.

Two things happen that make this untrue:

  1. On IEEE 754 binary32, a never becomes equal to 2, so the loop does not terminate.
  2. If the condition is rewritten as a < 2, the loop terminates, but the total is not 199. On IEEE 754 binary32 it is about 201 (200.999… after 201 additions).

The reason that this happens is that Floating Point Numbers represent approximations of their assigned values.

The classical example is the following computation:

// :glot
#include <iostream>

int main() {
    const double a = 0.1;
    const double b = 0.2;
    const double c = 0.3;
    if (a + b == c) {
        // This never prints on IEEE754-compliant machines
        std::cout << "This Computer is Magic!\n";
    } else {
        std::cout << "This Computer is pretty normal, all things considered.\n";
    }
}
This Computer is pretty normal, all things considered.

Though what the programmer sees are three numbers written in base 10, the compiler and the hardware use binary. 0.1, 0.2, and 0.3 have no finite base-2 representation, so they are stored approximately, similar to how 1/3 is stored as 0.333333333333333... in base 10.

// A binary64 value has a 53-bit significand, including the implicit leading bit.
double a =     0011111110111001100110011001100110011001100110011001100110011010; // imperfect representation of 0.1
double b =     0011111111001001100110011001100110011001100110011001100110011010; // imperfect representation of 0.2
double c =     0011111111010011001100110011001100110011001100110011001100110011; // imperfect representation of 0.3
double a + b = 0011111111010011001100110011001100110011001100110011001100110100; // Note that this is not quite equal to the "canonical" 0.3!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents