【问题标题】:Basic python arithmetic - division基本的python算术 - 除法
【发布时间】:2010-07-29 22:02:03
【问题描述】:

我有两个变量:count,它是我过滤的对象的数量,以及 per_page 的常量值。我想将计数除以 per_page 并获得整数值,但无论我尝试什么 - 我得到 0 或 0.0:

>>> count = friends.count()
>>> print count
1
>>> per_page = 2
>>> print per_page
2
>>> pages = math.ceil(count/per_pages)
>>> print pages
0.0
>>> pages = float(count/per_pages)
>>> print pages
0.0

我做错了什么,为什么 math.ceil 给出浮点数而不是 int ?

【问题讨论】:

  • 当我这样做时它可以工作:count = float(count), per_page = float(per_page), pages = math.ceil(count/per_page) 最后 pages = int(pages) 。但这有点愚蠢。
  • 见[为什么这个除法在python中不起作用? ](stackoverflow.com/questions/1787249/…)。

标签: python math python-2.x


【解决方案1】:

当两个操作数都是整数时,Python会进行整数除法,这意味着1 / 2基本上是“2进1的次数”,当然是0次。做你想做的事,将一个操作数转换为浮点数:1 / float(2) == 0.5,正如你所期望的那样。当然,math.ceil(1 / float(2)) 将产生 1,正如您所期望的那样。

(我认为这种除法行为在 Python 3 中有所改变。)

【讨论】:

    【解决方案2】:

    整数除法是 Python / 运算符的默认值。这有一些看起来有点奇怪的行为。它返回没有余数的股息。

    >>> 10 / 3
    3
    

    如果您运行的是 Python 2.6+,请尝试:

    from __future__ import division
    
    >>> 10 / 3
    3.3333333333333335
    

    如果您运行的 Python 版本低于此版本,则需要将分子或分母中的至少一个转换为浮点数:

    >>> 10 / float(3)
    3.3333333333333335
    

    另外,math.ceil 总是返回一个浮点数...

    >>> import math 
    >>> help(math.ceil)
    
    ceil(...)
        ceil(x)
    
        Return the ceiling of x as a float.
        This is the smallest integral value >= x.
    

    【讨论】:

    • 不要挑剔,但它是分子,而不是提名者 =]
    • 我在专注于“整数”部分的文档中错过了这一点:P 谢谢
    【解决方案3】:

    来自Python documentation (math module)

    math.ceil(x)

    将 x 的上限作为浮点数返回,即大于或等于 x 的最小整数值。

    【讨论】:

      【解决方案4】:

      它们是整数,所以count/per_pages 在函数可以做任何事情之前为零。我真的不是 Python 程序员,但我知道(count * 1.0) / pages 会做你想做的事。不过,这可能是一种正确的方法。

      编辑 — 是的,请参阅@mipadi 的回答和float(x)

      【讨论】:

      • 与其到处乘以 1.0,不如直接使用from __future__ import division
      • 如果我对 Python 有所了解,我可能会这样做 :-)
      【解决方案5】:

      因为你设置它的方式是执行操作,然后将其转换为浮点数尝试

      count = friends.count()
      print count
      
      per_page = float(2)
      print per_page
      
      pages = math.ceil(count/per_pages)
      
      print pages
      pages = count/per_pages
      

      通过将 count 或 per_page 转换为浮点数,其所有未来操作都应该能够进行除法并最终得到非整数

      【讨论】:

        【解决方案6】:
        >>> 10 / float(3)
        3.3333333333333335
        >>> #Or 
        >>> 10 / 3.0
        3.3333333333333335
        >>> #Python make any decimal number to float
        >>> a = 3
        >>> type(a)
        <type 'int'>
        >>> b = 3.0
        >>> type(b)
        <type 'float'>
        >>> 
        

        最好的解决方案可能是使用from __future__ import division

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-17
          • 2015-02-28
          • 1970-01-01
          • 2016-07-03
          相关资源
          最近更新 更多