简体   繁体   中英

How to set minimum value to a division operation in python?

Is there a standard library function which will set a minimum value to a division operation, for example:

min(1, a/b)

This will ensure that min value of operation above will always be 1, never 0.

Such as:

min(1, 1/5)
1

Also, how do I round up a division:

round_up(1/5) = 1

I always get "0" when I divide 1/5, even with ceil function:

math.ceil(1/5)
0

If you want to use floating point division as default, you can do from __future__ import division :

>>> 1/5
0
>>> from __future__ import division
>>> 1/5
0.2
>>> math.ceil(1/5)
1.0

If you need the result to be of integer type, eg for indexing, you can use

int(math.ceil(1/5))

The result of 1/5 is an integer already. If you want the floating point version you need to do 1.0/5 . The math.ceil function will then work as you expect: math.ceil(1.0/5) = 1.0 .

If you're working with variables instead of constants, use the float(x) function to convert an integer into a floating point.

In [4]: 1/5
Out[4]: 0

In [5]: math.ceil(1/5)
Out[5]: 0.0

In [7]: float(1)/5
Out[7]: 0.2

In [8]: math.ceil(float(1)/5)
Out[8]: 1.0

You could make a round up function for integers like this

>>> def round_up(p, q):
...     d, r = divmod(p, q)
...     if r != 0:
...         d += 1
...     return d
... 
>>> round_up(1, 5)
1
>>> round_up(0, 5)
0
>>> round_up(5, 5)
1
>>> round_up(6, 5)
2
>>> 

Your example doesn't work because an integer dividing an integer is an integer.

As for your min question - what you wrote is probably the best you can do.

I don't know about anything in the standard library, but if you are just trying to make sure the answer is never less than 1, the function is pretty easy:

def min_dev(x,y):
    ans = x/y
    if ans < 1:      # ensures answer cannot be 0
        return 1
    else:            # answers greater than 1 are returned normally
        return ans

If, instead, you are looking to round up every answer:

def round_up(x,y):
    ans = x//y         # // is the floor division operator
    if x % y == 1:     # tests for remainder (returns 0 for no, 1 for yes)
        ans += 1       # same as ans = ans + 1
        return ans
    else:
        return ans

This will round up any answer with a remainder. I believe Python 3.3 (and I know 3.4) return a float by default for integer division: https://docs.python.org/3/tutorial/introduction.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM