3 ms·
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
by ben509 7y 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/75ea05fc0af60c685e6c071dae1f04c489a3ce93/numpy/core/src/multiarray/calculation.c#L667 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.
- dagw 7y agoThe 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
- Armisael16 7y agoHow does truncating a positive number ever round up?
- NohatCoder 7y agoAdd 0.5 before rounding towards negative infinity, and you'll get standard rounding.
- deleted 7y ago[deleted]
- deleted 7y ago[deleted]
- deleted 7y ago[deleted]
- phkahler 7y agoThe problem is the division after truncation. That division by a power of 10 can produce errors in binary.