|
| 1 | +/* |
| 2 | + Copyright (C) 2026 Edgar Costa |
| 3 | +
|
| 4 | + This file is part of FLINT. |
| 5 | +
|
| 6 | + FLINT is free software: you can redistribute it and/or modify it under |
| 7 | + the terms of the GNU Lesser General Public License (LGPL) as published |
| 8 | + by the Free Software Foundation; either version 3 of the License, or |
| 9 | + (at your option) any later version. See <https://www.gnu.org/licenses/>. |
| 10 | +*/ |
| 11 | + |
| 12 | +#include "arb.h" |
| 13 | +#include "fmpq.h" |
| 14 | + |
| 15 | +int |
| 16 | +arb_get_simplest_fmpq(fmpq_t res, const arb_t x) |
| 17 | +{ |
| 18 | + arf_t lo_arf, hi_arf; |
| 19 | + fmpq_t lo, hi; |
| 20 | + int negate; |
| 21 | + |
| 22 | + if (!arb_is_finite(x)) |
| 23 | + return 0; |
| 24 | + |
| 25 | + /* Fast path: exact ball. The midpoint is the only element of the |
| 26 | + * interval, so it is trivially the simplest rational. arf is |
| 27 | + * dyadic, so arf_get_fmpq produces the canonical form exactly. */ |
| 28 | + if (arb_is_exact(x)) |
| 29 | + { |
| 30 | + arf_get_fmpq(res, arb_midref(x)); |
| 31 | + return 1; |
| 32 | + } |
| 33 | + |
| 34 | + /* Fast path: 0 lies in the ball. 0/1 has the smallest possible |
| 35 | + * denominator and smallest absolute numerator, so it wins both |
| 36 | + * sub-criteria. arb_contains_zero is an exact predicate on the |
| 37 | + * arf/mag pair, avoiding any fmpq conversion. */ |
| 38 | + if (arb_contains_zero(x)) |
| 39 | + { |
| 40 | + fmpq_zero(res); |
| 41 | + return 1; |
| 42 | + } |
| 43 | + |
| 44 | + /* The remaining intervals are strictly positive or strictly |
| 45 | + * negative. Reduce to the positive case so that |
| 46 | + * fmpq_simplest_between's "smallest value" tie-break agrees with |
| 47 | + * our "smallest absolute numerator" contract on the original. */ |
| 48 | + negate = arb_is_negative(x); |
| 49 | + |
| 50 | + arf_init(lo_arf); |
| 51 | + arf_init(hi_arf); |
| 52 | + fmpq_init(lo); |
| 53 | + fmpq_init(hi); |
| 54 | + |
| 55 | + arb_get_lbound_arf(lo_arf, x, ARF_PREC_EXACT); |
| 56 | + arb_get_ubound_arf(hi_arf, x, ARF_PREC_EXACT); |
| 57 | + arf_get_fmpq(lo, lo_arf); |
| 58 | + arf_get_fmpq(hi, hi_arf); |
| 59 | + |
| 60 | + if (negate) |
| 61 | + { |
| 62 | + fmpq_neg(lo, lo); |
| 63 | + fmpq_neg(hi, hi); |
| 64 | + fmpq_swap(lo, hi); |
| 65 | + } |
| 66 | + |
| 67 | + fmpq_simplest_between(res, lo, hi); |
| 68 | + if (negate) |
| 69 | + fmpq_neg(res, res); |
| 70 | + |
| 71 | + arf_clear(lo_arf); |
| 72 | + arf_clear(hi_arf); |
| 73 | + fmpq_clear(lo); |
| 74 | + fmpq_clear(hi); |
| 75 | + return 1; |
| 76 | +} |
0 commit comments