Practical example – iterating floating point values within a range

Let's address a fundamental problem with floating point values; they are very often not exact representations of the values assigned to them, rather they often represent something very near the assigned value.

For example, often when I would like to iterate from 0.0 to 1.0 with a step length of 0.1, I conveniently start with something like this:

for(float t = 0.0f; t <= 1.0f; t += 0.1f) {  std::cout << t << ", ";}// Prints 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,

The subtle problem here is that 0.1 cannot be represented by a floating point value; instead, it is represented by something slightly larger than 0.1, and therefore the loop will not reach 1.0f.

To solve ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.