我正在尝试编写一个方法来生成高斯整数的高斯除数序列-高斯整数可以是普通整数或复数
g = a + bi
,其中a
和b
都是整数,高斯整数g
的高斯除数是一个高斯整数d
,使得g / 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
看起来它“基本上”有效,但对于某些输入,它会遗漏一些高斯因子,例如对于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)]
//
,而不是/
。对于复数操作数,我不知道它的作用。 - President James K. Polk//
运算符不适用于复数,例如1 / 1j
会按预期给出-1j
,但是1 // -1j
会抛出错误:TypeError: can't take floor of complex number.
。这可能是因为与整数不同,复数没有自然排序。 - srmif g == 1: yield complex(g, 0) return
是不正确的。数字1
的因数是1,-1,i,-i
。 - Stef