【发布时间】:2020-11-16 13:01:08
【问题描述】:
是否有任何库或快捷方式来实现以下内容?对不起,如果这是一个愚蠢的问题,对python库不太熟悉。
如果小数点高于某个阈值而不是 0.5,我想四舍五入。
例如,如果我的阈值是 0.2,那么:
input => output
1.2 => 2
1.3 => 2
1.19 => 1
2.21 => 3
2.1 => 2
谢谢
【问题讨论】:
是否有任何库或快捷方式来实现以下内容?对不起,如果这是一个愚蠢的问题,对python库不太熟悉。
如果小数点高于某个阈值而不是 0.5,我想四舍五入。
例如,如果我的阈值是 0.2,那么:
input => output
1.2 => 2
1.3 => 2
1.19 => 1
2.21 => 3
2.1 => 2
谢谢
【问题讨论】:
你可以试试这个:
threshold = 0.2
def round_up(a):
if a - int(a) >= threshold:
return int(a) + 1
return int(a)
仅适用于正数。
【讨论】:
import math
input = 1.19
threshold = 1.2
math.floor(input) if input < threshold else math.ceil(input)
1
使阈值动态化:
import math
input = 1.19
threshold = 0.2
math.floor(input) if input < (math.floor(input) + threshold) else math.ceil(input)
1
【讨论】:
math.floor(input) if (input - math.floor(input)) < t else math.ceil(input)
t 当作threshold,如果t 是阈值,之前的答案将不起作用,这就是我建议更改的原因