Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 794
a.smiet Avatar asked Jul 27 '15 08:07

a.smiet


2 Answers

You need to ceil before dividing:

import numpy as np

def round_up_to_odd(f):
    return np.ceil(f) // 2 * 2 + 1
like image 172
Holt Avatar answered Oct 10 '22 21:10

Holt


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.

like image 37
JuniorCompressor Avatar answered Oct 10 '22 21:10

JuniorCompressor