← Fundamentals
Fundamentals

Floating-point numbers

Which value is stored, and which step — arithmetic, comparison or display — produced the surprise?

Follow the stored numeric value through comparison, calculation and display.

Outcome

Separate a floating-point value’s stored representation from arithmetic, comparison and display; predict NaN and infinity; and keep exact decimal work in integer units.

Terminology (8)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

binary64
The 64-bit IEEE 754 format: one sign bit, 11 exponent bits and 52 fraction bits. Normal values have 53 significant binary digits.
Representation error
The difference between a decimal you write and the nearest binary64 value actually stored.
Rounding error
The change introduced when an exact arithmetic result is rounded to a binary64 value, for the separately rounded operations discussed here.
Shortest round-trip printing
Printing the fewest decimal digits that read back as the same stored value.
Tolerance
An allowed difference for treating two values as equal, chosen for their units and size.
NaN
“Not a number”: the result of an undefined operation. It compares unequal to every value, itself included.
Infinity
A signed nonfinite value beyond finite range; the examples obtain it through the language’s named infinity API.
Stream precision
How many significant digits std::cout prints (6 by default), or decimals with std::fixed.

Precision, range and displayed digits

Floating-point represents numbers using a finite significant part scaled by an exponent. Binary64 is the format used for the runtime values in these examples. Its finite precision leaves gaps between representable values, so storing a decimal or performing arithmetic can require rounding.

Formatting chooses a decimal description of a stored value; it does not increase that value’s precision. An equality decision and a rounding policy must therefore be judged against the actual representation. Finite amounts, infinities and NaN also require different handling when a calculation feeds a real decision.

01Representation

Most decimal fractions are stored approximately

A receipt tool must print a total, decide whether the customer paid the right amount and apply a percentage discount with a stated cent-rounding rule. A displayed 0.30 can conceal a value that fails the payment comparison, and a decimal half-cent can move below the boundary before rounding. Track the stored value through each receipt decision.

Before totaling prices, inspect what parsing a decimal can retain. Normal binary64 values have 53 significant binary digits, scaled by a power of two; precision and exponent range both limit exact representation. The shown literals use the nearest representable values under the default rounding profile.

The program displays the stored values of 0.1 and 0.375 rounded to twenty decimal places. Which original decimal was stored exactly?

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iomanip>
#include <iostream>

int main() {
    std::cout << std::fixed << std::setprecision(20);
    std::cout << 0.1 << '\n';
    std::cout << 0.375 << '\n';
}
Which of the two values is stored exactly?
C++ · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
clang++ -std=c++2c -Wall -Wextra -pedantic main.cpp -o main && ./main

Use the selected language’s setup from the first reading and replace the file for each experiment. The examples use binary64 number, float64 and f64; the C++ track target uses binary64 double. Predictions describe the shown separate operations under the track’s default rounding and formatting profile.

02Arithmetic

The shown binary64 additions round before comparison

The receipt’s 0.10 and 0.20 prices have already been approximated. In the shown separate binary64 addition, their exact sum is rounded to a representable value. The program compares 0.1 + 0.2 with 0.3, first with literals and then with variables, and prints the sum with the default formatting. Predict all three lines.

std::cout prints a double with 6 significant digits by default.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>

int main() {
    std::cout << std::boolalpha << (0.1 + 0.2 == 0.3) << '\n';

    double a = 0.1;
    double b = 0.2;

    std::cout << (a + b == 0.3) << '\n';
    std::cout << a + b << '\n';
}
What do the three lines print?
Loading 0.1 + 0.2 lands between two doubles…

03NaN and infinity

Special values break the usual comparison rules

Payment classification assumes finite inputs. This reduced preflight probe explains why callers need that acceptance condition: binary64 also has infinities and NaN, “not a number”, which can arise from calculations such as infinity minus infinity. Can the ordinary comparison branches classify these special values as usable receipt amounts?

Predict the first line: whether NaN equals itself, and whether NaN is either below 1 or at least 1.

std::numeric_limits<double> supplies quiet_NaN() and infinity().

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cmath>
#include <iostream>
#include <limits>

int main() {
    double missing = std::numeric_limits<double>::quiet_NaN();
    double huge = std::numeric_limits<double>::infinity();

    std::cout << std::boolalpha;
    std::cout << (missing == missing) << ' ' << (missing < 1 || missing >= 1) << '\n';
    std::cout << huge << ' ' << -huge << '\n';
    std::cout << std::isnan(huge - huge) << '\n';
}
What does the first line print?

04Rounding and display

Rounding works on the stored value, not the decimal you typed

A half-price discount on 2.01 has an intended decimal result of 1.005, exactly at a half-cent. This reduced probe assigns 1.005 directly, rounds it to cents in two ways and prints the stored value in between. Predict the first line.

std::fixed with std::setprecision(2) prints two decimals.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cmath>
#include <iomanip>
#include <iostream>

int main() {
    double price = 1.005;

    std::cout << std::fixed << std::setprecision(2) << price << '\n';
    std::cout << std::setprecision(20) << price << '\n';
    std::cout << std::defaultfloat << std::round(price * 100) / 100 << '\n';
}
What does the first line print?

05Repair the receipt

Print, compare, then round to the cent

Repair the receipt’s printed amounts, payment verdict and percentage discount. Display precision alone cannot settle a cent comparison; the half-up discount must also preserve the intended cent value before its percentage calculation.

This terminal supports finite nonnegative amounts with exactly two decimal digits. Each receipt has at most 100 prices; prices, the total and the amount paid are at most 99999.99. Discounts use whole percentages from 0 through 100. The lab receives data within those bounds; input validation is outside these repairs.

The lab opens in your reading language and has its own language control. Each file contains its imports, reader and complete main. Later levels supply the earlier correct helpers.

Repair the receipt

Display, comparison and exact decimal rounding, each on amounts read as binary floating point.

  1. easy · F-FLOAT-V4-1 Print amounts to the cent
  2. medium · F-FLOAT-V4-2 Check the payment
  3. hard · F-FLOAT-V4-3 Round the discount
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.