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

How to round floats to scaled integers?

进一步解释我的标题:我有一个浮点数数组,我想对其进行舍入,但是,我想将数字舍入为不是最接近整数的数字。例如,假设我希望将数字四舍五入为最接近的整数,即 2 的倍数。这就是我所拥有的:

Temp = np.around(data,0)

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

0.9 -> 0

1.1 -> 2

等等

谢谢!

以下是一种方法:

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]

二的倍数很简单:

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

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

但是对此没有通用的方法。例如,没有 obvoius "round to the nearest Fibonacci number"。考虑 2 倍数的公式,给定一个函数 f(x)=2*x:1) 首先应用 f 的逆函数(在这种情况下除法),2) 然后 round, 3) 然后将 f 应用于结果。为此,f 必须存在,有一个逆,结果也必须是一个 int;所以它只适用于少数功能。