【发布时间】:2017-05-08 10:56:55
【问题描述】:
我一直在编写一些代码来列出 Python 中有理整数的高斯整数除数。 (与Project Euler问题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以下的有理整数没有出现这个问题?
提前感谢您的帮助。
【问题讨论】:
-
这可能源于
complex在内部使用两个双精度数字来表示实部和虚部。您可以使用decimal或round来实现您自己的复数,并将结果精确到适当的小数位数。 -
呃,
if IsGaussian(n / complex(x, y)) == n:应该做什么?它只能在 n = 0 或 n = 1 时为 True。您可能想摆脱== n。
标签: python division complex-numbers approximation