13

What is the default rounding mode (rounding to nearest, etc) in Python? And how can we specify it?

1
  • 5
    What is so "high level" about not having a proper rounding mode? Commented Dec 2, 2015 at 7:28

4 Answers 4

14

With IEEE754-based platform (as most modern ones do, including x86, ARM, MIPS...), it's default mode "round to nearest, ties to even" is the only mode available in Python standard library. That is "provided" by standardized defaults and absense of library methods to change it. There are more languages that doesn't allow to change rounding mode - e.g. Java - so this isn't an isolated Python whim.

In real, there are too few reasons to change this. Direct rounding modes of IEEE754 are very special in their use. (I don't apologize the approach to stick on the default rounding, but simply comment on it.) For example, multiply of 1e308 by 1e308 with rounding to zero or to minus infinity results in approximately 1.8e308, so, the result is too far both from the exact answer and from POLA-based one (infinity). If you really need some specific modes for your computations, consider using specific libraries, like MPFR or gmpy2.

If you insist on changing this without external modules specialized on floating-point calculations, try using C-library fesetround via ctypes module or analog, e.g. here. Again, it's your choice to use such hacks and become responsible to all consequences. I'd suggest wrapping all pieces with special rounding to C-level code which restores the default mode on function exit.

4
  • I would say that the principle of least astonishment requires the mathematical result 1e616 being rounded to the greatest representable floating-point value below that number, and +inf is definitely not that. I would also be astonished if interval arithmetic did not soundly over-approximate the sets of values that could have been obtained with real computations. Commented Dec 2, 2015 at 18:01
  • @PascalCuoq your attitude exposes even more that direct rounding is not for getting an approximate result, but for detecting a possible interval. For an exact value, even with an unusual rounding, making value which is closer to sqrt(x) instead of x and less by ~308 decimal magnitudes isn't ever admissible; but, for interval detecting, it's rather adequate.
    – Netch
    Commented Dec 2, 2015 at 20:18
  • @RudyVelthuis could you please elaborate when this appeared and how the API is named?
    – Netch
    Commented Aug 18, 2016 at 6:42
  • @Netch: When what appeared? Commented Aug 18, 2016 at 11:02
5

The accepted answer is not really correct. While floats are probably what first comes to mind when someone asks about rounding modes, they are not the place you should look.

The reason is simple: rounding is something you use to make your answer have a smaller number of digits. Whenever you mention digits, you must be sure what base you're talking about. I don't know about you specifically, but when people speak of digits, they usually mean decimal digits. For that purpose, floats are obviously inadequate, since they have binary digits. You cannot round a float 0.12 to one decimal digit because it doesn't make sense: despite the appearance, it doesn't have that kind of digits. :-)

Of course, what you can do, is try to compensate for the decimal inexactness of floats by rounding them so the overshoots and undershoots cancel each other in the best possible way, and in that context, it has been proven long ago that there is only one right answer, ROUND_HALF_EVEN---and it is provided by float (and by round function, if you need it on some higher decimal place) out of the box. But please note that it's not the same as 'calculating the mean grade' (ROUND_HALF_UP, usually), or 'estimating the mean error' (ROUND_UP), or 'giving you a tax grade (ROUND_FLOOR), or various other specific tasks which need some fixed number of decimal digits (or in case of some now defunct currencies, some other base, but usually not binary).

And in fact, there is a Python standard library module which gives you all the rounding modes you might find useful, and given the above paragraphs, it is the logical place to look: of course, it's the decimal module. It represents floating point numbers not in base 2, but in base 10, and as such, it offers the meaningful possibility to round a number to a given number of decimals, using a rounding method that makes sense for a particular task.

>>> import statistics, decimal
>>> grades = map(decimal.Decimal, [4, 5])
>>> print(statistics.mean(grades).to_integral_exact(decimal.ROUND_HALF_UP))
5

HTH.

-2

I've used these in the past without any negative effects:

from math import floor, ceil

def round_floor(scale, x):
  return floor(x*(10**scale))/(10**scale)

def round_ceiling(scale,x):
  return ceil(x*(10**scale))/(10**scale)

but I haven't considered the implications for very large or very precise numbers.

>>> round_floor(1,123.456)
123.4
>>> round_floor(-1,123.456)
120.0
>>> round_floor(2,123.456)
123.45

>>> round_ceiling(1,123.456)
123.5
>>> round_ceiling(-1,123.456)
130.0
>>> round_ceiling(-2,123.456)
200.0
-4

round() is the built in fonction for rounding. it works as follows:

round(number[, ndigits])

it returns the float type number you are rounding with ndigits decimals

Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). The return value is an integer if called with one argument, otherwise of the same type as number.

for limitations: https://docs.python.org/3/tutorial/floatingpoint.html#tut-fp-issues

sources: https://docs.python.org/3/library/functions.html

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.