Ad

Same Code For Python 2 And 3 Gives Different Results

- 1 answer

I have the issue that I run python 3 on my client and the server where I execute the programs run python 2.

So I set up the following script:

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

When I run it locally with python 3 I get the following output:

0.8521437889662113
1.0
0.36787944117144233

However, when I run it on the server I get:

0.367879441171
1.0
0.367879441171
Ad

Answer

The problem lies in the division here diff/h_date

From the details mentioned in this answer here or this answer here

  • In Python2.7, division of two ints produces an int
>>> -12/30
-1
  • In Python3, division of two ints produces an float
>>> -12/30
-0.4

So depending on what you want

  • If you want a float for both cases, import from __future__ import division in Python2.7,
>>> from __future__ import division
>>> -12/30
-0.4
  • If you want a int in both cases, perform integer division // in Python3
>>> -12//30
-1
Ad
source: stackoverflow.com
Ad