Round a float UP to next odd integer
How can I round a float up to the next odd integer? 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:
>>> odd(32.6)
35.0
Any suggestions?
Solution 1:
You need to ceil
before dividing:
import numpy as np
def round_up_to_odd(f):
return np.ceil(f) // 2 * 2 + 1
Solution 2:
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.