我一直在编写一些代码来列出Python中有理整数的高斯整数除数。 (关于项目欧拉问题153)
我似乎在某些数字上遇到了一些麻烦,我相信它与Python近似于复数的划分有关。
这是我的函数代码:
def IsGaussian(z):
#returns True if the complex number is a Gaussian integer
return complex(int(z.real), int(z.imag)) == z
def Divisors(n):
divisors = []
#Firstly, append the rational integer divisors
for x in range(1, int(n / 2 + 1)):
if n % x == 0:
divisors.append(x)
#Secondly, two for loops are used to append the complex Guassian integer divisors
for x in range(1, int(n / 2 + 1)):
for y in range(1, int(n / 2 + 1)):
if IsGaussian(n / complex(x, y)) == n:
divisors.append(complex(x, y))
divisors.append(complex(x, -y))
divisors.append(n)
return divisors
当我运行Divisors(29)
时,我得到[1, 29]
,但是缺少了其他四个除数,其中一个是(5 + 2j),可以清楚地看出它除以29。
在运行29 / complex(5, 2)
时,Python会提供(5 - 2.0000000000000004j)
此结果不正确,因为它应为(5 - 2j)
。有什么办法以某种方式绕过Python的近似值?为什么100岁以下的许多其他理性整数没有出现这个问题?
提前感谢您的帮助。