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

Time:01-21

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

CodePudding user response:

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

CodePudding user response:

If it's posible you can use round method for imag part, like this:

import sys

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


main()
  •  Tags:  
  • Related