On Jun 16, 7:22 am, Mel <chemmyg...@gmail.com> wrote:
> I do want to convert to an integer in this particular case...but
> integers are rationals, so I don't understand why I don't just get the
> integer 344 when I try the following code:

If you are sure that the element can be represented as an integer,
then just convert to an integer. That will always work:

> sage: K=Qp(7,5)
> sage: Q=QQ
> sage: a=344
> sage: b=K(a)
> sage: a=Q(b) #your error

sage: ZZ(a)
344
sage: ZZ(K(1/5))
6723
sage: c = K(1/21)
sage: c
sage: ZZ(c)
ValueError: negative valuation

If it's not, you can make sure you can:

sage: ZZ(K.prime()^(-c.valuation())*c)*K.prime()^(c.valuation())
11205/7
sage: Q(c)
1/21
sage: K(1/21)-K(11205/7)
O(7^4)

The default choice of conversion from K to Q is apparently to call
"rational reconstruction" (see c.rational_reconstruction) which, as
you observed, tries to find a rational number N/D close to your
element with |N|, |D| bounded by sqrt(p^precision),
i.e., it's trying to use the same number of bits, but equally
distributed over the numerator and denominator.

For an arbitrary p-adic that happens to be meaning to represent a
rational number, this is almost always what you want. If you know you
mean an integer, you're wasting bits on a denominator you want to take
1 anyway, so it's not what you want.

I'm a little on the fence whether rational reconstruction is the best
default conversion for p-adics to Q, since your example shows
sometimes people just want some rational number that lies close to
their p-adic number. If you want to have your cake and eat it too
(i.e., nice reps if they exist and some rep otherwise), just double
the apparent precision:

sage: QQ(Qp(7,2*K.precision_cap())
(b).lift_to_precision(2*b.precision_relative()))
344

-- 
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to