Search code examples
pythonpython-3.xpython-2.7ubuntucomplex-numbers

How can I make this tiny Python 2.7 complex number code snippet work the same with Python 3?


check.py —

import sys

def main():
    h = 5
    for y in range(h):   
        fy = 2j * y / h - 1j
        print ( fy )    
        
main()

expected result —

$ python --version
Python 2.7.18
$ python check.py
-1j
-0.6j
-0.2j
0.2j
0.6j

but —

$ python3  --version
Python 3.10.1
$ python3 check.py
-1j
-0.6j
-0.19999999999999996j
0.19999999999999996j
0.6000000000000001j

Solution

  • Divide after the subtraction:

    def main():
        h = 5
        for y in range(h):   
            fy = (2j * y - h * 1j) / h
            print(fy)
    

    Output:

    -1j
    -0.6j
    -0.2j
    0.2j
    0.6j