Python 3 - 复数

srm*_*srm 5 python complex-numbers python-3.x

我正在尝试编写一种方法来生成高斯整数的高斯除数序列 - 高斯整数是正整数或复数g = a + bi,其中ab都是整数,高斯整数的高斯除数g是高斯整数dg / d也是高斯整数.

我有以下代码.

def is_gaussian_integer(c):
    """
        Checks whether a given real or complex number is a Gaussian integer,
        i.e. a complex number g = a + bi such that a and b are integers.
    """
    if type(c) == int:
        return True
    return c.real.is_integer() and c.imag.is_integer()


def gaussian_divisors(g):
    """
        Generates a sequence of Gaussian divisors of a rational or Gaussian
        integer g, i.e. a Gaussian integer d such that g / d is also a Gaussian integer.
    """
    if not is_gaussian_integer(g):
        return
    if g == 1:
        yield complex(g, 0)
        return
    g = complex(g) if type(g) == int or type(g) == float else g
    a = b = 1
    ubound = int(math.sqrt(abs(g)))
    for a in range(-ubound, ubound + 1):
        for b in range(-ubound, ubound + 1):
            if a or b:
                d = complex(a, b)
                if is_gaussian_integer(g / d):
                    yield d
    yield g
Run Code Online (Sandbox Code Playgroud)

它似乎"大部分"起作用,但对于某些输入它缺少一些高斯除数,例如2我希望序列包含除数-2 + 0j(这只是-2),但它缺失了.我无法弄清楚为什么会这样做或者逻辑上存在差距.

In [92]: list(gaussian_divisors(2))
Out[92]: [(-1-1j), (-1+0j), (-1+1j), -1j, 1j, (1-1j), (1+0j), (1+1j), (2+0j)]
Run Code Online (Sandbox Code Playgroud)

MSe*_*ert 1

而不是仅仅屈服

yield g
Run Code Online (Sandbox Code Playgroud)

你还可以另外

yield -g
Run Code Online (Sandbox Code Playgroud)

因为你的循环在int(math.sqrt(abs(g)))=int(sqrt(2))处开始和停止1,所以它只会测试-1,01

或者,如果您想在循环中包含-2and ,2则需要增加uboundmath.ceil结果sqrt