Skip to content

Commit 65ac2cb

Browse files
committed
gr: Improve conversions
C.f. https://flintlib.org/doc/gr.html#assignment-and-conversions We can use more appropriate functions for conversions than roundtripping through a string
1 parent 7b2c76d commit 65ac2cb

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/flint/types/_gr.pxd

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ from flint.flintlib.functions.gr_domains cimport (
8686
)
8787
from flint.flintlib.functions.gr cimport (
8888
gr_heap_init,
89+
gr_set_d,
90+
gr_set_other,
8991
gr_set_str,
9092
gr_get_str,
9193
gr_set,
@@ -214,6 +216,24 @@ cdef class gr_ctx(flint_ctx):
214216
py_val._init = True
215217
return py_val
216218

219+
@cython.final
220+
cdef inline gr from_d(self, double d):
221+
cdef gr py_val
222+
py_val = self.new_gr()
223+
err = gr_set_d(py_val.pval, d, self.ctx_t)
224+
if err != GR_SUCCESS:
225+
raise self._error(err, "Incorrect conversion from a double")
226+
return py_val
227+
228+
@cython.final
229+
cdef inline gr from_other(self, gr x):
230+
cdef gr py_val
231+
py_val = self.new_gr()
232+
err = gr_set_other(py_val.pval, x.pval, x.ctx.ctx_t, self.ctx_t)
233+
if err != GR_SUCCESS:
234+
raise self._error(err, "Incorrect conversion")
235+
return py_val
236+
217237
@cython.final
218238
cdef inline gr from_str(self, s: str):
219239
cdef gr py_val

src/flint/types/_gr.pyx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,13 @@ cdef class gr_ctx(flint_ctx):
229229
>>> ctx(2)
230230
2
231231
"""
232+
if isinstance(arg, gr):
233+
return self.from_other(arg)
234+
if arg is int:
235+
return self.from_si(arg)
236+
if arg is float:
237+
return self.from_d(arg)
238+
# TODO: fmpz & fmpq ?
232239
try:
233240
return self.from_str(str(arg))
234241
except AssertionError:

0 commit comments

Comments
 (0)