Issue
I am new to python, and as far as I found out, python doesn't have sort of "mathematical" rounding. Or does it have? I have a temperature array, for example:
temp = [-20.5, -21.5, -22.5, -23.5, 10.5, 11.5, 12.5, 13.5]
I couldn't fine the way to round values mathematically to:
>> [-21, -21, -22, -22, -22, -24, -23, -23, -23, -23, -24, ...]
So that -20.5 rounded to -21, -21.5 rounded to -22, -23.5 rounded to -24, 10.5 rounded to 11, 11.5 rounded to 12, 12.5 rounded to 13. Mathematical accuracy is important in my case.
The best option for me is using function like numpy.around() due to it does rounding for all the values at ones, not one by one (I suppose, it is faster). Is there such a function, or such a way at all?
Results i got:
np.around(temp, decimals=0)
>>[-20. -22. -22. -24. 10. 12. 12. 14.]
np.rint(temp)
>>[-20. -22. -22. -24. 10. 12. 12. 14.]
np.round(temp)
>>[-20. -22. -22. -24. 10. 12. 12. 14.]
np.trunc(temp)
>>[-20. -21. -22. -23. 10. 11. 12. 13.]
Solution
numpy
has a around
, which documents:
Notes
-----
For values exactly halfway between rounded decimal values, NumPy
rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
-0.5 and 0.5 round to 0.0, etc. Results may also be surprising due
to the inexact representation of decimal fractions in the IEEE
floating point standard [1]_ and errors introduced when scaling
by powers of ten.
Rounding to nearest even is just as valid, mathematically, as rounding away from zero. The purpose of such rules is to provide consistency, and some degree of statistical uniformity (reduce bias).
But it also warns that float values are seldom 'exactly' half's. We frequently get questions about values that display like 20.49999999
.
===
A numpy version of the round_away_from_zero
function in the other answer:
def round_away(x):
a = np.abs(x)
b = np.floor(a) + np.floor(2*(a%1))
return np.sign(x)*b
In [279]: np.array(temp)
Out[279]: array([-20.5, -21.5, -22.5, -23.5, 10.5, 11.5, 12.5, 13.5])
In [280]: round_away(temp)
Out[280]: array([-21., -22., -23., -24., 11., 12., 13., 14.])
Answered By - hpaulj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.