四舍五入到最接近的步长

编程入门 行业动态 更新时间:2024-10-28 18:31:18
本文介绍了四舍五入到最接近的步长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道如何将numpy中的数字四舍五入到上限或下限,这是预定义步长的函数.希望以更清楚的方式说明,如果我的数字是123,步长等于50,则需要将123舍入到150或100(在这种情况下为100)中最接近的值.但我想知道是否有更好,更简洁的方法.

I would like to know how I can round a number in numpy to an upper or lower threshold which is function of predefined step size. Hopefully stated in a clearer way, if I have the number 123 and a step size equal to 50, I need to round 123 to the closest of either 150 or 100, in this case 100. I came out with function below which does the work but I wonder if there is a better, more succint, way to do this.

预先感谢

保罗

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)

推荐答案

我认为您不需要numpy:

def getRoundedThresholdv1(a, MinClip): return round(float(a) / MinClip) * MinClip

此处a是单个数字,如果要向量化此功能,则只需将round替换为np.round,将float(a)替换为np.array(a, dtype=float)

here a is a single number, if you want to vectorize this function you only need to replace round with np.round and float(a) with np.array(a, dtype=float)

更多推荐

四舍五入到最接近的步长

本文发布于:2023-06-08 23:36:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/591021.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:步长   最接近   四舍五入

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!