Programming Search⌘K

Conceptcore

Floating-point arithmetic

Also called floating point, float, double, IEEE 754, binary64, rounding error, NaN.

A floating-point number is a binary fraction times a power of two. It covers a huge range with a fixed number of bits, but most decimal fractions, such as 0.1, have no exact form.

Applies to
core-languages

Idea

A computer stores a number in a fixed number of bits. An integer type stores each whole number in its range exactly. Real numbers are a different problem. There are infinitely many of them in any interval, so a fixed number of bits can hold only a few. Goldberg puts it this way: "Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation."1

A floating-point number is a fraction with a fixed number of binary digits, times a power of two. The power of two lets the point "float": the same 64 bits can hold the distance between two atoms or between two galaxies, each with about 16 significant decimal digits. The cost is that most numbers have no exact form. The result of each operation is rounded to the nearest number that does.

The best-known example is 0.1 + 0.2.

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
Output
0.30000000000000004
False

Nothing is broken here. The decimal fraction 0.1 has no exact binary form, as 1/3 has no exact decimal form. The program stores the nearest binary fraction, which is a little more than 0.1. The same is true of 0.2 and 0.3, and the rounding errors do not cancel.2

How it works

The format

IEEE 754 binary64, the double of C, Java and C# and the float of Python, has three fields in 64 bits.

Field Bits Meaning
sign 1 0 for positive, 1 for negative
exponent 11 the power of two, stored with a bias of 1023
fraction 52 the digits after the binary point

A normal number has the value (-1)^sign * 1.fraction * 2^(exponent - 1023). The leading 1. is not stored, so the significand has 53 bits of precision.1 Binary32, the float of C and Java, has 8 exponent bits and a 24-bit significand.

This program takes some doubles apart.

import struct

for x in [1.0, 0.1, -2.5, 0.0, -0.0]:
    bits = struct.unpack(">Q", struct.pack(">d", x))[0]
    sign = bits >> 63
    exponent = (bits >> 52) & 0x7FF
    fraction = bits & ((1 << 52) - 1)
    print(f"{x:>5}: sign {sign}, exponent field {exponent:4}, fraction {fraction:013x}")
Output
  1.0: sign 0, exponent field 1023, fraction 0000000000000
  0.1: sign 0, exponent field 1019, fraction 999999999999a
 -2.5: sign 1, exponent field 1024, fraction 4000000000000
  0.0: sign 0, exponent field    0, fraction 0000000000000
 -0.0: sign 1, exponent field    0, fraction 0000000000000

For 1.0 the exponent field is 1023, which means 2^0. For 0.1 it is 1019, which means 2^-4, and 0.1 is 1.6 times 2^-4. An exponent field of 0 marks zero and the subnormal numbers, and the two zeros differ only in the sign bit.

The fraction of 0.1 is the repeating binary pattern 1001 1001 ..., cut off after 52 bits and rounded up in the last digit. That is why the stored value is a little more than 0.1. Its exact value is 0.1000000000000000055511151231257827021181583404541015625.2

Rounding and the ulp

The gap between a double and the next larger double is one ulp, a "unit in the last place".1 The gap is not fixed. It doubles with each power of two. Near 1.0 it is 2^-52, about 2.2e-16. Near 1e16 it is 2.0, so above 2^53 not every integer has a double. This is why JavaScript defines Number.MAX_SAFE_INTEGER as 2^53 - 1.3

IEEE 754 requires that addition, subtraction, multiplication and division "be exactly rounded".1 The result is the exact result, rounded to a neighbouring double by the current rounding rule. The default rule is round to nearest, with ties to the value whose last bit is even. One operation therefore has an error of at most half an ulp. A sequence of operations can have a much larger error, because each step rounds again.

Special values

IEEE 754 adds values that are not numbers in the usual sense.1

  • Infinity. A result too large for the format becomes infinity, with a sign. A nonzero number divided by zero also gives an infinity.
  • NaN. "Not a number" is the result of an operation with no defined value, such as 0/0 or the square root of a negative number. Every operation with a NaN as input gives NaN, so the NaN reaches the end of the computation. A NaN is not equal to anything, not even to itself.
  • Signed zero. There are two zeros, +0 and -0. They compare equal, but 1/+0 is +inf and 1/-0 is -inf.
  • Subnormal numbers. Below the smallest normal number, the leading bit is 0 instead of 1. These numbers fill the gap between the smallest normal number and zero. Goldberg shows that they guarantee that x - y is zero only when x == y.1

