
Rounding or rounding off is the process of adjusting a
number
A number is a mathematical object used to count, measure, and label. The most basic examples are the natural numbers 1, 2, 3, 4, and so forth. Numbers can be represented in language with number words. More universally, individual numbers can ...
to an
approximate
An approximation is anything that is intentionally similar but not exactly equal to something else.
Etymology and usage
The word ''approximation'' is derived from Latin ''approximatus'', from ''proximus'' meaning ''very near'' and the prefix ...
, more convenient value, often with a shorter or simpler representation. For example, replacing $ with $, the
fraction
A fraction (from , "broken") represents a part of a whole or, more generally, any number of equal parts. When spoken in everyday English, a fraction describes how many parts of a certain size there are, for example, one-half, eight-fifths, thre ...
312/937 with 1/3, or the expression √2 with .
Rounding is often done to obtain a value that is easier to report and communicate than the original. Rounding can also be important to avoid
misleadingly precise reporting of a computed number, measurement, or estimate; for example, a quantity that was computed as but is known to be
accurate only to within a few hundred units is usually better stated as "about ".
On the other hand, rounding of exact numbers will introduce some
round-off error
In computing, a roundoff error, also called rounding error, is the difference between the result produced by a given algorithm using exact arithmetic and the result produced by the same algorithm using finite-precision, rounded arithmetic. Roun ...
in the reported result. Rounding is almost unavoidable when reporting many computations – especially when dividing two numbers in
integer
An integer is the number zero (0), a positive natural number (1, 2, 3, ...), or the negation of a positive natural number (−1, −2, −3, ...). The negations or additive inverses of the positive natural numbers are referred to as negative in ...
or
fixed-point arithmetic
In computing, fixed-point is a method of representing fractional (non-integer) numbers by storing a fixed number of digits of their fractional part. Dollar amounts, for example, are often stored with exactly two fractional digits, represen ...
; when computing
mathematical function
In mathematics, a function from a set (mathematics), set to a set assigns to each element of exactly one element of .; the words ''map'', ''mapping'', ''transformation'', ''correspondence'', and ''operator'' are sometimes used synonymously. ...
s such as
square root
In mathematics, a square root of a number is a number such that y^2 = x; in other words, a number whose ''square'' (the result of multiplying the number by itself, or y \cdot y) is . For example, 4 and −4 are square roots of 16 because 4 ...
s,
logarithm
In mathematics, the logarithm of a number is the exponent by which another fixed value, the base, must be raised to produce that number. For example, the logarithm of to base is , because is to the rd power: . More generally, if , the ...
s, and
sine
In mathematics, sine and cosine are trigonometric functions of an angle. The sine and cosine of an acute angle are defined in the context of a right triangle: for the specified angle, its sine is the ratio of the length of the side opposite th ...
s; or when using a
floating-point
In computing, floating-point arithmetic (FP) is arithmetic on subsets of real numbers formed by a ''significand'' (a Sign (mathematics), signed sequence of a fixed number of digits in some Radix, base) multiplied by an integer power of that ba ...
representation with a fixed number of
significant digits
Significant figures, also referred to as significant digits, are specific digits within a number that is written in positional notation that carry both reliability and necessity in conveying a particular quantity. When presenting the outcom ...
. In a sequence of calculations, these rounding errors generally
accumulate, and in certain
ill-conditioned
In numerical analysis, the condition number of a function measures how much the output value of the function can change for a small change in the input argument. This is used to measure how sensitive a function is to changes or errors in the inpu ...
cases they may make the result meaningless.
Accurate rounding of
transcendental mathematical functions is difficult because the number of extra digits that need to be calculated to resolve whether to round up or down cannot be known in advance. This problem is known as "
the table-maker's dilemma".
Rounding has many similarities to the
quantization that occurs when
physical quantities
A physical quantity (or simply quantity) is a property of a material or system that can be quantified by measurement. A physical quantity can be expressed as a ''value'', which is the algebraic multiplication of a '' numerical value'' and a '' ...
must be encoded by numbers or
digital signals
A digital signal is a signal that represents data as a sequence of discrete space, discrete values; at any given time it can only take on, at most, one of a finite number of values. This contrasts with an analog signal, which represents contin ...
.
A
wavy equals sign (
≈, ''approximately equal to'') is sometimes used to indicate rounding of exact numbers, e.g. 9.98 ≈ 10. This sign was introduced by
Alfred George Greenhill
Sir Alfred George Greenhill (29 November 1847 in London – 10 February 1927 in London), was a British mathematician.
George Greenhill was educated at Christ's Hospital School and from there he went to St John's College, Cambridge in 1866. In ...
in 1892.
Ideal characteristics of rounding methods include:
# Rounding should be done by a
function. This way, when the same input is rounded in different instances, the output is unchanged.
# Calculations done with rounding should be close to those done without rounding.
#* As a result of (1) and (2), the output from rounding should be close to its input, often as close as possible by some
metric
Metric or metrical may refer to:
Measuring
* Metric system, an internationally adopted decimal system of measurement
* An adjective indicating relation to measurement in general, or a noun describing a specific type of measurement
Mathematics
...
.
# To be considered rounding, the
range
Range may refer to:
Geography
* Range (geographic), a chain of hills or mountains; a somewhat linear, complex mountainous or hilly area (cordillera, sierra)
** Mountain range, a group of mountains bordered by lowlands
* Range, a term used to i ...
will be a
subset
In mathematics, a Set (mathematics), set ''A'' is a subset of a set ''B'' if all Element (mathematics), elements of ''A'' are also elements of ''B''; ''B'' is then a superset of ''A''. It is possible for ''A'' and ''B'' to be equal; if they a ...
of the
domain, often
discrete
Discrete may refer to:
*Discrete particle or quantum in physics, for example in quantum theory
* Discrete device, an electronic component with just one circuit element, either passive or active, other than an integrated circuit
* Discrete group, ...
. A classical range is the integers,
Z.
# Rounding should preserve
symmetries that already exist between the domain and range. With finite precision (or a discrete domain), this translates to removing
bias
Bias is a disproportionate weight ''in favor of'' or ''against'' an idea or thing, usually in a way that is inaccurate, closed-minded, prejudicial, or unfair. Biases can be innate or learned. People may develop biases for or against an individ ...
.
# A rounding method should have utility in computer science or human arithmetic where finite precision is used, and speed is a consideration.
Because it is not usually possible for a method to satisfy all ideal characteristics, many different rounding methods exist.
As a general rule, rounding is
idempotent
Idempotence (, ) is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. The concept of idempotence arises in a number of pl ...
; i.e., once a number has been rounded, rounding it again to the same precision will not change its value. Rounding functions are also
monotonic
In mathematics, a monotonic function (or monotone function) is a function between ordered sets that preserves or reverses the given order. This concept first arose in calculus, and was later generalized to the more abstract setting of ord ...
; i.e., rounding two numbers to the same absolute precision will not exchange their
order
Order, ORDER or Orders may refer to:
* A socio-political or established or existing order, e.g. World order, Ancien Regime, Pax Britannica
* Categorization, the process in which ideas and objects are recognized, differentiated, and understood
...
(but may give the same value). In the general case of a discrete range, they are
piecewise constant function
In mathematics, a function on the real numbers is called a step function if it can be written as a finite linear combination of indicator functions of intervals. Informally speaking, a step function is a piecewise constant function having only ...
s.
Types of rounding
Typical rounding problems include:
Rounding to integer
The most basic form of rounding is to replace an arbitrary number by an integer. All the following rounding modes are concrete implementations of an abstract single-argument "round()" procedure. These are true functions (with the exception of those that use randomness).
Directed rounding to an integer
These four methods are called directed rounding to an integer, as the displacements from the original number to the rounded value are all directed toward or away from the same limiting value (0,
+∞, or −∞). Directed rounding is used in
interval arithmetic
Interval arithmetic (also known as interval mathematics; interval analysis or interval computation) is a mathematical technique used to mitigate rounding and measurement errors in mathematical computation by computing function bounds. Numeri ...
and is often required in financial calculations.
If is positive, round-down is the same as round-toward-zero, and round-up is the same as round-away-from-zero. If is negative, round-down is the same as round-away-from-zero, and round-up is the same as round-toward-zero. In any case, if is an integer, is just .
Where many calculations are done in sequence, the choice of rounding method can have a very significant effect on the result. A famous instance involved a new
index
Index (: indexes or indices) may refer to:
Arts, entertainment, and media Fictional entities
* Index (''A Certain Magical Index''), a character in the light novel series ''A Certain Magical Index''
* The Index, an item on the Halo Array in the ...
set up by the
Vancouver Stock Exchange in 1982. It was initially set at 1000.000 (three decimal places of accuracy), and after 22 months had fallen to about 520, although the market appeared to be rising. The problem was caused by the index being recalculated thousands of times daily, and always being truncated (rounded down) to 3 decimal places, in such a way that the rounding errors accumulated. Recalculating the index for the same period using rounding to the nearest thousandth rather than truncation corrected the index value from 524.811 up to 1098.892.
For the examples below, refers to the
sign function
In mathematics, the sign function or signum function (from '' signum'', Latin for "sign") is a function that has the value , or according to whether the sign of a given real number is positive or negative, or the given number is itself zer ...
applied to the original number, .
Rounding down
One may round down (or take the
floor
A floor is the bottom surface of a room or vehicle. Floors vary from wikt:hovel, simple dirt in a cave to many layered surfaces made with modern technology. Floors may be stone, wood, bamboo, metal or any other material that can support the ex ...
, or round toward negative infinity): is the largest integer that does not exceed .
:
For example, 23.7 gets rounded to 23, and −23.2 gets rounded to −24.
Rounding up
One may also round up (or take the
ceiling
A ceiling is an overhead interior roof that covers the upper limits of a room. It is not generally considered a structural element, but a finished surface concealing the underside of the roof structure or the floor of a story above. Ceilings can ...
, or round toward positive infinity): is the smallest integer that is not less than .
:
For example, 23.2 gets rounded to 24, and −23.7 gets rounded to −23.
Rounding toward zero
One may also round toward zero (or
truncate, or round away from infinity): is the integer that is closest to such that it is between 0 and (included); i.e. is the integer part of , without its fraction digits.
:
For example, 23.7 gets rounded to 23, and −23.7 gets rounded to −23.
Rounding away from zero
One may also round away from zero (or round toward infinity): is the integer that is closest to 0 (or equivalently, to ) such that is between 0 and (included).
:
For example, 23.2 gets rounded to 24, and −23.2 gets rounded to −24.
Rounding to the nearest integer
These six methods are called rounding to the nearest integer. Rounding a number to the nearest integer requires some tie-breaking rule for those cases when is exactly half-way between two integers – that is, when the fraction part of is exactly 0.5.
If it were not for the 0.5 fractional parts, the round-off errors introduced by the round to nearest method would be symmetric: for every fraction that gets rounded down (such as 0.268), there is a complementary fraction (namely, 0.732) that gets rounded up by the same amount.
When rounding a large set of
fixed-point numbers with
uniformly distributed fractional parts, the rounding errors by all values, with the omission of those having 0.5 fractional part, would statistically compensate each other. This means that the
expected (average) value of the rounded numbers is equal to the expected value of the original numbers when numbers with fractional part 0.5 from the set are removed.
In practice,
floating-point
In computing, floating-point arithmetic (FP) is arithmetic on subsets of real numbers formed by a ''significand'' (a Sign (mathematics), signed sequence of a fixed number of digits in some Radix, base) multiplied by an integer power of that ba ...
numbers are typically used, which have even more computational nuances because they are not equally spaced.
Rounding half up
One may round half up (or round half toward positive infinity), a tie-breaking rule that is widely used in many disciplines. That is, half-way values of are always rounded up. If the fractional part of is exactly 0.5, then
:
For example, 23.5 gets rounded to 24, and −23.5 gets rounded to −23.
Some programming languages (such as Java and Python) use "half up" to refer to ''
round half away from zero'' rather than ''round half toward positive infinity''.
This method only requires checking one digit to determine rounding direction in
two's complement
Two's complement is the most common method of representing signed (positive, negative, and zero) integers on computers, and more generally, fixed point binary values. Two's complement uses the binary digit with the ''greatest'' value as the ''s ...
and similar representations.
Rounding half down
One may also round half down (or round half toward negative infinity) as opposed to the more common ''round half up''. If the fractional part of is exactly 0.5, then
:
For example, 23.5 gets rounded to 23, and −23.5 gets rounded to −24.
Some programming languages (such as Java and Python) use "half down" to refer to ''
round half toward zero'' rather than ''round half toward negative infinity''.
Rounding half toward zero
One may also round half toward zero (or round half away from infinity) as opposed to the conventional ''round half away from zero''. If the fractional part of is exactly 0.5, then if is positive, and if is negative.
:
For example, 23.5 gets rounded to 23, and −23.5 gets rounded to −23.
This method treats positive and negative values symmetrically, and therefore is free of overall positive/negative bias if the original numbers are positive or negative with equal probability. It does, however, still have bias toward zero.
Rounding half away from zero
One may also round half away from zero (or round half toward infinity), a tie-breaking rule that is commonly taught and used, namely: If the fractional part of is exactly 0.5, then if is positive, and if is negative.
:
For example, 23.5 gets rounded to 24, and −23.5 gets rounded to −24.
This can be more efficient on computers that use
sign-magnitude
In computing, signed number representations are required to encode negative numbers in binary number systems.
In mathematics, negative numbers in any base are represented by prefixing them with a minus sign ("−"). However, in RAM or CPU reg ...
representation for the values to be rounded, because only the first omitted digit needs to be considered to determine if it rounds up or down. This is one method used when rounding to
significant figures
Significant figures, also referred to as significant digits, are specific digits within a number that is written in positional notation that carry both reliability and necessity in conveying a particular quantity. When presenting the outcom ...
due to its simplicity.
This method, also known as commercial rounding, treats positive and negative values symmetrically, and therefore is free of overall positive/negative bias if the original numbers are positive or negative with equal probability. It does, however, still have bias away from zero.
It is often used for currency conversions and price roundings (when the amount is first converted into the smallest significant subdivision of the currency, such as cents of a euro) as it is easy to explain by just considering the first fractional digit, independently of supplementary precision digits or sign of the amount (for strict equivalence between the paying and recipient of the amount).
Rounding half to even
One may also round half to even, a tie-breaking rule without positive/negative bias ''and'' without bias toward/away from zero. By this convention, if the fractional part of is 0.5, then is the even integer nearest to . Thus, for example, 23.5 becomes 24, as does 24.5; however, −23.5 becomes −24, as does −24.5. This function minimizes the expected error when summing over rounded figures, even when the inputs are mostly positive or mostly negative, provided they are neither mostly even nor mostly odd.
This variant of the round-to-nearest method is also called convergent rounding, statistician's rounding, Dutch rounding, Gaussian rounding, odd–even rounding, or bankers' rounding.
This is the default rounding mode used in
IEEE 754
The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point arithmetic originally established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard #Design rationale, add ...
operations for results in binary floating-point formats.
By eliminating bias, repeated addition or subtraction of independent numbers, as in a
one-dimensional random walk, will give a rounded result with an error that tends to grow in proportion to the square root of the number of operations rather than linearly.
However, this rule distorts the distribution by increasing the probability of evens relative to odds. Typically this is less important than the biases that are eliminated by this method.
Rounding half to odd
One may also round half to odd, a similar tie-breaking rule to round half to even. In this approach, if the fractional part of is 0.5, then is the odd integer nearest to . Thus, for example, 23.5 becomes 23, as does 22.5; while −23.5 becomes −23, as does −22.5.
This method is also free from positive/negative bias and bias toward/away from zero, provided the numbers to be rounded are neither mostly even nor mostly odd. It also shares the round half to even property of distorting the original distribution, as it increases the probability of odds relative to evens. It was the method used for bank balances in the
United Kingdom
The United Kingdom of Great Britain and Northern Ireland, commonly known as the United Kingdom (UK) or Britain, is a country in Northwestern Europe, off the coast of European mainland, the continental mainland. It comprises England, Scotlan ...
when it decimalized its currency.
This variant is almost never used in computations, except in situations where one wants to avoid increasing the scale of floating-point numbers, which have a limited exponent range. With ''round half to even'', a non-infinite number would round to infinity, and a small value would round to a normal non-zero value. Effectively, this mode prefers preserving the existing scale of tie numbers, avoiding out-of-range results when possible for numeral systems of even
radix
In a positional numeral system, the radix (radices) or base is the number of unique digits, including the digit zero, used to represent numbers. For example, for the decimal system (the most common system in use today) the radix is ten, becaus ...
(such as binary and decimal)..
Rounding to prepare for shorter precision
This rounding mode is used to avoid getting a potentially wrong result after
multiple roundings. This can be achieved if all roundings except the final one are done using rounding to prepare for shorter precision ("RPSP"), and only the final rounding uses the externally requested mode.
With decimal arithmetic, final digits of 0 and 5 are avoided; if there is a choice between numbers with the least significant digit 0 or 1, 4 or 5, 5 or 6, 9 or 0, then the digit different from 0 or 5 shall be selected; otherwise, the choice is arbitrary. IBM defines that, in the latter case, a digit with the smaller magnitude shall be selected. RPSP can be applied with the step between two consequent roundings as small as a single digit (for example, rounding to 1/10 can be applied after rounding to 1/100).
For example, when rounding to integer,
* 20.0 is rounded to 20;
* 20.01, 20.1, 20.9, 20.99, 21, 21.01, 21.9, 21.99 are rounded to 21 (avoiding a final 0);
* 22.0, 22.1, 22.9, 22.99 are rounded to 22;
* 24.0, 24.1, 24.9, 24.99 are rounded to 24 (avoiding a final 5);
* 25.0 is rounded to 25;
* 25.01, 25.1 are rounded to 26 (avoiding a final 5).
In the example from "
Double rounding" section, rounding 9.46 to one decimal gives 9.4, which rounding to integer in turn gives 9.
With binary arithmetic, this rounding is also called "round to odd" (not to be confused with "
round half to odd"). For example, when rounding to 1/4 (0.01 in binary),
* ⇒ result is 2 (10.00 in binary)
* ⇒ result is 2.25 (10.01 in binary)
* ⇒ result is 2.5 (10.10 in binary)
* ⇒ result is 2.75 (10.11 in binary)
* ⇒ result is 3 (11.00 in binary)
For correct results with binary arithmetic, each rounding step must remove at least 2 binary digits, otherwise, wrong results may appear. For example,
* 3.125 RPSP to 1/4 ⇒ result is 3.25
* 3.25 RPSP to 1/2 ⇒ result is 3.5
* 3.5 round-half-to-even to 1 ⇒ result is 4 (wrong)
If the erroneous middle step is removed, the final rounding to integer rounds 3.25 to the correct value of 3.
RPSP is implemented in hardware in IBM
zSeries
IBM Z is a family name used by IBM for all of its z/Architecture mainframe computers.
In July 2017, with another generation of products, the official family was changed to IBM Z from IBM z Systems; the IBM Z family will soon include the newes ...
and
pSeries. In
Python module "Decimal",
Tcl module "math",
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
package "decimal-arithmetic", and possibly others, this mode is called ROUND_05UP or round05up.
Randomized rounding to an integer
Alternating tie-breaking
One method, more obscure than most, is to alternate direction when rounding a number with 0.5 fractional part. All others are rounded to the closest integer. Whenever the fractional part is 0.5, alternate rounding up or down: for the first occurrence of a 0.5 fractional part, round up, for the second occurrence, round down, and so on. Alternatively, the first 0.5 fractional part rounding can be determined by a
random seed
A random seed (or seed state, or just seed) is a number (or vector) used to initialize a pseudorandom number generator.
A pseudorandom number generator's number sequence is completely determined by the seed: thus, if a pseudorandom number gener ...
. "Up" and "down" can be any two rounding methods that oppose each other - toward and away from positive infinity or toward and away from zero.
If occurrences of 0.5 fractional parts occur significantly more than a restart of the occurrence "counting", then it is effectively bias free. With guaranteed zero bias, it is useful if the numbers are to be summed or averaged.
Random tie-breaking
If the fractional part of is 0.5, choose randomly between and , with equal probability. All others are rounded to the closest integer.
Like round-half-to-even and round-half-to-odd, this rule is essentially free of overall bias, but it is also fair among even and odd values. An advantage over alternate tie-breaking is that the last direction of rounding on the 0.5 fractional part does not have to be "remembered".
Stochastic rounding
Rounding as follows to one of the closest integer toward negative infinity and the closest integer toward positive infinity, with a probability dependent on the proximity is called
stochastic Stochastic (; ) is the property of being well-described by a random probability distribution. ''Stochasticity'' and ''randomness'' are technically distinct concepts: the former refers to a modeling approach, while the latter describes phenomena; i ...
rounding and will give an unbiased result on average.
:
For example, 1.6 would be rounded to 1 with probability 0.4 and to 2 with probability 0.6.
Stochastic rounding can be accurate in a way that a rounding
function can never be. For example, suppose one started with 0 and added 0.3 to that one hundred times while rounding the running total between every addition. The result would be 0 with regular rounding, but with stochastic rounding, the expected result would be 30, which is the same value obtained without rounding. This can be useful in
machine learning
Machine learning (ML) is a field of study in artificial intelligence concerned with the development and study of Computational statistics, statistical algorithms that can learn from data and generalise to unseen data, and thus perform Task ( ...
where the training may use low precision arithmetic iteratively.
Stochastic rounding is also a way to achieve 1-dimensional
dithering.
Comparison of approaches for rounding to an integer
Rounding to other values
Rounding to a specified multiple
The most common type of rounding is to round to an integer; or, more generally, to an integer multiple of some increment – such as rounding to whole tenths of seconds, hundredths of a dollar, to whole multiples of 1/2 or 1/8 inch, to whole dozens or thousands, etc.
In general, rounding a number to a multiple of some specified positive value entails the following steps:
:
For example, rounding dollars to whole cents (i.e., to a multiple of 0.01) entails computing , then rounding that to 218, and finally computing .
When rounding to a predetermined number of
significant digits
Significant figures, also referred to as significant digits, are specific digits within a number that is written in positional notation that carry both reliability and necessity in conveying a particular quantity. When presenting the outcom ...
, the increment depends on the magnitude of the number to be rounded (or of the rounded result).
The increment is normally a finite fraction in whatever
numeral system
A numeral system is a writing system for expressing numbers; that is, a mathematical notation for representing numbers of a given set, using digits or other symbols in a consistent manner.
The same sequence of symbols may represent differe ...
is used to represent the numbers. For display to humans, that usually means the
decimal numeral system (that is, is an integer times a
power of 10, like 1/1000 or 25/100). For intermediate values stored in digital computers, it often means the
binary numeral system
A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method for representing numbers that uses only two symbols for the natural numbers: typically "0" ( zero) and "1" ( one). A ''binary number'' may als ...
( is an integer times a power of 2).
The abstract single-argument "round()" function that returns an integer from an arbitrary real value has at least a dozen distinct concrete definitions presented in the
rounding to integer section. The abstract two-argument "roundToMultiple()" function is formally defined here, but in many cases it is used with the implicit value for the increment and then reduces to the equivalent abstract single-argument function, with also the same dozen distinct concrete definitions.
Logarithmic rounding
Rounding to a specified power
Rounding to a specified ''power'' is very different from rounding to a specified ''multiple''; for example, it is common in computing to need to round a number to a whole power of 2. The steps, in general, to round a positive number to a power of some positive number other than 1, are:
:
Many of the caveats applicable to rounding to a multiple are applicable to rounding to a power.
In the
chromatic "twelve-tone" scale of music, is rounded to (a
fifth), is rounded to (a
fourth), is rounded to (a
major third
In music theory, a third is a Interval (music), musical interval encompassing three staff positions (see Interval (music)#Number, Interval number for more details), and the major third () is a third spanning four Semitone, half steps or two ...
), is rounded to (a
minor third
In music theory, a minor third is a interval (music), musical interval that encompasses three half steps, or semitones. Staff notation represents the minor third as encompassing three staff positions (see: interval (music)#Number, interval numb ...
), and is rounded to (a
diminished third).
Scaled rounding
This type of rounding, which is also named rounding to a logarithmic scale, is a variant of
rounding to a specified power. Rounding on a logarithmic scale is accomplished by taking the log of the amount and doing normal rounding to the nearest value on the log scale.
For example, resistors are supplied with
preferred numbers on a logarithmic scale. In particular, for resistors with a 10% accuracy, they are supplied with nominal values 100, 120, 150, 180, 220, etc. rounded to multiples of 10 (
E12 series). If a calculation indicates a resistor of 165 ohms is required then , and . The logarithm of 165 is closer to the logarithm of 180 therefore a 180 ohm resistor would be the first choice if there are no other considerations.
Whether a value rounds to or depends upon whether the squared value is greater than or less than the product . The value 165 rounds to 180 in the resistors example because is greater than .
Floating-point rounding
In
floating-point arithmetic
In computing, floating-point arithmetic (FP) is arithmetic on subsets of real numbers formed by a ''significand'' (a Sign (mathematics), signed sequence of a fixed number of digits in some Radix, base) multiplied by an integer power of that ba ...
, rounding aims to turn a given value into a value with a specified number of digits. In other words, should be a multiple of a number that depends on the magnitude of . The number is a power of the
base (usually 2 or 10) of the floating-point representation.
Apart from this detail, all the variants of rounding discussed above apply to the rounding of floating-point numbers as well. The algorithm for such rounding is presented in the
Scaled rounding section above, but with a constant scaling factor , and an integer base .
Where the rounded result would overflow the result for a directed rounding is either the appropriate signed infinity when "rounding away from zero", or the highest representable positive finite number (or the lowest representable negative finite number if is negative), when "rounding toward zero". The result of an overflow for the usual case of ''round to nearest'' is always the appropriate infinity.
Rounding to a simple fraction
In some contexts it is desirable to round a given number to a "neat" fraction – that is, the nearest fraction whose numerator and denominator do not exceed a given maximum. This problem is fairly distinct from that of rounding a value to a fixed number of decimal or binary digits, or to a multiple of a given unit . This problem is related to
Farey sequence
In mathematics, the Farey sequence of order ''n'' is the sequence of completely reduced fractions, either between 0 and 1, or without this restriction, which have denominators less than or equal to ''n'', arranged in order of increasing size.
Wi ...
s, the
Stern–Brocot tree
In number theory, the Stern–Brocot tree is an infinite complete binary tree in which the vertices correspond one-for-one to the positive rational numbers, whose values are ordered from the left to the right as in a binary search tree.
The ...
, and
continued fraction
A continued fraction is a mathematical expression that can be written as a fraction with a denominator that is a sum that contains another simple or continued fraction. Depending on whether this iteration terminates with a simple fraction or not, ...
s.
Rounding to an available value
Finished
lumber
Lumber is wood that has been processed into uniform and useful sizes (dimensional lumber), including beams and planks or boards. Lumber is mainly used for construction framing, as well as finishing (floors, wall panels, window frames). ...
, writing paper, electronic components, and many other products are usually sold in only a few standard values.
Many design procedures describe how to calculate an approximate value, and then "round" to some standard size using phrases such as "round down to nearest standard value", "round up to nearest standard value", or "round to nearest standard value".
When a set of
preferred values is equally spaced on a logarithmic scale, choosing the closest
preferred value to any given value can be seen as a form of
scaled rounding. Such rounded values can be directly calculated.
Arbitrary bins
More general rounding rules can separate values at arbitrary break points, used for example in
data binning. A related mathematically formalized tool is
signpost sequences, which use notions of distance other than the simple difference – for example, a sequence may round to the integer with the smallest ''relative'' (percent) error.
Rounding in other contexts
Dithering and error diffusion
When digitizing
continuous signal
In mathematical dynamics, discrete time and continuous time are two alternative frameworks within which variables that evolve over time are modeled.
Discrete time
Discrete time views values of variables as occurring at distinct, separate "poi ...
s, such as sound waves, the overall effect of a number of measurements is more important than the accuracy of each individual measurement. In these circumstances,
dithering, and a related technique,
error diffusion, are normally used. A related technique called
pulse-width modulation
Pulse-width modulation (PWM), also known as pulse-duration modulation (PDM) or pulse-length modulation (PLM), is any method of representing a signal as a rectangular wave with a varying duty cycle (and for some methods also a varying peri ...
is used to achieve analog type output from an inertial device by rapidly pulsing the power with a variable duty cycle.
Error diffusion tries to ensure the error, on average, is minimized. When dealing with a gentle slope from one to zero, the output would be zero for the first few terms until the sum of the error and the current value becomes greater than 0.5, in which case a 1 is output and the difference subtracted from the error so far.
Floyd–Steinberg dithering is a popular error diffusion procedure when digitizing images.
As a one-dimensional example, suppose the numbers , , , and occur in order and each is to be rounded to a multiple of . In this case the cumulative sums, , , , and , are each rounded to a multiple of : , , , and . The first of these and the differences of adjacent values give the desired rounded values: , , , and .
Monte Carlo arithmetic
Monte Carlo arithmetic is a technique in
Monte Carlo method
Monte Carlo methods, or Monte Carlo experiments, are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical results. The underlying concept is to use randomness to solve problems that might be ...
s where the rounding is randomly up or down. Stochastic rounding can be used for Monte Carlo arithmetic, but in general, just rounding up or down with equal probability is more often used. Repeated runs will give a random distribution of results which can indicate the stability of the computation.
Exact computation with rounded arithmetic
It is possible to use rounded arithmetic to evaluate the exact value of a function with integer domain and range. For example, if an integer is known to be a perfect square, its square root can be computed by converting to a floating-point value , computing the approximate square root of with floating point, and then rounding to the nearest integer . If is not too big, the floating-point round-off error in will be less than 0.5, so the rounded value will be the exact square root of . This is essentially why
slide rule
A slide rule is a hand-operated mechanical calculator consisting of slidable rulers for conducting mathematical operations such as multiplication, division, exponents, roots, logarithms, and trigonometry. It is one of the simplest analog ...
s could be used for exact arithmetic.
Double rounding
Rounding a number twice in succession to different levels of precision, with the latter precision being coarser, is not guaranteed to give the same result as rounding once to the final precision except in the case of directed rounding.
For instance rounding 9.46 to one decimal gives 9.5, and then 10 when rounding to integer using rounding half to even, but would give 9 when rounded to integer directly. Borman and Chatfield discuss the implications of double rounding when comparing data rounded to one decimal place to specification limits expressed using integers.
In ''Martinez v. Allstate'' and ''Sendejo v. Farmers'', litigated between 1995 and 1997, the insurance companies argued that double rounding premiums was permissible and in fact required. The US courts ruled against the insurance companies and ordered them to adopt rules to ensure single rounding.
Some computer languages and the
IEEE 754-2008
The Institute of Electrical and Electronics Engineers (IEEE) is an American 501(c)(3) public charity professional organization for electrical engineering, electronics engineering, and other related disciplines.
The IEEE has a corporate office ...
standard dictate that in straightforward calculations the result should not be rounded twice. This has been a particular problem with Java as it is designed to be run identically on different machines, special programming tricks have had to be used to achieve this with
x87 floating point. The Java language was changed to allow different results where the difference does not matter and require a
strictfp qualifier to be used when the results have to conform accurately; strict floating point has been restored in Java 17.
In some algorithms, an intermediate result is computed in a larger precision, then must be rounded to the final precision. Double rounding can be avoided by choosing an adequate rounding for the intermediate computation. This consists in avoiding to round to midpoints for the final rounding (except when the midpoint is exact). In binary arithmetic, the idea is to round the result toward zero, and set the least significant bit to 1 if the rounded result is inexact; this rounding is called ''sticky rounding''. Equivalently, it consists in returning the intermediate result when it is exactly representable, and the nearest floating-point number with an odd significand otherwise; this is why it is also known as ''rounding to odd''. A concrete implementation of this approach, for binary and decimal arithmetic, is implemented as
Rounding to prepare for shorter precision.
Table-maker's dilemma
William M. Kahan coined the term "The Table-Maker's Dilemma" for the unknown cost of rounding
transcendental function
In mathematics, a transcendental function is an analytic function that does not satisfy a polynomial equation whose coefficients are functions of the independent variable that can be written using only the basic operations of addition, subtraction ...
s:
The
IEEE 754
The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point arithmetic originally established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard #Design rationale, add ...
floating-point standard guarantees that add, subtract, multiply, divide,
fused multiply–add, square root, and floating-point remainder will give the correctly rounded result of the infinite-precision operation. No such guarantee was given in the 1985 standard for more complex functions and they are typically only accurate to within the last bit at best. However, the 2008 standard guarantees that conforming implementations will give correctly rounded results which respect the active rounding mode; implementation of the functions, however, is optional.
Using the
Gelfond–Schneider theorem and
Lindemann–Weierstrass theorem
In transcendental number theory, the Lindemann–Weierstrass theorem is a result that is very useful in establishing the transcendence of numbers. It states the following:
In other words, the extension field \mathbb(e^, \dots, e^) has transc ...
, many of the standard elementary functions can be proved to return
transcendental results, except on some well-known arguments; therefore, from a theoretical point of view, it is always possible to correctly round such functions. However, for an implementation of such a function, determining a limit for a given precision on how accurate results need to be computed, before a correctly rounded result can be guaranteed, may demand a lot of computation time or may be out of reach.
In practice, when this limit is not known (or only a very large bound is known), some decision has to be made in the implementation (see below); but according to a probabilistic model, correct rounding can be satisfied with a very high probability when using an intermediate accuracy of up to twice the number of digits of the target format plus some small constant (after taking special cases into account).
Some programming packages offer correct rounding. The
GNU MPFR package gives correctly rounded arbitrary precision results. Some other libraries implement elementary functions with correct rounding in
IEEE 754 double precision (binary64):
*
IBM
International Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American Multinational corporation, multinational technology company headquartered in Armonk, New York, and present in over 175 countries. It is ...
's ''ml4j'', which stands for ''Mathematical Library for Java'', written by
Abraham Ziv and Moshe Olshansky in 1999, correctly rounded to nearest only. This library was claimed to be portable, but only binaries for
PowerPC
PowerPC (with the backronym Performance Optimization With Enhanced RISC – Performance Computing, sometimes abbreviated as PPC) is a reduced instruction set computer (RISC) instruction set architecture (ISA) created by the 1991 Apple Inc., App ...
/
AIX,
SPARC/
Solaris and
x86
x86 (also known as 80x86 or the 8086 family) is a family of complex instruction set computer (CISC) instruction set architectures initially developed by Intel, based on the 8086 microprocessor and its 8-bit-external-bus variant, the 8088. Th ...
/
Windows NT
Windows NT is a Proprietary software, proprietary Graphical user interface, graphical operating system produced by Microsoft as part of its Windows product line, the first version of which, Windows NT 3.1, was released on July 27, 1993. Original ...
were provided. According to its documentation, this library uses a first step with an accuracy a bit larger than double precision, a second step based on
double-double arithmetic, and a third step with a 768-bit precision based on arrays of IEEE 754 double-precision floating-point numbers.
* IBM's ''Accurate portable mathematical library'' (abbreviated as APMathLib or just MathLib), also called libultim, in rounding to nearest only. This library uses up to 768 bits of working precision. It was included in the
GNU C Library
The GNU C Library, commonly known as glibc, is the GNU Project implementation of the C standard library. It provides a wrapper around the system calls of the Linux kernel and other kernels for application use. Despite its name, it now also dir ...
in 2001, but the "slow paths" (providing correct rounding) were removed from 2018 to 2021.
* CRlibm, written in the old Arénaire team (LIP,
ENS Lyon), first distributed in 2003. It supports the 4 rounding modes and is proved, using the knowledge of the hardest-to-round cases. More efficient than IBM MathLib.
[ Succeeded by Metalibm (2014), which automates the formal proofs.
* ]Sun Microsystems
Sun Microsystems, Inc., often known as Sun for short, was an American technology company that existed from 1982 to 2010 which developed and sold computers, computer components, software, and information technology services. Sun contributed sig ...
's libmcr of 2004, in the 4 rounding modes. For the difficult cases, this library also uses multiple precision, and the number of words is increased by 2 each time the Table-maker's dilemma occurs (with undefined behavior in the very unlikely event that some limit of the machine is reached).
* The CORE-MATH project (2022) provides some correctly rounded functions in the 4 rounding modes for x86-64
x86-64 (also known as x64, x86_64, AMD64, and Intel 64) is a 64-bit extension of the x86 instruction set architecture, instruction set. It was announced in 1999 and first available in the AMD Opteron family in 2003. It introduces two new ope ...
processors. Proved using the knowledge of the hardest-to-round cases.
* LLVM
LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
libc provides some correctly rounded functions in the 4 rounding modes.
There exist computable numbers for which a rounded value can never be determined no matter how many digits are calculated. Specific instances cannot be given but this follows from the undecidability of the halting problem
In computability theory (computer science), computability theory, the halting problem is the problem of determining, from a description of an arbitrary computer program and an input, whether the program will finish running, or continue to run for ...
. For instance, if Goldbach's conjecture
Goldbach's conjecture is one of the oldest and best-known list of unsolved problems in mathematics, unsolved problems in number theory and all of mathematics. It states that every even and odd numbers, even natural number greater than 2 is the ...
is true but unprovable, then the result of rounding the following value, , up to the next integer cannot be determined: either =1+10− where is the first even number greater than 4 which is not the sum of two primes, or =1 if there is no such number. The rounded result is 2 if such a number exists and 1 otherwise. The value before rounding can however be approximated to any given precision even if the conjecture is unprovable.
Interaction with string searches
Rounding can adversely affect a string search for a number. For example, rounded to four digits is "3.1416" but a simple search for this string will not discover "3.14159" or any other value of rounded to more than four digits. In contrast, truncation does not suffer from this problem; for example, a simple string search for "3.1415", which is truncated to four digits, will discover values of truncated to more than four digits.
History
The concept of rounding is very old, perhaps older than the concept of division itself. Some ancient clay tablet
In the Ancient Near East, clay tablets (Akkadian language, Akkadian ) were used as a writing medium, especially for writing in cuneiform, throughout the Bronze Age and well into the Iron Age.
Cuneiform characters were imprinted on a wet clay t ...
s found in Mesopotamia
Mesopotamia is a historical region of West Asia situated within the Tigris–Euphrates river system, in the northern part of the Fertile Crescent. Today, Mesopotamia is known as present-day Iraq and forms the eastern geographic boundary of ...
contain tables with rounded values of reciprocals and square roots in base 60.
Rounded approximations to , the length of the year, and the length of the month are also ancient – see base 60 examples.
The ''round-half-to-even'' method has served as American Standard Z25.1 and ASTM
ASTM International, formerly known as American Society for Testing and Materials, is a standards organization that develops and publishes voluntary consensus technical international standards for a wide range of materials, products, systems and s ...
standard E-29 since 1940. The origin of the terms ''unbiased rounding'' and ''statistician's rounding'' are fairly self-explanatory. In the 1906 fourth edition of ''Probability and Theory of Errors'' Robert Simpson Woodward
Robert Simpson Woodward (July 21, 1849 – June 29, 1924) was an American civil engineer, physicist and mathematician.
Biography
He was born at Rochester, Michigan, on July 21, 1849, to Lysander Woodward and Peninah A. Simpson. called this "the computer's rule", indicating that it was then in common use by human computer
The term "computer", in use from the early 17th century (the first known written reference dates from 1613), meant "one who computes": a person performing mathematical calculations, before electronic calculators became available. Alan Turing ...
s who calculated mathematical tables. For example, it was recommended in Simon Newcomb
Simon Newcomb (March 12, 1835 – July 11, 1909) was a Canadians, Canadian–Americans, American astronomer, applied mathematician, and autodidactic polymath. He served as Professor of Mathematics in the United States Navy and at Johns Hopkins ...
's c. 1882 book ''Logarithmic and Other Mathematical Tables''. Lucius Tuttle's 1916 ''Theory of Measurements'' called it a "universally adopted rule" for recording physical measurements. Churchill Eisenhart indicated the practice was already "well established" in data analysis by the 1940s.
The origin of the term ''bankers' rounding'' remains more obscure. If this rounding method was ever a standard in banking, the evidence has proved extremely difficult to find. To the contrary, section 2 of the European Commission report ''The Introduction of the Euro and the Rounding of Currency Amounts'' suggests that there had previously been no standard approach to rounding in banking; and it specifies that "half-way" amounts should be rounded up.
Until the 1980s, the rounding method used in floating-point computer arithmetic was usually fixed by the hardware, poorly documented, inconsistent, and different for each brand and model of computer. This situation changed after the IEEE 754 floating-point standard was adopted by most computer manufacturers. The standard allows the user to choose among several rounding modes, and in each case specifies precisely how the results should be rounded. These features made numerical computations more predictable and machine-independent, and made possible the efficient and consistent implementation of interval arithmetic
Interval arithmetic (also known as interval mathematics; interval analysis or interval computation) is a mathematical technique used to mitigate rounding and measurement errors in mathematical computation by computing function bounds. Numeri ...
.
Currently, much research tends to round to multiples of 5 or 2. For example, Jörg Baten used age heaping
Whipple's index (or index of concentration), invented by American demographer George Chandler Whipple (1866–1924), is a method to measure the tendency for individuals to inaccurately report their actual age or date of birth. Respondents to a cens ...
in many studies, to evaluate the numeracy level of ancient populations. He came up with the ABCC Index, which enables the comparison of the numeracy
Numeracy is the ability to understand, reason with, and apply simple numerical concepts; it is the numerical counterpart of literacy. The charity National Numeracy states: "Numeracy means understanding how mathematics is used in the real world ...
among regions possible without any historical sources where the population literacy
Literacy is the ability to read and write, while illiteracy refers to an inability to read and write. Some researchers suggest that the study of "literacy" as a concept can be divided into two periods: the period before 1950, when literacy was ...
was measured.
Rounding functions in programming languages
Most programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s provide functions or special syntax to round fractional numbers in various ways. The earliest numeric languages, such as Fortran and C, would provide only one method, usually truncation (toward zero). This default method could be implied in certain contexts, such as when assigning a fractional number to an integer
An integer is the number zero (0), a positive natural number (1, 2, 3, ...), or the negation of a positive natural number (−1, −2, −3, ...). The negations or additive inverses of the positive natural numbers are referred to as negative in ...
variable, or using a fractional number as an index of an array. Other kinds of rounding had to be programmed explicitly; for example, rounding a positive number to the nearest integer could be implemented by adding 0.5 and truncating.
In the last decades, however, the syntax and the standard libraries
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
of most languages have commonly provided at least the four basic rounding functions (up, down, to nearest, and toward zero). The tie-breaking method can vary depending on the language and version or might be selectable by the programmer. Several languages follow the lead of the IEEE 754 floating-point standard, and define these functions as taking a double-precision float argument and returning the result of the same type, which then may be converted to an integer if necessary. This approach may avoid spurious overflows because floating-point types have a larger range than integer types. Some languages, such as PHP, provide functions that round a value to a specified number of decimal digits (e.g., from 4321.5678 to 4321.57 or 4300). In addition, many languages provide a printf
printf is a C standard library function that formats text and writes it to standard output. The function accepts a format c-string argument and a variable number of value arguments that the function serializes per the format string. Mism ...
or similar string formatting function, which allows one to convert a fractional number to a string, rounded to a user-specified number of decimal places (the ''precision''). On the other hand, truncation (round to zero) is still the default rounding method used by many languages, especially for the division of two integer values.
In contrast, CSS and SVG do not define any specific maximum precision for numbers and measurements, which they treat and expose in their DOM and in their IDL interface as strings as if they had infinite precision, and do not discriminate between integers and floating-point values; however, the implementations of these languages will typically convert these numbers into IEEE 754 double-precision floating-point values before exposing the computed digits with a limited precision (notably within standard JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
or ECMAScript
ECMAScript (; ES) is a standard for scripting languages, including JavaScript, JScript, and ActionScript. It is best known as a JavaScript standard intended to ensure the interoperability of web pages across different web browsers. It is stan ...
interface bindings).
Other rounding standards
Some disciplines or institutions have issued standards or directives for rounding.
US weather observations
In a guideline issued in mid-1966,[OFCM, 2005]
Federal Meteorological Handbook No. 1
, Washington, DC., 104 pp. the U.S.
The United States of America (USA), also known as the United States (U.S.) or America, is a country primarily located in North America. It is a federal republic of 50 states and a federal capital district, Washington, D.C. The 48 contiguous ...
Office of the Federal Coordinator for Meteorology determined that weather data should be rounded to the nearest round number, with the "round half up" tie-breaking rule. For example, 1.5 rounded to integer should become 2, and −1.5 should become −1. Prior to that date, the tie-breaking rule was "round half away from zero".
Negative zero in meteorology
Some meteorologist
A meteorologist is a scientist who studies and works in the field of meteorology aiming to understand or predict Earth's atmosphere of Earth, atmospheric phenomena including the weather. Those who study meteorological phenomena are meteorologists ...
s may write "−0" to indicate a temperature between 0.0 and −0.5 degrees (exclusive) that was rounded to an integer. This notation is used when the negative sign is considered important, no matter how small is the magnitude; for example, when rounding temperatures in the Celsius
The degree Celsius is the unit of temperature on the Celsius temperature scale "Celsius temperature scale, also called centigrade temperature scale, scale based on 0 ° for the melting point of water and 100 ° for the boiling point ...
scale, where below zero indicates freezing.
See also
* Cash rounding, dealing with the absence of extremely low-value coins
* Data binning, a similar operation
* Gal's accurate tables
* Guard digit
Guard or guards may refer to:
Professional occupations
* Bodyguard, who protects an individual from personal assault
* Crossing guard, who stops traffic so pedestrians can cross the street
* Lifeguard, who rescues people from drowning
* Prison ...
* Interval arithmetic
Interval arithmetic (also known as interval mathematics; interval analysis or interval computation) is a mathematical technique used to mitigate rounding and measurement errors in mathematical computation by computing function bounds. Numeri ...
* ISO/IEC 80000
ISO/IEC 80000, ''Quantities and units'', is an international standard describing the International System of Quantities (ISQ). It was developed and promulgated jointly by the International Organization for Standardization (ISO) and the Intern ...
* Kahan summation algorithm
* Party-list proportional representation
Party-list proportional representation (list-PR) is a system of proportional representation based on preregistered Political party, political parties, with each party being Apportionment (politics), allocated a certain number of seats Apportionm ...
* Signed-digit representation
In mathematical notation for numbers, a signed-digit representation is a positional numeral system with a set of signed digits used to encode the integers.
Signed-digit representation can be used to accomplish fast addition of integers becau ...
* Truncation
In mathematics and computer science, truncation is limiting the number of digits right of the decimal point.
Truncation and floor function
Truncation of positive real numbers can be done using the floor function. Given a number x \in \mathbb ...
Notes
References
External links
* {{MathWorld, id=Rounding
An introduction to different rounding algorithms
that is accessible to a general audience but especially useful to those studying computer science and electronics.
How To Implement Custom Rounding Procedures
by Microsoft (broken)
Arithmetic
Computer arithmetic
Statistical data transformation
Theory of computation