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

Jes*_*erg 0 python python-2.7 python-3.x

我的问题是我在客户端上运行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"))
Run Code Online (Sandbox Code Playgroud)

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

0.8521437889662113
1.0
0.36787944117144233
Run Code Online (Sandbox Code Playgroud)

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

0.367879441171
1.0
0.367879441171
Run Code Online (Sandbox Code Playgroud)

Dev*_*ngh 7

问题出在这里 diff/h_date

从在此提到的细节答案或在这里这个答案在这里

  • 在Python2.7中,两个整数的除法产生一个整数
>>> -12/30
-1
Run Code Online (Sandbox Code Playgroud)
  • 在Python3中,两个整数的除法产生一个浮点数
>>> -12/30
-0.4
Run Code Online (Sandbox Code Playgroud)

所以根据你想要的

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