Ran*_*lus 3 python numpy rounding
我想知道如何将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)
Run Code Online (Sandbox Code Playgroud)
Rug*_*rra 13
我想你不需要numpy:
def getRoundedThresholdv1(a, MinClip):
return round(float(a) / MinClip) * MinClip
Run Code Online (Sandbox Code Playgroud)
这里a是一个单一的数字,如果你想向量化此功能,您只需要更换round与np.round和float(a)与np.array(a, dtype=float)
小智 8
摘要:这是一种正确的方法,最上面的答案有不起作用的情况:
def round_step_size(quantity: Union[float, Decimal], step_size: Union[float, Decimal]) -> float:
"""Rounds a given quantity to a specific step size
:param quantity: required
:param step_size: required
:return: decimal
"""
precision: int = int(round(-math.log(step_size, 10), 0))
return float(round(quantity, precision))
Run Code Online (Sandbox Code Playgroud)
我的声誉太低,无法对 Ruggero Turra 的最佳答案发表评论并指出问题。然而,它也有不起作用的情况,例如:
def getRoundedThresholdv1(a, MinClip):
return round(float(a) / MinClip) * MinClip
getRoundedThresholdv1(quantity=13.200000000000001, step_size=0.0001)
Run Code Online (Sandbox Code Playgroud)
无论使用 numpy 还是标准库回合,都会立即返回 13.200000000000001。我什至通过对该功能进行压力测试都没有发现这一点。它只是在生产代码中使用它时出现并抛出错误。
请注意,此答案的全部功劳来自开源 github 存储库,该存储库不是我在此处找到的
| 归档时间: |
|
| 查看次数: |
7878 次 |
| 最近记录: |