如何将浮点数舍入为缩放整数?

时间:2016-08-11 14:45:55

标签: python math floating-point rounding

进一步解释我的标题:我有一系列浮点数我想要舍入,但是,我想将数字四舍五入到一个不是最接近整数的数字。例如,让我们说我想要将数字四舍五入到最接近的2的倍数。这就是我所拥有的:

Temp = np.around(data,0)

data是浮点数组。数字四舍五入到最接近的整数,但我希望它们四舍五入到最接近的2的倍数。我的目标:

0.9 - > 0

1.1 - > 2

谢谢!

2 个答案:

答案 0 :(得分:3)

两个中的两个是直截了当的:

x = np.array([0.9, 1.1, 10.2, 7.4])

2*np.round(x/2)   # array([  0.,   2.,  10.,   8.])

但这并不是一种普遍的做法。例如,没有obvoius"舍入到最近的Fibonacci数"。在给定函数2的情况下,考虑多个f(x)=2*x的公式:1)首先应用f的倒数(在这种情况下除以),然后是round, 3)然后将f应用于结果。为了实现这一点,f必须存在,具有反转,结果也必须是int;所以它只适用于一些功能。

答案 1 :(得分:1)

以下是一种方法:

import math

data = [0.9, 1.1, 10.2, 7.4]

rounded_numbers = []

for num in data:

    rounded_up_num = math.ceil(num)

    if rounded_up_num % 2 == 0:
        rounded_num = rounded_up_num
    else:
        rounded_num = math.floor(num)

    rounded_numbers.append(int(rounded_num))

print rounded_numbers # [0, 2, 10, 8]
相关问题