2015-02-10 90 views
3

我想效仿this function。我想將浮點數舍入到最接近的0.05的倍數(或者通常是最接近的倍數)。將四捨五入的浮點數湊整到最接近的0.05

我想這一點:

>>> my_magical_rounding(1.29, 0.05) 
1.25 

>>> my_magical_rounding(1.30, 0.05) 
1.30 

我可以這樣做:

import math  
def my_magical_rounding(n, r): 
    return n - math.fmod(n, r) 

>>> my_magical_rounding(1.27, 0.05) 
1.25 # Yay! 

>>> my_magical_rounding(1.30, 0.05) 
1.25 # Boo! I want 1.30. 

大概是由於浮點舍入。

我可以把一些特殊情況檢查,看看n是「足夠接近」的r倍數,而不是做減法,這可能會起作用,但有沒有更好的方法?

或者是this strategy我最好的選擇?

+0

嘗試了這一點:) 回報(N +( r-(n%r))) – 2015-02-10 07:04:35

+0

你想讓'my_magical_rounding(1.29,0.05)'給出什麼? '1.30'還是'1.25'? – dopstar 2015-02-10 09:55:31

+0

1.25。編輯該問題以使其更加清晰。 – 2015-02-10 22:32:42

回答

10

您可以向下舍到a這樣的最接近倍數:

def round_down(x, a): 
    return math.floor(x/a) * a 

可以輪的a這樣的最接近倍數:

def round_nearest(x, a): 
    return round(x/a) * a 
6

由於@Anonymous寫道:

你可以四捨五入到最接近的一個像這樣:

def round_nearest(x, a): 
    return round(x/a) * a 

作品近乎完美,但round_nearest(1.39, 0.05)給1.4000000000000001。 爲了避免它,我會建議做的事情:

import math 
def round_nearest(x, a): 
    return round(round(x/a) * a, -int(math.floor(math.log10(a)))) 

這輪精密a,然後到顯著位數,有你精密a