The C example prints each of these.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeDouble and Float are the binary64 and binary32 types of the JVM, with the same rules as Java; no example file in this version. Alternative: Java.math.BigDecimal for exact decimal values, as in the Java example.
SQLNativeREAL and DOUBLE PRECISION are binary floating-point types; NUMERIC and DECIMAL hold exact decimal values. Alternative: NUMERIC with a fixed scale for money.
BashAbsent
PowerShellNative[double] and [decimal] are the .NET types; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: [decimal] for money, as in the C# example.
HTMLDoes not applyMarkup does not do arithmetic.
CSSDoes not applyCSS has numbers, but a page does not do arithmetic on them in the sense of this page.
Regular expressionsDoes not applyA pattern matches text, not numbers.
Language Verdict Form
Python native float is binary64; decimal.Decimal and fractions.Fraction for exact work
JavaScript native every number is binary64; BigInt for large integers
TypeScript native number as in JavaScript; bigint
Java native double and float; BigDecimal; strict semantics since Java 17
C native float, double and long double; IEC 60559 under Annex F
C++ native as C; std::numeric_limits describes each type
C# native double and float; decimal for money
Go native float64 and float32; exact constant arithmetic
Rust native f64 and f32; PartialOrd but not Ord; total_cmp
Kotlin native Double and Float of the JVM
PowerShell native [double] and [decimal] of .NET
Bash absent integer arithmetic only
SQL native REAL and DOUBLE PRECISION for floats; NUMERIC and DECIMAL for exact values
Regex n/a a pattern matches text, not numbers
HTML/CSS n/a CSS has numbers, but a page does not do arithmetic on them in the sense of this page

All the tier 1 languages that have floats use the IEEE 754 binary formats on common hardware, so 0.1 + 0.2 gives 0.30000000000000004 in each of them. The differences are in the types around the floats, in the comparisons, and in the rules for constants.

  • JavaScript has one number type. The Number type holds the binary64 values, except that the many NaN bit patterns of IEEE 754 are "represented in ECMAScript as a single special NaN".3
  • Java made all floating-point operations strict in Java 17. Java 1.2 had allowed a looser default because the x87 coprocessor could not match the strict rules at low cost. The SSE2 instructions, shipped "starting circa 2001", removed that reason.4
  • Rust gives f64 the traits PartialEq and PartialOrd, but not Eq and Ord, because a NaN breaks the laws of a total order. total_cmp gives the totalOrder predicate of the 2008 revision of IEEE 754, where every value, NaN too, has a place.5 The Rust example shows that v.sort() does not compile for a Vec<f64>.
  • Go evaluates constant expressions exactly: "Constant expressions are always evaluated exactly".6 The constant 0.1 + 0.2 becomes the double nearest to 0.3. The same sum of two variables gives 0.30000000000000004.
  • C# has a decimal type. It "is not an IEEE 754 floating-point format": it holds a 96-bit integer scaled by a power of 10, and it has no NaN and no infinity.7 It holds 0.1 exactly.
  • Python prints the shortest string that reads back as the same double. Since Python 3.1, repr(0.1) gives 0.1, though the stored value is not 0.1.2 Since Python 3.12, sum uses Neumaier summation for floats.8
  • C does not require IEEE 754. An implementation that defines __STDC_IEC_60559_BFP__, or the older macro __STDC_IEC_559__, conforms to IEC 60559 as Annex F specifies. C23 marks the older macro as obsolescent. The header <float.h> gives the properties of each type, such as DBL_MANT_DIG and DBL_EPSILON.9
  • Bash has no floats. The Bash example shows the error, and it keeps money as an integer number of cents.
PythonGitHub
import math
from decimal import Decimal
from fractions import Fraction

