Jump to content

Rounding: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Reverted to revision 312550010 by 84.81.69.133; revert unexplained blanking. (TW)
Line 321: Line 321:
** <code>CType(value, Integer)</code> uses bankers' rounding. Since this is a .NET language, programs may also use any of the rounding methods of the .NET framework (see above).
** <code>CType(value, Integer)</code> uses bankers' rounding. Since this is a .NET language, programs may also use any of the rounding methods of the .NET framework (see above).
*[[XSLT]] 1.0:
*[[XSLT]] 1.0:
** Uses round half even
** Uses round half up <ref>http://www.w3.org/TR/xpath#function-round</ref>
*[[AppleScript]]
*[[AppleScript]]
**<code>round</code> is the rounding function. By default, it rounds to the nearest even number. However, it takes an optional tag that specifies how to round: <code>rounding up</code>, <code>rounding down</code>, <code>rounding toward zero</code>, or <code>rounding as taught in school</code> (round-half-up). <code>rounding to nearest</code> is a synonym for the default behavior.
**<code>round</code> is the rounding function. By default, it rounds to the nearest even number. However, it takes an optional tag that specifies how to round: <code>rounding up</code>, <code>rounding down</code>, <code>rounding toward zero</code>, or <code>rounding as taught in school</code> (round-half-up). <code>rounding to nearest</code> is a synonym for the default behavior.

Revision as of 10:50, 28 September 2009

Rounding a numerical value means replacing it by another value that is approximately equal but has a shorter, simpler, or more explicit representation; for example, replacing US$ 23.4476 by US$ 23.45, or the fraction 312/937 by 1/3, or by 1.41.

Rounding produces a value that is easier to write and handle than the original, but, on the other hand, it also introduces some round-off error in the result. Rounding is almost unavoidable in many computations — especially when dividing two numbers in integer or fixed point arithmetic; when computing mathematical functions such as square roots, logarithms, and sines; or when using a floating point representation with a fixed number of significant digits.

Accurate rounding of mathematical functions is difficult because the number of extra digits that need to be calculated to resolve whether to round up or down is not 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 must be encoded by numbers or digital signals.

Types of roundings

Typical rounding problems are

  • approximating an irrational number by a fraction, e.g. π by 22/7;
  • approximating a fraction with periodic decimal expansion by a finite decimal fraction, e.g. 5/3 by 1.6667;
  • replacing a rational number by a fraction with smaller numerator and denominator, e.g. 3122/9417 by 1/3;
  • replacing a fractional decimal number by one with fewer digits, e.g. 2.1785 dollars by 2.18 dollars;
  • replacing a decimal integer by an integer with more trailing zeros, e.g. 23,217 people by 23,200 people; or, in general,
  • replacing a value by a multiple of a specified amount, e.g. 27.2 seconds by 30 seconds (a multiple of 15).

The most basic form of rounding is to replace an arbitrary number by an integer. This operation underlies many other kinds of rounding, such as rounding to whole hundreths, to thousands, to whole dozens, etc.. In general, rounding a number x to a multiple of some specified number m entails the following steps:

  1. Divide x by m, let the result be y;
  2. Round y to an integer value, call it q;
  3. Multiply q by m to obtain the rounded value z.

For example, rounding x = 2.1785 dollars to whole hundredths (i.e., to a multiple of 0.01) entails computing y = x/m = 2.1785/0.01 = 217.85, then rounding y to the integer q = 218, and finally computing z = q×m = 218×0.01 = 2.18.

Rounding can be done in any number system; in computers, it is usually performed on binary numbers.

Rounding methods

Basic rounding to integer

There are many ways of rounding a number y to an integer q. The most common ones are

  • round to nearest: q is the integer that is closest to y (see below for tie-breaking rules).
  • round towards zero (or truncate): q is the integer part of y, without its fraction digits.
  • round down (or take the floor): q is the largest integer that does not exceed y.
  • round up (or take the ceiling): q is the smallest integer that is not less than y.
  • round away from 0: if y is an integer, q is y; else q is the integer that is closest to 0 and is such that y is between 0 and q.

