[英]Python rounding a floating point number to nearest 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
的倍數而不進行減法,這可能會起作用,但是有更好的方法嗎?
或者這個策略是我最好的選擇?
您可以四舍五入到最接近的a
倍數,如下所示:
def round_down(x, a):
return math.floor(x / a) * a
您可以四舍五入到最接近的倍數a
是這樣的:
def round_nearest(x, a):
return round(x / a) * a
正如@Anonymous 所寫:
您可以四舍五入到 a 的最近倍數,如下所示:
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
def round_nearest(x,a):
return round(round(x/a)*a ,2)
這是一個略有不同的變化!
Paul Hankin的先前回答未通過測試round_down(4.6, 0.2) == 4.6
。 此答案通過了所有先前的測試,但它並未嘗試更改浮點數的精度。 它使用math.isclose
中最初建議的math.isclose
。
import math
def round_down(num: float, to: float) -> float:
mod = math.fmod(num, to)
return num if math.isclose(mod, to) else num - mod
> round_down(1.27, 0.05), round_down(1.30, 0.05)
(1.25, 1.3)
> round_down(4.4, 0.2), round_down(4.5, 0.2), round_down(4.6, 0.2)
(4.4, 4.4, 4.6)
def round_up(num: float, to: float) -> float:
down = round_down(num, to)
return num if num == down else down + to
> round_up(1.27, 0.05), round_up(1.30, 0.05)
(1.3, 1.3)
> round_up(4.4, 0.2), round_up(4.5, 0.2), round_up(4.6, 0.2)
(4.4, 4.6000000000000005, 4.6)
def round_nearest(num: float, to: float) -> float:
return round(num / to) * to
> round_nearest(1.27, 0.05), round_nearest(1.30, 0.05), round_nearest(1.39, 0.05)
(1.25, 1.3, 1.4000000000000001)
> round_nearest(82, 4.3)
81.7
def round_nearest2(num: float, to: float) -> float:
down, up = round_down(num, to), round_up(num, to)
return down if ((num - down) < (up - num)) else up
> round_nearest2(1.27, 0.05), round_nearest2(1.30, 0.05), round_nearest2(1.39, 0.05)
(1.25, 1.3, 1.4000000000000001)
> round_nearest(82, 4.3)
81.7
撇開精確度和貼近度不談,你能找到一個失敗的例子嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.