python 2和3的相同代码给出不同的结果

时间:2019-05-20 07:32:25

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

我的问题是我在客户端上运行python 3,而执行程序的服务器运行了python 2。

所以我设置了以下脚本:

from math import radians, cos, sin, asin, sqrt, exp
from datetime import datetime
def dateSmoother(a, b):
    #Format the date
    a = datetime.strptime(a, "%Y-%m-%d")
    b = datetime.strptime(b, "%Y-%m-%d")
    diff = (a-b).days

    return exp(-(diff/h_date)**2)

def timeSmoother(a, b):
    # Since we only got readings from two different times
    # We first check to see if they are the same
    if (a==b):
        return exp(-(0/h_time)**2)
    else:
        return exp(-(12/h_time)**2)


h_date = 30
h_time = 12
a = "2013-11-01"
b = "2013-11-13"
print(dateSmoother(a, b))
print(timeSmoother("06:00:00", "06:00:00"))
print(timeSmoother("06:00:00", "18:00:00"))

当我使用python 3在本地运行时,得到以下输出:

0.8521437889662113
1.0
0.36787944117144233

但是,当我在服务器上运行它时,会得到:

0.367879441171
1.0
0.367879441171

1 个答案:

答案 0 :(得分:7)

问题出在diff/h_date

根据此处answer或此处answer的详细信息

  • 在Python2.7中,将两个int相除会生成一个int
>>> -12/30
-1
  • 在Python3中,两个整数的除法会产生一个浮点数
>>> -12/30
-0.4

所以要根据您的需求

  • 如果两种情况都需要浮点数,请在Python2.7中导入from __future__ import division
>>> from __future__ import division
>>> -12/30
-0.4
  • 如果在两种情况下都需要int,请在Python3中执行整数除法//
>>> -12//30
-1