The last four methods are called directed rounding, as the displacements from the original number y to the rounded value q are all directed towards or away the same limiting value (0, +, or -∞).

If y is positive, round-down is the same as round-towards-zero, and round-up is the same as round-away-from-zero. If y is negative, round-down is the same as round-away-from-zero, and round-up is the same as round-towards-zero. In any case, if y is integer, q is just y. The following table illustrates these rounding methods:

y   to
nearest
  towards
zero
  down   up   away
from zero
+23.67 +24 +23 +23 +24 +24
+23.35 +23 +23 +23 +24 +24
−23.35 −23 −23 −24 −23 −24
−23.67 −24 −23 −24 −23 −24

Tie-breaking

Rounding a number y to the nearest integer requires some tie-breaking rule for those cases when y is exactly half-way between two integers — that is, when the fraction part of y is exactly .5

Where many calculations are done in sequence rounding can have a very significant effect on the result. A famous instance involved a new index set up by the Vancouver Stock Exchange in 1982. It was initially set at 1000.000 but after 22 months had fallen to about 520 whereas the market was doing well. The problem was caused by the index being held to 3 decimal places, always rounded down. The index was recalculated thousands of times daily and the errors accumulated. Recalculating with better rounding gave a value of 1098.892.[1]

Round half up

The following tie-breaking rule, called round half up, is widely used in accounting and other disciplines:

  • If the fraction of y is exactly .5, then q = y + 0.5

That is, half-way values y are always rounded up. For example, by this rule the value 23.5 gets rounded to 24, but -23.5 gets rounded to -23.

This is one of two rules generally taught in US elementary mathematics classes.[citation needed]

If it were not for the 0.5 fractions, the roundoff errors introduced by the round to nearest method would be quite symmetric: for every fraction that gets rounded up (such as .732), there is a complementary fraction (namely, .268) that gets rounded down, by the same amount. When rounding a large set of numbers with random fractional parts, these rounding errors would statistically compensate each other, and the expected (average) value of the rounded numbers would be equal to the expected value of the original numbers.

However, the "round half up" tie-breaking rule is not symmetric, as the fractions that are exactly 0.5 always get rounded up. This asymmetry introduces a positive bias in the roundoff errors. For example, if the fraction of y consists of three random decimal digits, then the expected value of q will be 0.0005 higher than the expected value of y. For this reason, round-to-nearest with the round-half-up rule is also known as asymmetric rounding.

Round half away from zero

The other tie-breaking method commonly taught and used is the round half away from zero, namely:

  • If the fraction of y is exactly .5, then q = y + 0.5 if y is positive, and q = y - 0.5 if y is negative

For example, 23.5 gets rounded to 24, and -23.5 gets rounded to -24.

This method treats positive and negative values symmetrically, and therefore is free of overall bias if the original numbers are positive or negative with equal probability. However, this rule will still introduce a positive bias for positive numbers, and a negative bias for the negative ones.

Round half to even

A tie-breaking rule that is even less biased is round half to even, namely

  • If the fraction of y is 0.5, then q is the even integer nearest to y.

Thus, for example, +23.5 becomes +24, +22.5 becomes +22, -22.5 becomes -22, and -23.5 becomes -24. This variant of the round-to-nearest method is also called unbiased rounding, convergent rounding, statistician's rounding, Dutch rounding, Gaussian rounding, or bankers' rounding. For most reasonable distributions of y values, the expected (average) value of the rounded numbers is essentially the same as that of the original numbers, even if the latter are all positive (or all negative).

Stochastic rounding

Another unbiased tie-breaking method is stochastic rounding:

  • If the fractional part of y is .5, choose q randomly among y+0.5 and y-0.5, with equal probability.

Like round-half-to-even, this rule is essentially free of overall bias; but it is also fair among even and odd q values. On the other hand, it introduces a random component into the result: performing the same computation twice on the same data may yield two different results.

Dithering