x = 0.1 + 0.2
print("0.1 + 0.2        =", x)
print("== 0.3           :", x == 0.3)
print("isclose(x, 0.3)  :", math.isclose(x, 0.3))
print("exact value of 0.1:", Decimal(0.1))
print("as a fraction     :", Fraction(0.1))
print("hex form of 0.1   :", (0.1).hex())
print("ulp(1.0)          :", math.ulp(1.0))
print("next after 1.0    :", math.nextafter(1.0, 2.0))
Output
0.1 + 0.2        = 0.30000000000000004
== 0.3           : False
isclose(x, 0.3)  : True
exact value of 0.1: 0.1000000000000000055511151231257827021181583404541015625
as a fraction     : 3602879701896397/36028797018963968
hex form of 0.1   : 0x1.999999999999ap-4
ulp(1.0)          : 2.220446049250313e-16
next after 1.0    : 1.0000000000000002
  • Verdict: native. A Python float is an IEEE 754 binary64 value on almost all platforms.
  • repr prints the shortest string that reads back as the same value, so 0.1 prints as 0.1 though the stored value is not 0.1.
  • Decimal(0.1) and Fraction(0.1) show the exact value that the float holds. float.hex shows its bits as a hexadecimal significand and a binary exponent.
  • math.isclose compares with a relative tolerance of 1e-09 by default.

Rounding errors add up in a long sum. A plain loop rounds after each addition. Since Python 3.12, the built-in sum uses Neumaier summation for floats, which keeps most of the lost low-order parts. math.fsum tracks all of them and rounds once at the end.

import math

def loop_sum(values):
    total = 0.0
    for v in values:
        total += v
    return total

for values in ([0.1] * 10, [1e16, 1.0, -1e16]):
    print(values if len(values) < 5 else "ten times 0.1")
    print("  loop     :", loop_sum(values))
    print("  sum      :", sum(values))
    print("  math.fsum:", math.fsum(values))
Output
ten times 0.1
  loop     : 0.9999999999999999
  sum      : 1.0
  math.fsum: 1.0
[1e+16, 1.0, -1e+16]
  loop     : 0.0
  sum      : 1.0
  math.fsum: 1.0

For money, use a decimal type. Decimal("0.10") holds exactly ten cents, and the context sets the rounding rule.

from decimal import Decimal, ROUND_HALF_EVEN

price = Decimal("0.10")
total = sum([price] * 3, Decimal("0"))
print("total:", total, total == Decimal("0.30"))
print("Decimal 2.675 to 0.01:", Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN))
print("float round(2.675, 2):", round(2.675, 2))
Output
total: 0.30 True
Decimal 2.675 to 0.01: 2.68
float round(2.675, 2): 2.67
  • round(2.675, 2) gives 2.67, not 2.68. The float nearest to 2.675 is a little below it, so the correct rounding of the stored value is down.
#include <cstdio>
#include <limits>
#include <numeric>
#include <vector>

double kahan_sum(const std::vector<double>& xs) {
    double sum = 0.0;
    double c = 0.0;  // the low-order part that the last addition lost
    for (double x : xs) {
        double y = x - c;
        double t = sum + y;
        c = (t - sum) - y;
        sum = t;
    }
    return sum;
}

int main() {
    using limits = std::numeric_limits<double>;
    std::printf("digits = %d, epsilon = %g, is_iec559 = %d\n", limits::digits, limits::epsilon(), limits::is_iec559);

    std::vector<double> xs(10'000'000, 0.1);
    double naive = std::accumulate(xs.begin(), xs.end(), 0.0);
    std::printf("naive sum of 10^7 x 0.1 = %.17g\n", naive);
    std::printf("Kahan sum of 10^7 x 0.1 = %.17g\n", kahan_sum(xs));
}
Output
digits = 53, epsilon = 2.22045e-16, is_iec559 = 1
naive sum of 10^7 x 0.1 = 999999.99983897537
Kahan sum of 10^7 x 0.1 = 1000000
  • Verdict: native. std::numeric_limits<double>::is_iec559 is true when double follows IEEE 754.
  • Kahan summation keeps the rounding error of each addition in c and puts it back into the next one. Its error does not grow with the number of terms the way that the error of a plain loop does.
  • The compensation depends on exact IEEE 754 rules. A compiler option such as -ffast-math lets the compiler treat (t - sum) - y as zero and remove the correction.
