Round a number to the next odd integer

How to combine fload up into the next odd integer? I found how this 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 an NEXT odd number:

>>> odd(32.6)
35.0

Any suggestions?

+4
source share
2 answers

You need ceilbefore dividing:

import numpy as np

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

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 to first round to an integer and then check if the integer is odd or even.

+6
source

Source: https://habr.com/ru/post/1599840/


All Articles