In some contexts, all the rounding methods above may be unsatisfactory. For example, suppose that y is an accurate measurement of an audio signal, which is being rounded to an integer q in order to reduce the storage or transmission costs. If y changes slowly with time, any of the rounding method above will result in q being completely constant for long intervals, separated by sudden jumps of ±1. When the q signal is played back, these steps will be heard as a very disagreeable noise, and any variations of the original signal between two integer values will be completely lost.

One way to avoid this problem is to round each value y upwards with probability equal to its fraction, and round it downwards with the complement of that probability. For example, the number 23.17 would be rounded up to 24 with probability 0.17, and down to 23 with probability 1-0.17 = 0.83. (This is equivalent to rounding y+s to the nearest integer, where s is a random number uniformly distributed between 0 and 1.) With this special rounding, known as dithering, the sudden steps get replaced by a less objectionable noise, and even small variations in the original signal will be preserved to some extent.

Floating-point rounding

In floating-point arithmetic, rounding aims to turn a given value x into a value z with a specified number of significant digits. In other words, z should be a multiple of a number m that depends on the magnitude of z. The number m 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.

For results where the rounded result would overflow the result for a directed rounding is either the appropriate infinity or the highest representable finite number depending on the direction. The result of an overflow for the usual case of round to even is always the appropriate infinity.

Rounding to simple fractions

In some contexts it is desirable to round a given number x to a "neat" fraction — that is, the nearest fraction z = m/n whose numerator m and denominator n 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 m. This problem is related to Farey sequences, the Stern-Brocot tree, and continued fractions.

Exact computation with rounded arithmetic

It is possible to use rounded arithmetic to evaluate the exact value of a function with a discrete domain and range. For example, if we know that an integer n is a perfect square, we can compute its square root by converting n to a floating-point value x, computing the approximate square root y of x with floating point, and then rounding y to the nearest integer q. If n is not too big, the floating-point roundoff error in y will be less than 0.5, so the rounded value q will be the exact square root of n. In most modern computers, this method may be much faster than computing the square root of n by an all-integer algorithm.

The table-maker's dilemma

William Kahan coined the term "The Table-Maker's Dilemma" for the unknown cost of rounding transcendental functions:

"Nobody knows how much it would cost to compute y^w correctly rounded for every two floating-point arguments at which it does not over/underflow. Instead, reputable math libraries compute elementary transcendental functions mostly within slightly more than half an ulp and almost always well within one ulp. Why can't Y^W be rounded within half an ulp like SQRT? Because nobody knows how much computation it would cost... No general way exists to predict how many extra digits will have to be carried to compute a transcendental expression and round it correctly to some preassigned number of digits. Even the fact (if true) that a finite number of extra digits will ultimately suffice may be a deep theorem."[2]

The IEEE floating point standard guarantees that add, subtract, multiply, divide, square root, and floating point remainder will give the correctly rounded result of the infinite precision operation. However, no such guarantee is given for more complex functions and they are typically only accurate to within the last bit at best.

Using the Gelfond–Schneider theorem and Lindemann–Weierstrass theorem many of the standard elementary functions can be proved to return transcendental results when given rational non-zero arguments; therefore it is always possible to correctly round such functions. However there is no way of determining in advance how accurate a result needs to be computed before a correctly rounded result can be produced.

There are some packages around now that offer full accuracy. The MPFR package gives correctly rounded arbitrary precision results. IBM have written a package for fast and accurate IEEE elementary functions and in the future the standard libraries may offer such precision.[3]

It is possible to devise well defined numbers which it may never be possible to correctly round no matter how many digits are calculated. For instance if Goldbach's conjecture is true but unprovable then it is impossible to correctly round down 0.5 + 10-n where n is the first even number greater than 4 which is not the sum of two primes.

History

The concept of rounding is very old, perhaps older even than the concept of division. Some ancient clay tablets found in Mesopotamia contain tables with rounded values of reciprocals and square roots in base 60.[citation needed].

