Re:Python rounds float values by converting them to string a...
by dagw on Wednesday August 28, 2019 @07:19AM
(#20818662)
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
Re:Python rounds float values by converting them to string a...
by phkahler on Wednesday August 28, 2019 @08:39AM
(#20819155)
The problem is the division after truncation. That division by a power of 10 can produce errors in binary.
Re:Python rounds float values by converting them to string a...
by Armisael16 on Wednesday August 28, 2019 @07:47AM
(#20818803)
How does truncating a positive number ever round up?
Re:Python rounds float values by converting them to string a...
by NohatCoder on Wednesday August 28, 2019 @08:08AM
(#20818948)
Add 0.5 before rounding towards negative infinity, and you'll get standard rounding.
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.