Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

python - floor and ceil with number of decimals

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

So:

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)

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

UPD: As pointed out by @aschipfl, for whole values np.round will round to the nearest even, which will lead to unexpected results, e.g. my_ceil(11) will return 12. Here is an updated solution, free of this problem:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...