The Round-to-even method has served as the ASTM (E-29) standard since 1940. The origin of the terms unbiased rounding and statistician's rounding are fairly self-explanatory. In the 1906 4th edition of Probability and Theory of Errors [1] Robert Simpson Woodward called this "the computer's rule" indicating that it was then in common use by human computers who calculated mathematical tables. Churchill Eisenhart's 1947 paper "Effects of Rounding or Grouping Data" (in Selected Techniques of Statistical Analysis, McGrawHill, 1947, Eisenhart, Hastay, and Wallis, editors) indicated that the practice was already "well established" in data analysis.

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 [2] 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.

Rounding functions in programming languages

  • C
    • C99 specifies (in <math.h>):
      • round(): round to nearest integer, halfway away from zero
      • rint(), nearbyint(): round according to current floating-point rounding direction
      • ceil(): smallest integral value not less than argument (round up)
      • floor(): largest integral value not greater than argument (round down)
      • trunc(), (int)[4]: round towards zero
    • The current floating-point rounding direction may, depending on implementation, be retrieved and set using the fegetround()/fesetround() functions defined in <fenv.h>; the available directions are specified to be at least those in IEEE 854 (see IEEE 754#Rounding floating-point numbers) which include round-to-even, round-down, round-up, and round-to-zero.
  • Fortran:
    • NINT: round to nearest integer, return integer result
    • ANINT: round to nearest integer, return real result
    • INT: truncate (round towards zero), return integer result
    • AINT: truncate (round towards zero), return real result
    • CEILING: smallest integral value not less than argument (round up) (Fortran-90)
    • FLOOR: largest integral value not greater than argument (round down) (Fortran-90)
  • Java
    • Math and StrictMath: round-half-up (asymmetric) or round-to-even (Math.rint).[5][6]
    • BigDecimal: Supports "round up", "round down", "round floor", "round ceiling", "round half up", "round half down", "round half even" and even a "rounding unnecessary" mode. Note, however, that the implementation of round half-up is symmetric, unlike the implementation of round half-up in Java.Math.
    • Math.round(-3.5) or StrictMath.round(-3.5) gives −3.
  • JavaScript:
    • Uses Asymmetric Arithmetic Rounding
  • Common Lisp:
    • round: round-to-even, fractional part as secondary value:
      • (round 2.5) ; => 2, 0.5
      • (round 3.5) ; => 4, -0.5
    • truncate, floor, ceiling: round to zero, down or up respectively, fractional part as secondary value:
      • (floor -2.5) ; => -3, 0.5
      • (ceiling -2.5) ; => -2, -0.5
  • Mathematica:
    • Round: round to even
      • Round[2.5] gives 2
      • Round[3.5] gives 4
    • IntegerPart: round toward zero
      • IntegerPart[2.7] gives 2
      • IntegerPart[-2.7] gives -2
    • Floor: round down
      • Floor[2.7] gives 2
      • Floor[-2.3] gives -3
    • Ceiling: round up
      • Ceiling[2.3] gives 3
      • Ceiling[-2.7] gives -2
  • MATLAB:
    • round(X): round to nearest integer, trailing 5 rounds to the nearest integer away from zero
      • round(2.5) returns 3
      • round(-2.5) returns -3
    • fix(X): round to nearest integer toward zero (truncate)
      • fix(2.7) returns 2
      • fix(-2.7) returns -2
    • floor(X): round to the nearest integer toward minus infinity (round to the nearest integer less than or equal to X)
      • floor(2.7) returns 2
      • floor(-2.3) returns -3
    • ceil(X): round to the nearest integer toward minus infinity (round to the nearest integer greater than or equal to X)
      • ceil(2.3) returns 3
      • ceil(-2.7) returns -2
  • Pascal:
    • Round and RoundTo (nonstandard) use bankers' rounding
    • Str (nonstandard), Write and FloatToStr (nonstandard) don't use bankers' rounding
    • Ceil(): smallest integral value not less than argument (round up)
    • Floor(): largest integral value not greater than argument (round down)
    • Trunc(): round towards zero
  • Perl:
    • printf "%f" or sprintf "%f": use bankers' rounding
    • int: chops off fractional part, rounding towards zero
    • POSIX::ceil: smallest integral value not less than argument (round up)
    • POSIX::floor: largest integral value not greater than argument (round down)
  • PHP:
    • round(-3.5) gives −4.
    • round(8.7352, 3) gives 8.735.
    • round(4278.5, -2) gives 4300.
  • Python:
    • Version 2.6.1 and lower use round-away-from-zero: round(0.5) is 1.0, round(-0.5) is -1.0.
    • Version 3.0 and higher use round-to-even: round(1.5) is 2.0, round(2.5) is 2.0.
    • Integer division is rounded down towards -inf: 7//3=2, −7//3=−3.
    • The Decimal type/class in module decimal (new in version 2.4) provides exact numerical representation and several rounding modes.
  • Ruby:
    • 2.5.round gives 3.
    • 3.5.round gives 4.
    • -3.5.round gives −4.
    • The BigDecimal class offers additional rounding options.
  • SQL:
    • TRUNC() to round numerics or dates (in DB2, PostgreSQL, Oracle and MySQL)[7]
    • ROUND() (in Sybase, Oracle and Microsoft SQL Server)[7]
  • Visual Basic for Applications:
    • Uses Round-Half-Even (Bankers' Rounding)[8]
    • ? Round(2.5, 0) gives 2.
  • Microsoft SQL Server:
    • Uses either Symmetric Arithmetic Rounding or Symmetric Round Down (Fix) depending on arguments
    • SELECT Round(2.5, 0) gives 3.
  • Microsoft Excel:
    • Uses Symmetric Arithmetic Rounding
    • = ROUND(2.5, 0) gives 3.
    • = ROUND(3.5, 0) gives 4.
    • = ROUND(-3.5, 0) gives −4
  • Microsoft .NET Framework
    • Uses Round-Half-Even by default. Since v2 of the framework Symmetric Arithmetic Rounding is also available and the caller can specify which method to use.[9]
  • C#
    • C# programs generally use methods of the .NET framework for rounding. (See above.)
  • Visual Basic .NET
    • CType(value, Integer) uses bankers' rounding. Since this is a .NET language, programs may also use any of the rounding methods of the .NET framework (see above).
  • XSLT 1.0:
    • Uses round half up [10]
  • AppleScript
    • round is the rounding function. By default, it rounds to the nearest even number. However, it takes an optional tag that specifies how to round: rounding up, rounding down, rounding toward zero, or rounding as taught in school (round-half-up). rounding to nearest is a synonym for the default behavior.

Other rounding standards

Some disciplines or institutions have issued standards or directives for rounding.

U.S. Weather Observations

In a guideline issued in mid-1966,[11] the U.S. 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 meteorologists may write "-0" to indicate a temperature between 0.0 and −0.5 degrees (exclusive) that was rounded to 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 scale, where below zero indicates freezing.[citation needed]

See also

External links

References

  1. ^ Nicholas J. Higham (2002). Accuracy and stability of numerical algorithms. p. 54. ISBN 978-0898715217.
  2. ^ Kahan, William. "A Logarithm Too Clever by Half". Retrieved 2008-11-14.
  3. ^ "An accurate elementary mathematical library for the IEEE floating point standard".
  4. ^ typecasting to an int returns an int instead of a double unlike the other functions.
  5. ^ Template:Cite api
  6. ^ Template:Cite api
  7. ^ a b Jones, Arie (2005). SQL Functions Programmer's Reference. Indianapolis, IN: Wiley. p. 127. ISBN 9780764569012. {{cite book}}: Cite has empty unknown parameters: |accessyear=, |origmonth=, |accessmonth=, |month=, |chapterurl=, and |origdate= (help); Unknown parameter |coauthors= ignored (|author= suggested) (help)
  8. ^ http://support.microsoft.com/kb/194983
  9. ^ http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
  10. ^ http://www.w3.org/TR/xpath#function-round
  11. ^ OFCM, 2005: Federal Meteorological Handbook No. 1, Washington, DC., 104 pp.