![](/img/trans.png)
[英]Why does round raise on ndigits=None for integers but not for floats?
[英]How to round floats to scaled integers?
進一步說明我的標題:我有一個浮點數組,但是我想四舍五入,但是我想將這些數字四舍五入為不是最接近的整數。 例如,假設我想將數字四舍五入為最接近的整數,該整數是2的倍數。這就是我的意思:
Temp = np.around(data,0)
data
是浮點數數組。 數字四舍五入到最接近的整數,但我希望將它們四舍五入到最接近的2的倍數。我的目標:
0.9-> 0
1.1-> 2
等等
謝謝!
兩個的倍數很簡單:
x = np.array([0.9, 1.1, 10.2, 7.4])
2*np.round(x/2) # array([ 0., 2., 10., 8.])
但是,沒有通用的方法。 例如,沒有obvoius“四舍五入到最近的斐波那契數”。 考慮的多個式2
如,給定的函數f(x)=2*x
:1)第一應用的逆f
在這種情況下(除),2)然后round
,3)然后應用f
導致。 為了使它起作用, f
必須存在,具有逆,並且結果也必須是int
; 因此它僅適用於一些功能。
以下是一種方法:
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.