Skip to content

Commit cad7266

Browse files
committed
Fix leaking in __complex__
- Fixes #81 - Fixes complex conversion of quadratic numbers (t_QUAD)
1 parent a70441b commit cad7266

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

cypari2/gen.pyx

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1936,8 +1936,7 @@ cdef class Gen(Gen_base):
19361936

19371937
def __complex__(self):
19381938
r"""
1939-
Return ``self`` as a Python ``complex``
1940-
value.
1939+
Return ``self`` as a Python ``complex`` value.
19411940
19421941
Examples:
19431942
@@ -1951,18 +1950,40 @@ cdef class Gen(Gen_base):
19511950
>>> complex(g)
19521951
(0.8090169943749475+0.5877852522924731j)
19531952
1953+
>>> g = pari('2/3')
1954+
>>> complex(g)
1955+
(0.6666666666666666+0j)
1956+
1957+
>>> g = pari.quadgen(-23)
1958+
>>> complex(g)
1959+
(0.5+2.3979157616563596j)
1960+
1961+
>>> g = pari.quadgen(5) + pari('2/3')
1962+
>>> complex(g)
1963+
(2.2847006554165614+0j)
1964+
19541965
>>> g = pari('Mod(3,5)'); g
19551966
Mod(3, 5)
19561967
>>> complex(g)
19571968
Traceback (most recent call last):
19581969
...
1959-
PariError: incorrect type in greal/gimag (t_INTMOD)
1970+
PariError: incorrect type in gtofp (t_INTMOD)
19601971
"""
19611972
cdef double re, im
19621973
sig_on()
1963-
re = gtodouble(greal(self.g))
1964-
im = gtodouble(gimag(self.g))
1965-
sig_off()
1974+
# First convert to floating point (t_REAL or t_COMPLEX)
1975+
# Note: DEFAULTPREC means 64 bits of precision
1976+
fp = gtofp(self.g, DEFAULTPREC)
1977+
if typ(fp) == t_REAL:
1978+
re = rtodbl(fp)
1979+
im = 0
1980+
elif typ(fp) == t_COMPLEX:
1981+
re = gtodouble(gel(fp, 1))
1982+
im = gtodouble(gel(fp, 2))
1983+
else:
1984+
sig_off()
1985+
raise AssertionError("unrecognized output from gtofp()")
1986+
clear_stack()
19661987
return complex(re, im)
19671988

19681989
def __nonzero__(self):

0 commit comments

Comments
 (0)