【问题标题】:How to set minimum value to a division operation in python?如何在python中为除法运算设置最小值?
【发布时间】:2012-05-31 18:23:42
【问题描述】:

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

min(1, a/b)

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

如:

min(1, 1/5)
1

另外,我如何四舍五入:

round_up(1/5) = 1

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

math.ceil(1/5)
0

【问题讨论】:

    标签: python division minimum integer-division


    【解决方案1】:

    我对标准库中的任何内容一无所知,但如果您只是想确保答案永远不会小于 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

    【讨论】:

      【解决方案2】:

      如果你想默认使用浮点除法,你可以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))
      

      【讨论】:

        【解决方案3】:

        你可以为这样的整数做一个向上取整函数

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

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

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

        【讨论】:

          【解决方案4】:
          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
          

          【讨论】:

            【解决方案5】:

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

            如果您使用的是变量而不是常量,请使用 float(x) 函数将整数转换为浮点数。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-06-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多