Python将浮点数舍入到最接近的0.05
发布时间:2020-12-20 13:05:26 所属栏目:Python 来源:网络整理
导读:我想模仿 this function.我想将浮点数舍入到最接近的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.
我想模仿
this function.我想将浮点数舍入到最接近的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是我最好的选择? 解决方法
您可以向下舍入到最接近的倍数,如下所示:
def round_down(x,a): return math.floor(x / a) * a 您可以舍入到最接近的倍数,如下所示: def round_nearest(x,a): return round(x / a) * a (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |