gpt4 book ai didi

python - 带有小数位数的地板和天花板

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:36 26 4
gpt4 key购买 nike

我需要用特定的小数位数对 float 进行下限。

所以:

2.1235 with 2 decimals --> 2.12
2.1276 with 2 decimals --> 2.12 (round would give 2.13 which is not what I need)

函数 np.round 接受一个 decimals 参数,但似乎函数 ceilfloor 没有'接受小数位数并始终返回小数点为零的数字。

当然,我可以将数字乘以 10^ndecimals,然后应用 floor,最后除以 10^ndecimals

new_value = np.floor(old_value * 10**ndecimals) / 10**ndecimals

但我想知道是否有一个内置函数可以在无需执行操作的情况下执行此操作。

最佳答案

内置的 Python 和 numpy 版本的 ceil/floor 都不支持精度。

不过,一个提示是重用 round 而不是乘法 + 除法(应该快得多):

def my_ceil(a, precision=0):
return np.round(a + 0.5 * 10**(-precision), precision)

def my_floor(a, precision=0):
return np.round(a - 0.5 * 10**(-precision), precision)

更新:正如@aschipfl 所指出的,对于整个值,np.round 将四舍五入到最接近的偶数,这将导致意想不到的结果,例如my_ceil(11) 将返回 12。这是一个更新的解决方案,没有这个问题:

def my_ceil(a, precision=0):
return np.true_divide(np.ceil(a * 10**precision), 10**precision)

def my_floor(a, precision=0):
return np.true_divide(np.floor(a * 10**precision), 10**precision)

关于python - 带有小数位数的地板和天花板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58065055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com