【问题标题】:How can I make this tiny Python 2.7 complex number code snippet work the same with Python 3?如何使这个小小的 Python 2.7 复数代码片段与 Python 3 一样工作?
【发布时间】:2022-01-21 06:22:00
【问题描述】:

check.py——

import sys

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

预期结果——

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

但是——

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

【问题讨论】:

    标签: python python-3.x python-2.7 ubuntu complex-numbers


    【解决方案1】:

    减法后除:

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

    输出:

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

    【讨论】:

    • Python 2 的哪些变化造成了这种差异?
    【解决方案2】:

    如果可能的话,您可以对图像部分使用圆形方法,如下所示:

    导入系统

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

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 2023-03-26
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2014-02-11
      • 2023-04-02
      相关资源
      最近更新 更多