AI Wiki中文/EN

Floating point and rounding

浮点数与舍入误差

Inspect the exact binary value of 0.1, distinguish precision from range, and reason about rounding, exceptional values, and tolerances.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The computer did not store one tenth

Type 0.1 + 0.2 == 0.3 in Python and the result is false. This does not mean addition is random. On the usual binary64 platform, each decimal input is first mapped to a nearby binary fraction, and the sum is rounded again. The resulting bit pattern differs from the one obtained by converting 0.3 directly.

A finite binary fraction can represent one half exactly, but not one tenth. Just as decimal notation needs an endless string of threes for one third, binary notation needs endless digits for one tenth. Printing a short decimal hides most of those stored digits; it does not replace the stored value. Python floating-point tutorial, Section 15.1

A movable scale with a fixed number of significant bits

A normal binary floating-point value has a sign, a significand, and an exponent. With p significant bits it can be written as

x=(−1)s(1+f2p−1)2e,0≤f<2p−1.x=(-1)^s\left(1+\frac{f}{2^{p-1}}\right)2^e,\qquad 0\leq f<2^{p-1}.

Here f is an integer fraction field and e is the unbiased exponent. Binary64 has p=53: 52 stored fraction bits plus the leading one for normal values. Its normal exponent range is −1022 through 1023. Adjacent values in a binade [2e,2e+1)[2^e,2^{e+1}) are separated by 2e−522^{e-52}. Spacing grows with magnitude; “64 bits” does not mean a fixed number of decimal places.

Near one, the gap to the next larger representable value is often called machine epsilon. For binary64 that gap and the round-to-nearest unit roundoff are different:

ϵ=2−52,u=2−53.\epsilon=2^{-52},\qquad u=2^{-53}.

The common rounding model fl⁡(z)=z(1+δ)\operatorname{fl}(z)=z(1+\delta) with ∣δ∣≤u|\delta|\leq u concerns correctly rounded, finite results in the normal range under round-to-nearest. It is not a universal relative-error guarantee near underflow, after overflow, or for an arbitrary library function. Goldberg uses “machine epsilon” for a unit-roundoff bound, so compare definitions before comparing symbols. Goldberg, Relative Error and Ulps

The stored value of 0.1 has a precise error:

float⁡(0.1)=3602879701896397255,float⁡(0.1)−110=1180143985094819840.\operatorname{float}(0.1)=\frac{3602879701896397}{2^{55}},\qquad \operatorname{float}(0.1)-\frac1{10}=\frac1{180143985094819840}.

This is representation error. Later arithmetic and a numerical algorithm can add other errors; keeping those stages separate helps locate a failure.

Inspect the bits through exact fractions

The complete program uses only Python’s standard library. It explicitly checks the binary64 precision and round-to-nearest assumptions before demonstrating midpoint ties, nonassociative addition, tiny values, and Python’s overflow exception. Fraction.from_float captures the exact stored fraction, not the decimal value you originally intended.

import math
import sys
from fractions import Fraction as F

# This demonstration explicitly requires binary64 with round-to-nearest.
assert sys.float_info.radix == 2 and sys.float_info.mant_dig == 53
assert sys.float_info.rounds == 1
stored = F.from_float(.1)
assert stored == F(3602879701896397, 2**55)
assert stored-F(1,10) == F(1,180143985094819840)
assert .1+.2 != .3
assert math.isclose(.1+.2, .3, rel_tol=1e-15)
epsilon = sys.float_info.epsilon
unit_roundoff = epsilon/2
assert epsilon == 2.**-52
assert math.nextafter(1.,math.inf)-1. == epsilon
assert 1.+unit_roundoff == 1.  # midpoint tie rounds to the even significand
assert 1.+epsilon > 1.
a,b,c = 2.**53,1.,-(2.**53)
assert (a+b)+c == 0.
assert a+(b+c) == 1.
assert math.fsum([a,b,c]) == 1.
assert math.ulp(0.) == 2.**-1074
assert math.ulp(0.)/2 == 0.
assert math.copysign(1.,-0.) == -1.
assert math.isnan(float('nan'))
assert float('nan') != float('nan')
try:
    math.exp(1000.)
