- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我需要用特定的小数位数对 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
参数,但似乎函数 ceil
和 floor
没有'接受小数位数并始终返回小数点为零的数字。
当然,我可以将数字乘以 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/
在调度问题中。我想按工作天数分配假期。现在我有一个使用多个 bool 标志的有效解决方案,但它的扩展性不是很好。 from ortools.sat.python import cp_model fro
如何在 jq jq-1.5-1-a5b5cbe 中对数字进行舍入、地板、天花板和截断? 例如,使用 {"mass": 188.72} , 我要 {"mass": 188}带地板,{"mass": 18
我有一个小型的 C++ 项目,一直在 XCode 中工作,我想在我的 Windows 机器上的 Visual Studio 上做一些工作。我创建了一个新项目并将所有源文件复制到新项目中。没有外部依赖性
我是一名优秀的程序员,十分优秀!