【发布时间】:2023-12-26 07:42:01
【问题描述】:
我想知道如何将 numpy 中的数字舍入到上限或下限,这是预定义步长的函数。希望以更清晰的方式说明,如果我有数字 123 和等于 50 的步长,我需要将 123 舍入到最接近的 150 或 100,在本例中为 100。我得出了下面的函数但我想知道是否有更好、更简洁的方法来做到这一点。
提前致谢,
保罗
def getRoundedThresholdv1(a, MinClip):
import numpy as np
import math
digits = int(math.log10(MinClip))+1
b = np.round(a, -digits)
if b > a: # rounded-up
c = b - MinClip
UpLow = np.array((b,c))
else: # rounded-down
c = b + MinClip
UpLow = np.array((c,b))
AbsDelta = np.abs(a - UpLow)
return UpLow[AbsDelta.argmin()]
getRoundedThresholdv1(143, 50)
【问题讨论】:
-
您的代码不起作用,例如
getRoundedThresholdv1(143, 50)返回 50 而不是 150 -
现在可以使用 - 需要 int(math.log10(MinClip))+1 而不是 int(math.log10(a))+1 - 感谢您指出这一点