0

when i run this python code in python3 it shows different results from python2? why there are different values?

    d = 0
    x1 = 0
    x2 = 1
    y1 = 1
    e=125
    phi=238
    temp_phi = phi

    while e > 0:
        print (e, temp_phi)
        temp1 = temp_phi / e
        print (temp1)
        temp2 = temp_phi - temp1 * e
        print (temp2)
        temp_phi = e
        e = temp2

        x = x2 - temp1 * x1
        y = d - temp1 * y1

        x2 = x1
        x1 = x
        d = y1
        y1 = y
    print (d + phi)
    if temp_phi == 1:
         print (d + phi)
  • 1
    because of the division `temp1 = temp_phi / e` you have in there. – Ma0 Jun 08 '18 at 08:02
  • 1
    When both operands are integers, the `/` operator was changed from integer division to (e.g. `floor(x/y)` or `(x//y)`) to returning a float (e.g. the equivalent of Python2's `float(x)/y`) – jedwards Jun 08 '18 at 08:02
  • 1
    Division works differently in python 2 and 3: https://stackoverflow.com/questions/21316968/division-in-python-2-7-and-3-3 – koPytok Jun 08 '18 at 08:03
  • 1
    Possible duplicate of [Division in Python 2.7. and 3.3](https://stackoverflow.com/questions/21316968/division-in-python-2-7-and-3-3) – Ma0 Jun 08 '18 at 08:05

2 Answers2

0

The reason for the change in values when running in Python 2 and 3 is that the / operator performs differently depending on the version the program is being run in. This can be read about in PEP 238 which details the change which took place in python 3

To ensure that the same results are achieved in both python 2 and 3, use the following import statement when using python 2:

from __future__ import division

This ensures that your code is compatible with both versions of python.

lyxαl
  • 1,108
  • 1
  • 16
  • 26
0

The problem lies on this line:

temp1 = temp_phi / e

In Python 2, the / operator performs integer division when both its arguments are integers. That is, it is equivalent (conceptually) to floor(float(a) / float(b)), where a and b are its integer arguments. In Python 3, / is float-division regardless of the types of its arguments, and the behaviour of / from Python 2 is recreated by the // operator.

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
  • Nitpick: while `a / b` is conceptually equivalent to `floor(float(a) / float(b))`, thanks to the imprecision and limited range of the floating-point type, it's not actually equivalent in practice for large integers `a` and `b`. – Mark Dickinson Jun 08 '18 at 12:40