Round number to nearest integer

前端 未结 11 2113
傲寒
傲寒 2020-11-27 12:32

I\'ve been trying to round long float numbers like:

32.268907563;
32.268907563;
31.2396694215;
33.6206896552;
...

With no success so far. I

11条回答
  •  眼角桃花
    2020-11-27 13:15

    I use and may advise the following solution (python3.6):

    y = int(x + (x % (1 if x >= 0 else -1)))
    

    It works fine for half-numbers (positives and negatives) and works even faster than int(round(x)):

    round_methods = [lambda x: int(round(x)), 
                     lambda x: int(x + (x % (1 if x >= 0 else -1))),
                     lambda x: np.rint(x).astype(int),
                     lambda x: int(proper_round(x))]
    
    for rm in round_methods:
        %timeit rm(112.5)
    Out:
    201 ns ± 3.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    159 ns ± 0.646 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    925 ns ± 7.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    1.18 µs ± 8.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    for rm in round_methods:
        print(rm(112.4), rm(112.5), rm(112.6))
        print(rm(-12.4), rm(-12.5), rm(-12.6))
        print('=' * 11)
    
    Out:
    112 112 113
    -12 -12 -13
    ===========
    112 113 113
    -12 -13 -13
    ===========
    112 112 113
    -12 -12 -13
    ===========
    112 113 113
    -12 -13 -13
    ===========
    

提交回复
热议问题