Hacker News new | ask | show | jobs
by ben509 2494 days ago
Rounding a number is, in the common case, multiplying it by some base, truncating to an integer, and dividing by the base. You do have to handle extremely high exponents, but even the logic for that is not complex.

Example of implementing it the sane way: https://github.com/numpy/numpy/blob/75ea05fc0af60c685e6c071d...

Every step of this function is complex and expensive, especially printing a float as a decimal is very complex. And round is routinely used in a tight loop.

3 comments

The numpy approach sacrifices correctness for speed (you sometimes get unexpected results in some corner cases, see below), the cpython way sacrifices speed for correctness.

  >>> round(56294995342131.5, 2)
  56294995342131.5
  >>> round(56294995342131.5, 3)
  56294995342131.5

  >>> np.round(56294995342131.5, 2)
  56294995342131.5
  >>> np.round(56294995342131.5, 3)
  56294995342131.51
The problem is the division after truncation. That division by a power of 10 can produce errors in binary.
How does truncating a positive number ever round up?
Add 0.5 before rounding towards negative infinity, and you'll get standard rounding.