Python类中除法计算的差异

时间:2012-02-03 12:39:00

标签: python python-3.x python-2.7

我有一个Python 3类方法来重新调整值,如下所示:

class A(object):
    """docstring for A"""
    def __init__(self):
        super(A, self).__init__()

    def rescale(self, old_min, old_max, new_min, new_max, value):
         """rescales a value given a current old_min and 
         old_max to the desired new_min and new_max"""
         scale = (old_max - old_min) / (new_max - new_min)
         rescaled_value = new_min + ((value - old_min) / (scale))
         return rescaled_value 

使用Python 3,此方法的工作方式如下:

>>> import A
>>> x = A()
>>> x.rescale(1,10,1,100,5)
45.0

在Python 2.7中,此代码不起作用:

>>> from __future__ import division
>>> x = A()
>>> x.rescale(1,10,1,100,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bunsen.py", line 35, in rescale
rescaled_value = new_min + ((value - old_min) / (scale))
ZeroDivisionError: integer division or modulo by zero

如果我在Python 2.7中手动执行此算法,我会得到正确的答案:

>>> from __future__ import division
>>> scale = (10 - 1) / (100 - 1)
>>> rescaled_value = 1 + ((5 - 1) / (scale))
>>> rescaled_value
45.0

有人能指出为什么这种方法在Python 2.7中不起作用吗?

3 个答案:

答案 0 :(得分:8)

您需要在包含分部的文件中设置from __future__ import division,即在A的文件中设置。{/ p>

答案 1 :(得分:3)

对于python 2.7,您可以:

    x.rescale(1.0, 10.0, 1.0, 100.0, 5.0)

或者你可以在方法内部显式转换为float。

    scale = float((old_max - old_min)) / (new_max - new_min)

或者另一种方法是导入from __future__ import division

这是因为在python 2.x中整数除以整数将得到一个整数,在你的情况下为0.

评论后

编辑

确保您执行

    from __future__ import division

IN 模块A,因为进行的计算不像你那样做。

答案 2 :(得分:1)

在2.7中使用此代码:

from __future__ import division

class A(object):
    """docstring for A"""
    def __init__(self):
        super(A, self).__init__()

    def rescale(self, old_min, old_max, new_min, new_max, value):
         """rescales a value given a current old_min and 
         old_max to the desired new_min and new_max"""
         scale = (old_max - old_min) / (new_max - new_min)
         rescaled_value = new_min + ((value - old_min) / (scale))
         return rescaled_value 

x = A()
print x.rescale(1,10,1,100,5)

给了我:

45.0

如果我删除__future__导入,我会收到:

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    print x.rescale(1,10,1,100,5)
  File "test.py", line 11, in rescale
    rescaled_value = new_min + ((value - old_min) / (scale))
ZeroDivisionError: integer division or modulo by zero

必须在定义A 的模块中拥有from __future__ import division。导入会影响其中包含的模块。