JavaGitHub
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] args) {
        double x = 0.1 + 0.2;
        System.out.println("0.1 + 0.2 = " + x);
        System.out.println("exact value of 0.1: " + new BigDecimal(0.1));
        System.out.println("BigDecimal 0.1 + 0.2 = " + new BigDecimal("0.1").add(new BigDecimal("0.2")));
        System.out.println("Math.ulp(1.0) = " + Math.ulp(1.0));
        System.out.println("Math.ulp(1e16) = " + Math.ulp(1e16));

        BigDecimal price = new BigDecimal("19.99");
        BigDecimal tax = price.multiply(new BigDecimal("0.075")).setScale(2, RoundingMode.HALF_EVEN);
        System.out.println("tax on 19.99 at 7.5%: " + tax);

        double nan = Double.NaN;
        System.out.println("NaN == NaN: " + (nan == nan));
        System.out.println("Double.valueOf(NaN).equals(NaN): " + Double.valueOf(nan).equals(nan));
        System.out.println("0.0 == -0.0: " + (0.0 == -0.0));
        System.out.println("Double.compare(0.0, -0.0): " + Double.compare(0.0, -0.0));
    }
}
Output
0.1 + 0.2 = 0.30000000000000004
exact value of 0.1: 0.1000000000000000055511151231257827021181583404541015625
BigDecimal 0.1 + 0.2 = 0.3
Math.ulp(1.0) = 2.220446049250313E-16
Math.ulp(1e16) = 2.0
tax on 19.99 at 7.5%: 1.50
NaN == NaN: false
Double.valueOf(NaN).equals(NaN): true
0.0 == -0.0: true
Double.compare(0.0, -0.0): 1
  • Verdict: native. double is IEEE 754 binary64 and float is binary32. Since Java 17, all floating-point operations are strict, so they give the same result on every JVM.
  • new BigDecimal(0.1) shows the exact value of the double. new BigDecimal("0.1") holds exactly one tenth. Make a BigDecimal from a string, not from a double.
  • == on double follows IEEE 754. Double.equals and Double.compare do not: they treat NaN as equal to itself and put -0.0 below 0.0, so that collections and sorting work.
  • Math.ulp gives the gap to the next larger double. The gap grows with the size of the number.

A loop that adds 0.1 ten times does not reach exactly 1.0.

This code runs but gives a wrong answer on purpose.

public class Main {
    public static void main(String[] args) {
        double total = 0.0;
        for (int i = 0; i < 10; i++) {
            total += 0.1;
        }
        System.out.println("total = " + total);
        System.out.println("total == 1.0: " + (total == 1.0));
    }
}
Output
total = 0.9999999999999999
total == 1.0: false
#include <float.h>
#include <math.h>
#include <stdio.h>

int main(void) {
    double x = 0.1 + 0.2;
    printf("0.1 + 0.2 = %.17g\n", x);
    printf("0.3       = %.17g\n", 0.3);
    printf("hex form of 0.1: %a\n", 0.1);
    printf("DBL_MANT_DIG = %d, DBL_DIG = %d\n", DBL_MANT_DIG, DBL_DIG);
    printf("DBL_EPSILON = %g\n", DBL_EPSILON);
    printf("DBL_MAX = %g\n", DBL_MAX);
    printf("DBL_MAX * 2 = %g\n", DBL_MAX * 2);
    printf("smallest normal = %g, smallest subnormal = %g\n", DBL_MIN, nextafter(0.0, 1.0));

    double zero = 0.0, neg = -0.0;
    printf("0.0 == -0.0: %d\n", zero == neg);
    printf("1/0.0 = %g, 1/-0.0 = %g\n", 1 / zero, 1 / neg);
    printf("signbit(-0.0) = %d\n", signbit(neg) != 0);
    double nan = zero / zero;
    printf("0/0 = %g, isnan = %d, nan == nan: %d\n", fabs(nan), isnan(nan) != 0, nan == nan);
}
Output
0.1 + 0.2 = 0.30000000000000004
0.3       = 0.29999999999999999
hex form of 0.1: 0x1.999999999999ap-4
DBL_MANT_DIG = 53, DBL_DIG = 15
DBL_EPSILON = 2.22045e-16
DBL_MAX = 1.79769e+308
DBL_MAX * 2 = inf
smallest normal = 2.22507e-308, smallest subnormal = 4.94066e-324
0.0 == -0.0: 1
1/0.0 = inf, 1/-0.0 = -inf
signbit(-0.0) = 1
0/0 = nan, isnan = 1, nan == nan: 0
  • Verdict: native. On almost all platforms double is IEEE 754 binary64. An implementation that defines __STDC_IEC_60559_BFP__ (C23) or __STDC_IEC_559__ (older standards) follows Annex F, which binds float and double to the IEC 60559 formats.
  • %.17g prints 17 significant digits, which are enough to tell any two doubles apart. %a prints the exact bits as a hexadecimal significand and a binary exponent.
  • Overflow gives infinity, and division of a nonzero number by zero gives an infinity with the sign of the zero. Neither is an error in IEEE 754 arithmetic.
  • The code prints fabs(nan), because the sign of a NaN from 0/0 depends on the processor.