except OverflowError:
    pass
else:
    raise AssertionError("expected Python math overflow")

These fixed-size demonstrations have constant cost. For an array of n values, summation requires at least O(n)O(n) reads, and a more accurate summation method can cost more than a naive accumulation. fsum reduces summation error but cannot restore information already lost when inputs were converted. Its behavior also does not make every compound expression exact. Python math documentation

Precision, range, and special values

Binary64’s smallest positive normal value is 2−10222^{-1022}. Subnormal values fill the gap toward zero with constant spacing 2−10742^{-1074}, using no implicit leading one. Relative precision deteriorates there; sufficiently tiny results round to zero. Underflow is broader than “always becomes zero”: small results can be represented subnormally, and exception signaling depends on tininess and inexactness rules.

Signed zeros compare equal but retain a sign bit. Infinity is not a large finite answer, and NaN represents an invalid or undefined numerical result rather than a missing measurement by definition. NaN is unequal to itself, so test it with isnan. APIs differ in whether invalid arithmetic returns a special value or raises an exception: Python’s math.exp(1000) raises OverflowError in this example. Do not assume every operation imitates a GPU array library.

An approximate comparison needs a scale and a reason. A useful rule is

∣a−b∣≤max⁡(rmax⁡(∣a∣,∣b∣),t),|a-b|\leq\max\bigl(r\max(|a|,|b|),t\bigr),

with nonnegative relative tolerance r and absolute tolerance t. Near zero, a relative tolerance alone may be ineffective. Choose t from the units and expected error of the task, not as a universal “small number.” Never use approximate equality to disguise a broken integer count or an invalid probability normalization.

Predict before running

  1. Is Fraction.from_float(0.1) exactly one tenth? Answer: no; use Fraction(1,10) for that exact rational intention.
  2. Why can adding one to 2532^{53} disappear? Answer: spacing above that point is two, and the halfway result rounds to an even significand.
  3. Does binary64 have the same spacing near one and near 2202^{20}? Answer: no; the latter spacing is 2202^{20} times larger within the corresponding binades.
  4. Can a formatter that prints two decimal places fix arithmetic error? Answer: no. It changes the displayed string, not the computed value.

What reduced precision changes

AI systems often trade precision and range against memory and throughput. The relevant questions are which format stores values, which format accumulates products, whether scaling is applied, and where rounding occurs. Two formats with the same total bit count can divide those bits differently. This article establishes the vocabulary; numerical stability examines how changing the computation can avoid losing useful information.

Make a prediction, then check

In binary64, how does the gap above one compare with unit roundoff?

Choose one answer

Learning objectives

  • Distinguish representation error, rounding, precision, and exponent range.
  • Inspect arithmetic using exact fractions, adjacent floats, and justified tolerances.

Prerequisites & connections

Explore related knowledge →

References

  1. What Every Computer Scientist Should Know About Floating-Point Arithmetic — Oracle edited reprint
    David Goldberg · 1991
  2. Python — Floating-Point Arithmetic: Issues and Limitations
    Python Software Foundation
  3. Python — math: Mathematical functions
    Python Software Foundation

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: specified-source comparison, derivation checks, independent numerical checks, and paragraph-level bilingual comparison; no independent human peer review.

  • Checked adjacent spacing and ties-to-even with Fraction across 41 binary magnitudes, plus exact 0.1 error, nonassociative addition, subnormals, negative zero, and exceptions.
  • Distinguished ε from u and the normal-range error model from underflow; example behavior is scoped to the checked binary64 / round-to-nearest environment.
  • Compared bilingual assumptions, claims, numbers, exercise answers and citations; structural checks additionally compare formulas, code, main anchors and source IDs.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.