如何将一个十进制数舍入到python中可被2,4,8和16整除的最近数字?
示例:
1920/1.33 = 1443.609022556391
它应该四舍五入到1440,因为它很容易被2,4,8和16整除,反之亦然(1440 * 1.33 = 1920)。
1920/1.33 = 1440
答案 0 :(得分:17)
int( 16 * round( value / 16. ))
怎么样?
答案 1 :(得分:6)
如果一个数字可以被16整除,那么它可以被2,4和8整除。知道这一点,只需计算十进制数的模16余数并从基数中减去它。
>>>> 1443.609022556391 - (1443.609022556391 % 16)
1440.0
答案 2 :(得分:0)
如果您想要一种不具有除法和舍入功能的解决方案,请使用以下简单方法:
def round16(a):
return int(a) + 8 & ~15
示例:
>>> [(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)]