Round a float UP to next odd integer

11,880

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.

Share:
11,880
a.smiet
Author by

a.smiet

learning by doing

Updated on July 06, 2022

Comments

  • a.smiet
    a.smiet almost 2 years

    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?

  • a.smiet
    a.smiet over 8 years
    sys.version gives me '2.7.6 (default, Jun 22 2015, 17:58:13) \n[GCC 4.8.2]' but only the first code works?!
  • Holt
    Holt over 8 years
    @a.smiet I misplaced a bracket in the second example, actually the first one should also works in python 2+ since // already truncates float division in python 2.