简体   繁体   English

将浮点数向上舍入到下一个奇数

[英]Round a float UP to next odd integer

How can I round a fload up to the next odd integer? 我如何能圆一个FLOAD 下一个奇数。 I found how it can be done for even numbers here . 我发现在这里偶数可以做到这一点 So I tried something like: 所以我尝试了类似的东西:

import numpy as np

def round_up_to_odd(f):
    return np.ceil(f / 2.) * 2 + 1

But of course this does not round it to the NEXT odd number: 但当然这不会将其舍入到NEXT奇数:

>>> odd(32.6)
35.0

Any suggestions? 有什么建议么?

You need to ceil before dividing: 分开之前你需要ceil

import numpy as np

def round_up_to_odd(f):
    return np.ceil(f) // 2 * 2 + 1

What about: 关于什么:

def round_up_to_odd(f):
    f = int(np.ceil(f))
    return f + 1 if f % 2 == 0 else f

The idea is first to round up to an integer and then check if the integer is odd or even. 这个想法首先是舍入到一个整数,然后检查整数是奇数还是偶数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM