底数和小数位数 [英] floor and ceil with number of decimals

查看:99
本文介绍了底数和小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要给浮点数加上一个特定的小数位数.

I need to floor a float number with an specific number of decimals.

所以:

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

函数np.round接受decimals参数,但是看来函数ceilfloor不接受小数位数,并且始终返回零位数的数字.

The function np.round accepts a decimals parameter but it appears that the functions ceil and floor don't accept a number of decimals and always return a number with zero decimals.

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

Of course I can multiply the number by 10^ndecimals, then apply floor and finally divide by 10^ndecimals

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

但是我想知道是否有一个内置函数可以执行此操作而不必执行操作.

But I'm wondering if there's a built-in function that does this without having to do the operations.

推荐答案

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

Neither Python built-in nor numpy's version of ceil/floor support precision.

一个提示是重用循环而不是多用+相除(应该更快):

One hint though is to reuse round instead of multyplication + division (should be much faster):

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)

这篇关于底数和小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