Subtraction of two close values cancels the digits that they share. What is left is mostly the earlier rounding error.

#include <math.h>
#include <stdio.h>

int main(void) {
    double small = 1e-15;
    double naive = (1.0 + small) - 1.0;
    printf("(1 + 1e-15) - 1 = %.17g\n", naive);
    printf("relative error  = %.2g\n", fabs(naive - small) / small);

    double x = 1e-10;
    printf("log(1 + x)  = %.17g\n", log(1.0 + x));
    printf("log1p(x)    = %.17g\n", log1p(x));
}
Output
(1 + 1e-15) - 1 = 1.1102230246251565e-15
relative error  = 0.11
log(1 + x)  = 1.000000082690371e-10
log1p(x)    = 9.9999999995000007e-11
  • log1p computes log(1 + x) without the rounding of 1 + x, so it keeps the digits of a small x.
using System;

double d = 0.1 + 0.2;
Console.WriteLine($"double  0.1 + 0.2 = {d:R}, == 0.3: {d == 0.3}");

decimal m = 0.1m + 0.2m;
Console.WriteLine($"decimal 0.1 + 0.2 = {m}, == 0.3: {m == 0.3m}");

Console.WriteLine($"decimal 1 / 3 = {1m / 3m}");
Console.WriteLine($"double  1 / 3 = {1.0 / 3.0:R}");

Console.WriteLine($"Math.BitIncrement(1.0) = {Math.BitIncrement(1.0):R}");
Console.WriteLine($"double.Epsilon = {double.Epsilon:R}");
Console.WriteLine($"Math.Round(2.5) = {Math.Round(2.5)}, Math.Round(3.5) = {Math.Round(3.5)}");
Console.WriteLine($"Math.Round(2.5, MidpointRounding.AwayFromZero) = {Math.Round(2.5, MidpointRounding.AwayFromZero)}");
Output
double  0.1 + 0.2 = 0.30000000000000004, == 0.3: False
decimal 0.1 + 0.2 = 0.3, == 0.3: True
decimal 1 / 3 = 0.3333333333333333333333333333
double  1 / 3 = 0.3333333333333333
Math.BitIncrement(1.0) = 1.0000000000000002
double.Epsilon = 5E-324
Math.Round(2.5) = 2, Math.Round(3.5) = 4
Math.Round(2.5, MidpointRounding.AwayFromZero) = 3
  • Verdict: native. double is IEEE 754 binary64 and float is binary32. decimal is a 16-byte decimal type for money, with 28 to 29 significant digits. It is not an IEEE 754 format: it holds a 96-bit integer scaled by a power of 10, and it has no NaN and no infinity.
  • decimal holds 0.1 exactly, but it still rounds: one third has no exact decimal form.
  • double.Epsilon is the smallest positive subnormal double, not the gap after 1.0 that other languages call epsilon.
  • Math.Round rounds a midpoint to the even neighbour by default, as IEEE 754 does. Pass MidpointRounding.AwayFromZero for the rule that most people learn at school.
