Python 3 - complex numbers

I am trying to write a method for generating a sequence of Gaussian divisors of a Gaussian integer - a Gaussian integer is either a normal integer or a complex number g = a + bi , where a and b are integers, and a Gaussian divisor of a Gaussian integer g is a Gaussian integer d such that that g / d also a Gaussian integer.

I have the following code.

 def is_gaussian_integer(c): """ Checks whether a given real or complex number is a Gaussian integer, ie 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, ie 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 

It seems that β€œmostly” works, but for some inputs it skips some Gaussian dividers, for example. for 2 I expect the sequence to include the divisor -2 + 0j (which is just -2 ), but it is missing. I can’t understand why he does it or where there is a gap in the logic.

 In [92]: list(gaussian_divisors(2)) Out[92]: [(-1-1j), (-1+0j), (-1+1j), -1j, 1j, (1-1j), (1+0j), (1+1j), (2+0j)] 
+5
source share
1 answer

Instead of just giving in

 yield g 

you could additionally

 yield -g 

Since your loops start and stop on int(math.sqrt(abs(g))) = int(sqrt(2)) , which is just 1 , so it will just check -1 , 0 and 1 .

Alternatively, if you want to include -2 and 2 in your loops, you need to either increase the result of ubound or math.ceil sqrt .

+1
source

Source: https://habr.com/ru/post/1262842/


All Articles