Rounding a number to nearest even

Scott David Daniels Scott.Daniels at Acm.Org
Fri Apr 11 07:37:03 EDT 2008


bdsatish wrote:
> The built-in function round( ) will always "round up", that is 1.5 is
> rounded to 2.0 and 2.5 is rounded to 3.0.
> 
> If I want to round to the nearest even, that is
> 
> my_round(1.5) = 2        # As expected
> my_round(2.5) = 2        # Not 3, which is an odd num
> 
> I'm interested in rounding numbers of the form "x.5" depending upon
> whether x is odd or even. Any idea about how to implement it ?

def rounded(v):
     rounded = round(v)
     if divmod(v, 1)[1] == .5 and divmod(rounded, 2)[1] == 1:
	if v > 0:
	    return rounded - 1
	return rounded + 1
     return rounded

last = None
for n in range(-29, 28):
     x = n * .25
     r = xr(x)
     if r != last:
	last = r
	print
     print '%s->%s' % (x, xr(x)),

-7.25->-7.0 -7.0->-7.0 -6.75->-7.0
-6.5->-6.0 -6.25->-6.0 -6.0->-6.0 -5.75->-6.0 -5.5->-6.0
-5.25->-5.0 -5.0->-5.0 -4.75->-5.0
-4.5->-4.0 -4.25->-4.0 -4.0->-4.0 -3.75->-4.0 -3.5->-4.0
-3.25->-3.0 -3.0->-3.0 -2.75->-3.0
-2.5->-2.0 -2.25->-2.0 -2.0->-2.0 -1.75->-2.0 -1.5->-2.0
-1.25->-1.0 -1.0->-1.0 -0.75->-1.0
-0.5->0.0 -0.25->-0.0 0.0->0.0 0.25->0.0 0.5->0.0
0.75->1.0 1.0->1.0 1.25->1.0
1.5->2.0 1.75->2.0 2.0->2.0 2.25->2.0 2.5->2.0
2.75->3.0 3.0->3.0 3.25->3.0
3.5->4.0 3.75->4.0 4.0->4.0 4.25->4.0 4.5->4.0
4.75->5.0 5.0->5.0 5.25->5.0
5.5->6.0 5.75->6.0 6.0->6.0 6.25->6.0 6.5->6.0
6.75->7.0



More information about the Python-list mailing list