JavaScriptGitHub
const x = 0.1 + 0.2;
console.log("0.1 + 0.2 =", x);
console.log("=== 0.3   :", x === 0.3);
console.log("near 0.3  :", Math.abs(x - 0.3) < Number.EPSILON);
console.log("0.1 to 20 digits:", (0.1).toPrecision(20));
console.log("EPSILON   :", Number.EPSILON);
console.log("MAX_SAFE_INTEGER:", Number.MAX_SAFE_INTEGER);
console.log("2**53 + 1 :", 2 ** 53 + 1);
console.log("(1.005).toFixed(2):", (1.005).toFixed(2));
console.log("NaN === NaN:", NaN === NaN, " Object.is(NaN, NaN):", Object.is(NaN, NaN));
console.log("0 === -0  :", 0 === -0, " Object.is(0, -0):", Object.is(0, -0));
Output
0.1 + 0.2 = 0.30000000000000004
=== 0.3   : false
near 0.3  : true
0.1 to 20 digits: 0.10000000000000000555
EPSILON   : 2.220446049250313e-16
MAX_SAFE_INTEGER: 9007199254740991
2**53 + 1 : 9007199254740992
(1.005).toFixed(2): 1.00
NaN === NaN: false  Object.is(NaN, NaN): true
0 === -0  : true  Object.is(0, -0): false
  • Verdict: native. Every JavaScript number is an IEEE 754 binary64 value, and the language has no separate integer type for number.
  • An integer above Number.MAX_SAFE_INTEGER, which is 2^53 - 1, may not have an exact representation. 2 ** 53 + 1 rounds to 2 ** 53.
  • (1.005).toFixed(2) gives "1.00", because the stored value is a little below 1.005.
  • === follows IEEE 754: NaN is not equal to itself, and 0 equals -0. Object.is tells them apart.
  • A fixed comparison with Number.EPSILON works only near 1. For large numbers the gap between floats is much larger than Number.EPSILON.

An integer type with no size limit, BigInt, is exact for large integers.

const big = 2n ** 53n + 1n;
console.log(big.toString());
console.log(Number(big));
Output
9007199254740993
9007199254740992
TypeScriptGitHub
// Keep money as a whole number of cents, and format it only for output.
type Cents = number & { readonly __brand: "Cents" };

function cents(n: number): Cents {
  if (!Number.isSafeInteger(n)) throw new RangeError(`not a safe integer: ${n}`);
  return n as Cents;
}

function add(a: Cents, b: Cents): Cents {
  return cents(a + b);
}

function format(c: Cents): string {
  const sign = c < 0 ? "-" : "";
  const abs = Math.abs(c);
  return `${sign}${Math.trunc(abs / 100)}.${String(abs % 100).padStart(2, "0")}`;
}

let total = cents(0);
for (let i = 0; i < 10; i++) total = add(total, cents(10));
console.log("ten times 0.10 in cents:", format(total));

let floatTotal = 0;
for (let i = 0; i < 10; i++) floatTotal += 0.1;
console.log("ten times 0.1 as numbers:", floatTotal);

try {
  cents(0.1 * 3 * 100);
} catch (e) {
  console.log((e as Error).message);
}
Output
ten times 0.10 in cents: 1.00
ten times 0.1 as numbers: 0.9999999999999999
not a safe integer: 30.000000000000004
  • Verdict: native. TypeScript uses the number of JavaScript, which is IEEE 754 binary64. The type bigint holds integers of any size.
  • The type checker does not know whether a number holds an integer. A branded type such as Cents marks the values that the code has checked.
  • 0.1 * 3 * 100 is not exactly 30, so the check rejects it.
package main

import (
	"fmt"
	"math"
)

func main() {
	x := 0.1 + 0.2
	fmt.Println("0.1 + 0.2 =", x)

	a, b := 0.1, 0.2
	y := a + b
	fmt.Println("a + b     =", y)
	fmt.Println("a + b == 0.3:", y == 0.3)

	fmt.Printf("0.1 to 20 digits: %.20f\n", 0.1)
	fmt.Println("next after 1.0:", math.Nextafter(1.0, 2.0))

	var f32 float32 = 16777217
	fmt.Println("float32(16777217) =", f32)

	nan := math.NaN()
	m := map[float64]int{}
	m[nan] = 1
	m[nan] = 2
	fmt.Println("map with two NaN keys has length", len(m))
	_, ok := m[nan]
	fmt.Println("lookup of NaN finds it:", ok)
	clear(m)
	fmt.Println("length after clear:", len(m))
}
Output
0.1 + 0.2 = 0.3
a + b     = 0.30000000000000004
a + b == 0.3: false
0.1 to 20 digits: 0.10000000000000000555
next after 1.0: 1.0000000000000002
float32(16777217) = 1.6777216e+07
map with two NaN keys has length 2
lookup of NaN finds it: false
length after clear: 0
  • Verdict: native. float64 is IEEE 754 binary64 and float32 is binary32.
  • 0.1 + 0.2 is a constant expression. Go evaluates constant expressions exactly and rounds only when it stores the result, so x is the float nearest to 0.3. The sum of the variables a and b is rounded after each step, as at run time.
  • A float32 has a 24-bit significand, so 16777217 (2^24 + 1) rounds to 16777216.
  • NaN is not equal to itself, so each NaN key in a map is a new entry, and a lookup cannot find it. The built-in clear removes such entries.
