Conceptcore
Floating-point rounding error
Also called rounding error, round-off error, roundoff error, representation error, why 0.1 + 0.2 is not 0.3.
A float holds the nearest binary fraction, not the decimal you wrote, and each operation rounds again. The errors are small, but they can add up or be exposed by a subtraction.
- Applies to
- core-languages
Idea
You type 0.1. The program does not store one tenth. It stores the binary fraction that is nearest to one tenth, because "most decimal fractions cannot be represented exactly as binary fractions".1 For a binary64 float, that fraction is 3602879701896397 / 2^55.1
from decimal import Decimal
from fractions import Fraction
print(Fraction(0.1))
print(Decimal(0.1))
print(Decimal(0.1 + 0.2))
print(Decimal(0.3))
print(0.1 + 0.2 == 0.3)
3602879701896397/36028797018963968
0.1000000000000000055511151231257827021181583404541015625
0.3000000000000000444089209850062616169452667236328125
0.299999999999999988897769753748434595763683319091796875
False
Fraction and Decimal show the exact value of each float. The stored 0.1 is a little more than one tenth, and the sum of 0.1 and 0.2 is a different float from the one nearest to 0.3. Neither number is wrong. Each one is the nearest float to its exact value.
A rounding error is the difference between the result of exact arithmetic and the result of the same steps with rounded arithmetic.2 It has two causes. The input can have no exact form (representation error), and each operation rounds its result. One error is very small. The problems come when errors add up, or when a subtraction removes the correct digits and leaves only the error.
How it works
Representation error
A binary64 float is an integer of 53 bits times a power of two.1 A decimal fraction such as 0.1 has an infinite binary expansion, 0.000110011001100..., as one third has an infinite decimal expansion. The machine cuts it off and rounds.1 The Round-off error article calls this "a form of roundoff error called representation error".2
Representation error happens once, when the value enters the program: in a literal, in a parse of text, or in a conversion from a decimal type. The program cannot get it back later, and rounding the input again does not help. The Python tutorial shows that round(0.1, 1) + round(0.1, 1) + round(0.1, 1) == round(0.3, 1) is false.1
The error of one operation
IEEE 754 requires that the basic operations round the exact result to a float. With the default rounding, the error is at most half a unit in the last place (ulp).3 The Python tutorial gives the same bound in other words: on most machines the error of one operation is no more than 1 part in 2^53.1 Goldberg measures error in two ways: in ulps, and as relative error, "the difference between the two numbers divided by the real number".3
Accumulated error
Each step of a long computation adds its own small error. "When a sequence of calculations with an input involving any roundoff error are made, errors may accumulate, sometimes dominating the calculation."2 A loop that adds 0.1 ten times does not give 1.0.
import math
from fractions import Fraction
total = 0.0
for _ in range(10):
total += 0.1
print("loop:", total)
print("math.fsum:", math.fsum([0.1] * 10))
values = [1e16, 1.0, -1e16]
print("loop over", values, "->", values[0] + values[1] + values[2])
print("math.fsum:", math.fsum(values))
print("exact:", float(sum(map(Fraction, values))))
loop: 0.9999999999999999
math.fsum: 1.0
loop over [1e+16, 1.0, -1e+16] -> 0.0
math.fsum: 1.0
exact: 1.0
math.fsum tracks the digits that each addition loses, so the result has only one rounding.1 Kahan summation does a similar job with one extra variable. For plain summation the worst-case error "grows proportional to n", while with a good compensation the bound is "effectively independent of n".4
Cancellation
A subtraction of two close numbers is exact, but the digits that the numbers share cancel. If those numbers already had rounding errors, the result shows mostly the errors. Goldberg calls this catastrophic cancellation, and for one example he writes: "The subtraction did not introduce any error, but rather exposed the error introduced in the earlier multiplications."3 A subtraction of exact values is benign cancellation.3
import math
x = 1e-10
print("(1 + x) - 1:", (1 + x) - 1)
print("exact: ", x)
print("log(1 + x): ", math.log(1 + x))
print("log1p(x): ", math.log1p(x))
(1 + x) - 1: 1.000000082740371e-10
exact: 1e-10
log(1 + x): 1.000000082690371e-10
log1p(x): 9.999999999500001e-11
1 + x rounds away most of the digits of x, and the subtraction shows what is left. Only 7 or 8 digits of the result are correct. log1p computes log(1 + x) without the cancellation.
Goldberg's rule is to change the formula: x*x - y*y has a catastrophic cancellation, and (x - y) * (x + y) has only a benign one.3
Ill-conditioned problems
Some problems magnify any small error in the input, whatever the algorithm. The condition number is "the ratio of the relative change in the solution to the relative change in the input".2 When it is large, a correct algorithm still gives a result with few correct digits.2
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript numbers are the binary64 numbers of JavaScript, so the same sums give the same errors. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin Double is the binary64 double of the JVM, and java.math.BigDecimal is available for exact decimal work. No example file exists because kotlinc is not installed. |
| SQL | Native | SQL has REAL and DOUBLE PRECISION, which round like binary floats, and NUMERIC and DECIMAL, which hold decimal values exactly. No example file exists. |
| Bash | Absent | Bash arithmetic expansion works on integers only, so a script has no floats and no float rounding error. No example file exists. |
| PowerShell | Native | PowerShell [double] is the binary64 System.Double of .NET, and [decimal] is System.Decimal. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no arithmetic. |
| CSS | Does not apply | CSS computes lengths, but a page does not do the sums of this page. |
| Regular expressions | Does not apply | A pattern matches text and does no arithmetic. |
| Language | Verdict | Form |
|---|---|---|
| Python | native | float is binary64; decimal.Decimal(x) and fractions.Fraction(x) show the exact value; math.fsum |
| JavaScript | native | every number is binary64; toPrecision shows more digits |
| TypeScript | native | as JavaScript |
| Java | native | double; new BigDecimal(x) shows the exact value; BigDecimal for decimal work |
| C | native | double; printf("%.55f") shows the exact value on glibc |
| C++ | native | as C; std::setprecision |
| C# | native | double; decimal for decimal work |
| Go | native | float64; %.55f; math/big for exact work |
| Rust | native | f64; {:.55} |
| Kotlin | native | Double of the JVM; BigDecimal |
| PowerShell | native | [double]; [decimal] |
| Bash | absent | integer arithmetic only |
| SQL | native | REAL and DOUBLE PRECISION round; NUMERIC is exact |
| Regex | n/a | no arithmetic |
| HTML | n/a | no arithmetic |
| CSS | n/a | no arithmetic on the page in this sense |
Every tier 1 language with floats uses the same binary formats on common hardware, so the same sums give the same errors. The languages differ in how much of the error they show and in the exact types they offer.
- Java shows the exact value through
BigDecimal(double). Its documentation warns that "The results of this constructor can be somewhat unpredictable", becausenew BigDecimal(0.1)is "actually equal to 0.1000000000000000055511151231257827021181583404541015625".5 The Java example usesBigDecimal.valueOf(0.1)and the string constructor for exact work. - C# has
decimal. Microsoft says it "is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors".6 The same page adds that it "does not eliminate the need for rounding".6 - Python has
decimal, where "Decimal numbers can be represented exactly", so0.1 + 0.1 + 0.1 - 0.3is exactly zero.7 - C, C++, Go and Rust print the exact value when you ask for enough digits, as the examples do with 55 digits after the point.
- Bash has no floats, so this error does not occur. The other errors of integer arithmetic do (Integer division and modulo).
from decimal import Decimal
prices = [0.1] * 10
print("float sum:", sum(prices), "loop:", end=" ")
total = 0.0
for p in prices:
total += p
print(total)
exact = sum([Decimal("0.1")] * 10)
print("Decimal sum:", exact)
print("Decimal(0.1):", Decimal(0.1))
print("cents:", sum([10] * 10), "->", f"{sum([10] * 10) / 100:.2f}")
print("round(2.675, 2):", round(2.675, 2), "stored:", Decimal(2.675))
float sum: 1.0 loop: 0.9999999999999999
Decimal sum: 1.0
Decimal(0.1): 0.1000000000000000055511151231257827021181583404541015625
cents: 100 -> 1.00
round(2.675, 2): 2.67 stored: 2.67499999999999982236431605997495353221893310546875
- Verdict: native. A Python
floatis a binary64 value, so the error is part of every float operation. - The built-in
sumuses extended precision for the intermediate steps, so it gives 1.0 where the plain loop gives 0.9999999999999999. Decimal("0.1")from a string is exact.Decimal(0.1)from a float shows the error that the float already has.round(2.675, 2)gives 2.67 because the stored value is below 2.675.
#include <cmath>
#include <iomanip>
#include <iostream>
int main() {
const double a = 1.0 + 1e-8;
const double b = 1.0;
const double x = a * a - b * b;
const double y = (a - b) * (a + b);
std::cout << std::setprecision(17);
std::cout << "a*a - b*b: " << x << '\n';
std::cout << "(a-b)*(a+b): " << y << '\n';
const double small = 1e-10;
std::cout << "log(1 + x): " << std::log(1.0 + small) << '\n';
std::cout << "log1p(x): " << std::log1p(small) << '\n';
std::cout << "expm1(x): " << std::expm1(small) << '\n';
std::cout << "exp(x) - 1: " << std::exp(small) - 1.0 << '\n';
}
a*a - b*b: 1.9999999878450581e-08
(a-b)*(a+b): 1.9999999978450579e-08
log(1 + x): 1.000000082690371e-10
log1p(x): 9.9999999995000007e-11
expm1(x): 1.00000000005e-10
exp(x) - 1: 1.000000082740371e-10
- Verdict: native. C++
doubleis binary64 on common platforms. a*a - b*bsubtracts two rounded products, so the cancellation exposes their errors.(a-b)*(a+b)subtracts exact values first.std::log1pandstd::expm1avoid the cancellation inlog(1 + x)andexp(x) - 1for smallx.
import java.math.BigDecimal;
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("loop: " + total);
System.out.println("new BigDecimal(0.1): " + new BigDecimal(0.1));
System.out.println("BigDecimal.valueOf(0.1): " + BigDecimal.valueOf(0.1));
BigDecimal exact = BigDecimal.ZERO;
BigDecimal tenth = new BigDecimal("0.1");
for (int i = 0; i < 10; i++) {
exact = exact.add(tenth);
}
System.out.println("BigDecimal sum: " + exact);
System.out.println("equals 1.0: " + (exact.compareTo(BigDecimal.ONE) == 0 ? "yes" : "no"));
System.out.println("float 0.1f as double: " + (double) 0.1f);
}
}
loop: 0.9999999999999999
new BigDecimal(0.1): 0.1000000000000000055511151231257827021181583404541015625
BigDecimal.valueOf(0.1): 0.1
BigDecimal sum: 1.0
equals 1.0: yes
float 0.1f as double: 0.10000000149011612
- Verdict: native. Java
doubleis binary64 andfloatis binary32. new BigDecimal(0.1)shows the exact stored value.BigDecimal.valueOf(0.1)goes throughDouble.toString, so it gives0.1.- A
floathas a larger representation error than adouble, as the last line shows.
#include <stdio.h>
int main(void) {
double total = 0.0;
float total_f = 0.0f;
for (int i = 0; i < 1000; i++) {
total += 0.1;
total_f += 0.1f;
}
printf("0.1 exact: %.55f\n", 0.1);
printf("double, 1000 additions: %.17g\n", total);
printf("float, 1000 additions: %.9g\n", (double) total_f);
double sum = 0.0, c = 0.0;
for (int i = 0; i < 1000; i++) {
double y = 0.1 - c;
double t = sum + y;
c = (t - sum) - y;
sum = t;
}
printf("Kahan, 1000 additions: %.17g\n", sum);
double big = 1e16;
printf("1e16 + 1 - 1e16: %g\n", (big + 1.0) - big);
return 0;
}
0.1 exact: 0.1000000000000000055511151231257827021181583404541015625
double, 1000 additions: 99.999999999998593
float, 1000 additions: 99.9990463
Kahan, 1000 additions: 100
1e16 + 1 - 1e16: 0
- Verdict: native. C
doubleis binary64 andfloatis binary32 on common platforms. - After 1000 additions the error of the
floatsum is much larger than the error of thedoublesum. Kahan summation gives 100.
using System;
double total = 0.0;
for (int i = 0; i < 10; i++)
{
total += 0.1;
}
Console.WriteLine($"loop: {total:R}");
Console.WriteLine($"equals 1.0: {(total == 1.0 ? "yes" : "no")}");
Console.WriteLine($"0.1 as G17: {0.1.ToString("G17")}");
decimal exact = 0m;
for (int i = 0; i < 10; i++)
{
exact += 0.1m;
}
Console.WriteLine($"decimal sum: {exact}");
Console.WriteLine($"equals 1: {(exact == 1m ? "yes" : "no")}");
Console.WriteLine($"1m / 3m: {1m / 3m}");
loop: 0.9999999999999999
equals 1.0: no
0.1 as G17: 0.10000000000000001
decimal sum: 1.0
equals 1: yes
1m / 3m: 0.3333333333333333333333333333
- Verdict: native. C#
doubleis binary64. decimalholds 0.1 exactly, so ten additions give 1.0. It still rounds 1/3 to 28 digits.
let total = 0;
for (let i = 0; i < 10; i++) {
total += 0.1;
}
console.log(`loop: ${total}`);
console.log(`0.1 to 25 digits: ${(0.1).toPrecision(25)}`);
console.log(`0.1 + 0.2: ${0.1 + 0.2}`);
function kahanSum(values) {
let sum = 0;
let c = 0;
for (const v of values) {
const y = v - c;
const t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
}
console.log(`Kahan: ${kahanSum(Array(10).fill(0.1))}`);
let cents = 0;
for (let i = 0; i < 10; i++) {
cents += 10;
}
console.log(`cents: ${cents} -> ${(cents / 100).toFixed(2)}`);
console.log(`(1.005).toFixed(2): ${(1.005).toFixed(2)}`);
loop: 0.9999999999999999
0.1 to 25 digits: 0.1000000000000000055511151
0.1 + 0.2: 0.30000000000000004
Kahan: 1
cents: 100 -> 1.00
(1.005).toFixed(2): 1.00
- Verdict: native. Every JavaScript
numberis a binary64 float. toPrecision(25)prints digits past the shortest form, so the error becomes visible.(1.005).toFixed(2)gives"1.00"because the stored value is below 1.005.
package main
import (
"fmt"
"math/big"
)
func main() {
total := 0.0
for i := 0; i < 10; i++ {
total += 0.1
}
fmt.Println("loop:", total)
fmt.Printf("0.1 exact: %.55f\n", 0.1)
a, b := 0.1, 0.2
fmt.Println("variables 0.1 + 0.2:", a+b)
fmt.Println("constants 0.1 + 0.2:", 0.1+0.2)
sum := new(big.Rat)
tenth := big.NewRat(1, 10)
for i := 0; i < 10; i++ {
sum.Add(sum, tenth)
}
fmt.Println("big.Rat sum:", sum.RatString())
}
loop: 0.9999999999999999
0.1 exact: 0.1000000000000000055511151231257827021181583404541015625
variables 0.1 + 0.2: 0.30000000000000004
constants 0.1 + 0.2: 0.3
big.Rat sum: 1
- Verdict: native. Go
float64is binary64. - Go evaluates constant expressions exactly, so the constant
0.1+0.2has no rounding error until it becomes afloat64. The same sum of two variables rounds. big.Ratkeeps one tenth as an exact fraction.
fn main() {
let mut total = 0.0_f64;
for _ in 0..10 {
total += 0.1;
}
println!("loop: {}", total);
println!("0.1 exact: {:.55}", 0.1_f64);
println!("0.1 + 0.2 == 0.3: {}", if 0.1 + 0.2 == 0.3 { "yes" } else { "no" });
let mut sum = 0.0_f64;
let mut c = 0.0_f64;
for _ in 0..10 {
let y = 0.1 - c;
let t = sum + y;
c = (t - sum) - y;
sum = t;
}
println!("Kahan: {}", sum);
let cents: i64 = (0..10).map(|_| 10).sum();
println!("cents: {} -> {}.{:02}", cents, cents / 100, cents % 100);
}
loop: 0.9999999999999999
0.1 exact: 0.1000000000000000055511151231257827021181583404541015625
0.1 + 0.2 == 0.3: no
Kahan: 1
cents: 100 -> 1.00
- Verdict: native. Rust
f64is binary64. {:.55}prints 55 digits after the point, which is the exact value of the stored 0.1.- The program keeps money as integer cents, which add without error.
Variations and related ideas
- Decimal floating point. A decimal type stores base 10 digits, so 0.1 is exact. It still rounds 1/3.7
- Fixed point and integer cents. An amount kept as an integer number of cents adds without error (Fixed-point arithmetic).
- Rational numbers. A fraction type is exact for
+,-,*and/, but its parts can grow (Rational numbers in code). - Arbitrary precision. A float type with more bits makes each error smaller, but it does not remove representation error for 0.1 (Arbitrary-precision arithmetic).
- Truncation error. Numerical analysis counts two kinds of computation error: truncation errors and roundoff errors.2 This page is about the second kind.
- Related pages. Floating-point arithmetic describes the format, the special values and the ulp.
Pitfalls
The printed value hides the error
Python prints the shortest string that reads back as the same float, so 0.1 prints as 0.1. The Python tutorial calls this "in a real sense, an illusion", and it says that other languages "may not display the difference by default".1 Print more digits, or the exact value, when you debug a numeric result.
Rounding the inputs does not help
The nearest float to 0.1 is already as close as a float can be. Rounding it to one decimal gives the same float.1 Round the output for display, and compare with a tolerance.
Rounding twice
A value rounded to two decimals and then to one can differ from the value rounded once. The Round-off error article gives 9.945309: rounded to 9.95 and then to 10.0, the error is 0.054691, and rounded once to 9.9, the error is 0.045309.2 The same thing can happen when a program computes in the x87 80-bit format and stores the result as binary64.2
Errors that grow with time
On February 25, 1991, a Patriot battery at Dhahran failed to intercept a Scud missile, and 28 soldiers were killed.8 The system had run for 100 hours, and its clock "had drifted by one-third of a second", the result of "truncation in a 24-bit fixed-point register".8 The error was small for each tick of the clock, but it grew with the run time. Keep time as an integer count of ticks, and convert it to seconds only at the end.
A float for money
The sum of many prices drifts by a cent now and then. Keep money in a decimal type or in integer cents (Fixed-point arithmetic).
Cost
- Exact types are slower.
decimal.Decimal,BigDecimal,Fractionandbig.Ratwork in software. They are much slower than a float, which is a single hardware instruction for each operation. - Compensated sums. Kahan summation does four float operations for each term instead of one.4 The Python tutorial says that
math.fsumis slower thansum.1 - More digits. A wider float, such as
long double, makes each error smaller, and each value takes more memory.
History
- 1991. David Goldberg's survey explained ulps, relative error, and catastrophic and benign cancellation.3
- 1991. On February 25, a Patriot battery at Dhahran missed a Scud missile because its clock had drifted after 100 hours of running.8
References
- The Python Tutorial, 15. Floating-Point Arithmetic, Issues and Limitations, Python Software Foundation, the opening section, and 15.1 Representation Error
- Round-off error, Wikipedia, the lead, Representation error, Accumulation of roundoff error, and Ill-conditioned problems
- 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 Rounding Error, Relative Error and Ulps, and Cancellation
- Kahan summation algorithm, Wikipedia, the lead, and The algorithm
- BigDecimal (Java SE 27 and JDK 27), Oracle, the constructor BigDecimal(double), API Note
- Decimal Struct, Microsoft Learn, Remarks
- decimal, Decimal fixed-point and floating-point arithmetic, Python Software Foundation, the list of advantages at the top of the page
- MIM-104 Patriot, Wikipedia, Failure at Dhahran
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag JAXVK5 Edit this page History Report an error Markdown