Round to the nearest number divisible by 2, 4, 8 and 16?

How can I round a decimal number to the nearest number divisible by 2, 4, 8 and 16 in python?

Example:

1920/1.33 = 1443.609022556391 

It should round to 1440, since it is easily divisible by 2, 4, 8, and 16 and vice versa (1440 * 1.33 = 1920).

1920/1.33 = 1440
+5
source share
3 answers

How about int( 16 * round( value / 16. ))?

+17
source

If the number is divisible by 16, then it is divisible by 2, 4 and 8. Knowing this, simply calculate modulo 16 the remainder of the decimal number and subtract it from the base number.

>>>> 1443.609022556391 - (1443.609022556391 % 16)
1440.0
+5
source

If you need a solution without division and rounding function, here is a simple one:

def round16(a):
    return int(a) + 8 & ~15

Example:

>>> [(x/2, round16(x/2)) for x in range(64)]
[(0.0, 0), (0.5, 0), (1.0, 0), (1.5, 0), (2.0, 0), (2.5, 0), (3.0, 0), (3.5, 0),
(4.0, 0), (4.5, 0), (5.0, 0), (5.5, 0), (6.0, 0), (6.5, 0), (7.0, 0), (7.5, 0),
(8.0, 16), (8.5, 16), (9.0, 16), (9.5, 16), (10.0, 16), (10.5, 16), (11.0, 16), (11.5, 16),
(12.0, 16), (12.5, 16), (13.0, 16), (13.5, 16), (14.0, 16), (14.5, 16), (15.0, 16),
(15.5, 16), (16.0, 16), (16.5, 16), (17.0, 16), (17.5, 16), (18.0, 16), (18.5, 16),
(19.0, 16), (19.5, 16), (20.0, 16), (20.5, 16), (21.0, 16), (21.5, 16), (22.0, 16),
(22.5, 16), (23.0, 16), (23.5, 16), (24.0, 32), (24.5, 32), (25.0, 32), (25.5, 32),
(26.0, 32), (26.5, 32), (27.0, 32), (27.5, 32), (28.0, 32), (28.5, 32), (29.0, 32),
(29.5, 32), (30.0, 32), (30.5, 32), (31.0, 32), (31.5, 32)]
0
source

All Articles