RustGitHub
fn main() {
    let x = 0.1_f64 + 0.2;
    println!("0.1 + 0.2 = {x}");
    println!("== 0.3: {}", x == 0.3);
    println!("EPSILON = {:e}", f64::EPSILON);
    println!("bits of 0.1 = {:#018x}", 0.1_f64.to_bits());

    let mut v = vec![2.5, f64::NAN, -0.0, 0.0, -1.0, f64::INFINITY];
    v.sort_by(|a, b| a.total_cmp(b));
    println!("sorted with total_cmp: {v:?}");

    println!("NaN == NaN: {}", f64::NAN == f64::NAN);
    println!("NaN.partial_cmp(1.0): {:?}", f64::NAN.partial_cmp(&1.0));
}
Output
0.1 + 0.2 = 0.30000000000000004
== 0.3: false
EPSILON = 2.220446049250313e-16
bits of 0.1 = 0x3fb999999999999a
sorted with total_cmp: [-1.0, -0.0, 0.0, 2.5, inf, NaN]
NaN == NaN: false
NaN.partial_cmp(1.0): None
  • Verdict: native. f64 is IEEE 754 binary64 and f32 is binary32.
  • f64 implements PartialEq and PartialOrd but not Eq and Ord, because NaN is not equal to itself and has no order with other values. partial_cmp returns None for it.
  • total_cmp gives the total order of IEEE 754: negative NaN first, then the numbers with -0.0 before 0.0, then positive NaN.

sort needs Ord, so the compiler rejects a sort of a vector of f64.

This code does not compile, on purpose.

fn main() {
    let mut v = vec![2.5, 1.0, 3.0];
    v.sort();
    println!("{v:?}");
}
Output
BashGitHub

Bash arithmetic works on integers only. A decimal point in $(( )) is a syntax error.

This code fails on purpose. The output below is the error.

#!/usr/bin/env bash
echo $((0.1 + 0.2))
Output

Keep amounts as integers in the smallest unit, such as cents, and put the decimal point in only for output.

#!/usr/bin/env bash
total=0
for price in 199 250 1005; do
  total=$((total + price))
done
printf 'total: %d.%02d\n' $((total / 100)) $((total % 100))
Output
total: 14.54
  • Verdict: absent. Bash has no floating-point type. Tools such as awk and bc do the arithmetic when a script needs fractions.
  • Decimal floating point. A decimal format stores digits in base 10, so 0.1 is exact. Python's decimal, Java's BigDecimal and C#'s decimal work this way. They still round: one third has no exact decimal form.
  • Fixed point and integers. Money is often stored as an integer number of the smallest unit, such as cents. Addition is then exact, and rounding happens only where the business rules say. The TypeScript and Bash examples do this.
  • Rational numbers. Python's Fraction keeps a numerator and a denominator, and every result of +, -, * and / is exact. The numbers can grow large.
  • Other widths. Binary16 and bfloat16 have fewer bits and are common in machine learning. The x87 80-bit extended format has a 64-bit significand.1
  • Interval arithmetic. Each value is a pair of bounds that contain the true result. The rounding direction of each bound is chosen so that the interval stays correct.
  • Related pages. Conversion between floats and integers can overflow or lose digits (Type conversion, Integer overflow or wraparound). A random float in [0, 1) has its own pitfalls (Generate random numbers).

Pitfalls

Comparing with ==

Two computations of the same real number often give different doubles. Compare with a tolerance. Python's math.isclose uses a relative tolerance, by default 1e-09.11 A fixed absolute tolerance such as Number.EPSILON works only for values near 1. For values near 1e16, it is smaller than the gap between two neighbouring doubles.

Money in binary floats

Ten additions of 0.1 do not give exactly 1.0. The Java example loop prints 0.9999999999999999. A bill that adds many prices drifts by a cent now and then. Use a decimal type or integer cents.

Rounding a decimal that was never exact

round(2.675, 2) in Python gives 2.67, and (1.005).toFixed(2) in JavaScript gives "1.00". The functions are correct. The stored values are a little below 2.675 and 1.005, so the nearest result is the lower one.

Catastrophic cancellation

