如何在Python中设置除法运算的最小值?

问题描述 投票:0回答:6

是否有标准库函数可以为除法运算设置最小值,例如:

min(1, a/b)

这将确保上述操作的最小值始终为 1,而不是 0。

如:

min(1, 1/5)
1

另外,我如何四舍五入:

round_up(1/5) = 1

即使使用 ceil 函数,当我除 1/5 时,我总是得到“0”:

math.ceil(1/5)
0
python division minimum integer-division
6个回答
3
投票

如果你想默认使用浮点除法,你可以这样做

from __future__ import division
:

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

如果您需要结果为整数类型,例如对于索引,您可以使用

int(math.ceil(1/5))

2
投票

1/5
的结果已经是一个整数了。如果你想要浮点版本,你需要做
1.0/5
。然后
math.ceil
函数将按您的预期工作:
math.ceil(1.0/5) = 1.0

如果您使用变量而不是常量,请使用

float(x)
函数将整数转换为浮点数。


2
投票
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

0
投票

您可以为这样的整数创建一个向上舍入函数

>>> 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
>>> 

您的示例不起作用,因为整数除以整数是整数。

至于你的最小问题 - 你写的可能是你能做的最好的。


0
投票

我对标准库中的任何内容一无所知,但如果你只是想确保答案永远不会小于 1,那么该函数非常简单:

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

如果您希望汇总每个答案:

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

这会将任何答案四舍五入并保留余数。 我相信Python 3.3(我知道3.4)默认返回一个浮点数进行整数除法:https://docs.python.org/3/tutorial/introduction.html


0
投票

针对您的用例的简单策略,无需导入任何内容:

max(1, a/b)
© www.soinside.com 2019 - 2024. All rights reserved.