Subtraction of two close values removes the digits they share. Goldberg: the subtraction "did not introduce any error, but rather exposed the error introduced in the earlier multiplications".1 The C example computes (1 + 1e-15) - 1 with a relative error of 11%. Rewrite the formula where you can. log1p(x) computes log(1 + x) without that loss.

Summation order

Floating-point addition is not associative. (1e16 + 1.0) - 1e16 is 0, but (1e16 - 1e16) + 1.0 is 1. A long sum loses the small terms. The C++ example adds 0.1 ten million times. A plain loop gives 999999.99983897537, and Kahan summation gives 1000000. Python's math.fsum gives a correctly rounded sum.11

NaN in comparisons and collections

NaN == NaN is false. A sort with a comparison that does not handle NaN can give an order that is not sorted. In Go, each NaN key in a map is a separate entry that no lookup finds. Java's Double.equals and Double.compare treat NaN as equal to itself, so collections of Double work, but they differ from ==.

Optimizations that assume real arithmetic

Kahan summation computes c = (t - sum) - y. In real arithmetic this is always 0. Goldberg warns that an optimizer "that believed floating-point arithmetic obeyed the laws of algebra would conclude that C = [T-S] - Y = [(S+Y)-S] - Y = 0, rendering the algorithm completely useless".1 GCC's -ffast-math sets -funsafe-math-optimizations, which enables -fassociative-math, and that option allows such changes.10

Large integers in doubles

A double holds every integer up to 2^53 exactly, and not all of them above it. In JavaScript, 2 ** 53 + 1 gives 2 ** 53. IDs and counters from a database can pass this limit. Keep them as strings or BigInt.

Cost

  • Speed. Addition and multiplication of doubles are single instructions on modern processors, close to integer speed. Division and square root are slower.
  • Decimal types. decimal and BigDecimal work in software, and they are much slower than doubles. The difference matters for numerical work, not for a bill.
  • Subnormals. Some hardware handles subnormal numbers with software traps. Goldberg notes that programs that often underflow then run "noticeably slower".1 Options such as flush-to-zero trade gradual underflow for speed.
  • Compensated sums. Kahan summation does four operations for each term instead of one.

History

  • 1985. IEEE 754-1985 defined the binary32 and binary64 formats, the special values, and correct rounding of the basic operations.1
  • 1991. David Goldberg's survey "What Every Computer Scientist Should Know About Floating-Point Arithmetic" explained rounding error, the standard and its effect on compilers.1
  • Late 1990s. Java SE 1.2 added a looser default floating-point mode next to strictfp, because of the x87 coprocessor.4
  • 2008. The revision of IEEE 754 defined the totalOrder predicate that Rust's total_cmp follows.5
  • 2021. Java 17 made all floating-point operations strict again (JEP 306).4
  • 2023. Python 3.12 changed sum to use Neumaier summation for floats.8

References

  1. David Goldberg, What Every Computer Scientist Should Know About Floating-Point Arithmetic, ACM Computing Surveys 23(1), March 1991 (edited reprint by Sun Microsystems), the sections Relative Error and Ulps, Cancellation, Exactly Rounded Operations, The IEEE Standard (Formats and Operations, Special Quantities, NaNs, Signed Zero), and Theorem 8 (Kahan Summation Formula) with the paragraph on optimizers after it
  2. The Python Tutorial, 15. Floating-Point Arithmetic, Issues and Limitations, the opening section, and 15.1 Representation Error
  3. ECMAScript Language Specification (ECMA-262), 6.1.6.1 The Number Type; 21.1.2.6 Number.MAX_SAFE_INTEGER
  4. JEP 306, Restore Always-Strict Floating-Point Semantics (delivered in JDK 17), Summary and Motivation
  5. Rust standard library, primitive type f64, method total_cmp
  6. The Go Programming Language Specification, Constant expressions
  7. C# language reference, Floating-point numeric types, Characteristics of the floating-point types (the table and the notes on decimal)
  8. What's New In Python 3.12, Other Language Changes (sum uses Neumaier summation)
  9. ISO/IEC 9899 working draft N3220 (C23), 5.2.5.3.3 Characteristics of floating types <float.h>; 6.10.10.4 Conditional feature macros; Annex F, ISO/IEC 60559 floating-point arithmetic
  10. GCC manual, Options That Control Optimization, -ffast-math and -fassociative-math
  11. Python standard library, math, math.fsum, math.isclose, math.ulp

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/A2519N/text.yaml