Sharedsupport / 2016-01-18-110500-docs-exact-rational.sagewsOpen in CoCalc
Examples for support purposes...
(1.0).exact_rational?
File: /projects/sage/sage-6.10/src/sage/rings/real_mpfr.pyx
Signature : (RealNumber('1.0')).exact_rational()
Docstring :
Returns the exact rational representation of this floating-point
number.

EXAMPLES:

   sage: RR(0).exact_rational()
   0
   sage: RR(1/3).exact_rational()
   6004799503160661/18014398509481984
   sage: RR(37/16).exact_rational()
   37/16
   sage: RR(3^60).exact_rational()
   42391158275216203520420085760
   sage: RR(3^60).exact_rational() - 3^60
   6125652559
   sage: RealField(5)(-pi).exact_rational()
   -25/8
(1.0).exact_rational??
   File: /projects/sage/sage-6.10/src/sage/rings/real_mpfr.pyx
   Source:
       def exact_rational(self):
        """
        Returns the exact rational representation of this floating-point
        number.

        EXAMPLES::

            sage: RR(0).exact_rational()
            0
            sage: RR(1/3).exact_rational()
            6004799503160661/18014398509481984
            sage: RR(37/16).exact_rational()
            37/16
            sage: RR(3^60).exact_rational()
            42391158275216203520420085760
            sage: RR(3^60).exact_rational() - 3^60
            6125652559
            sage: RealField(5)(-pi).exact_rational()
            -25/8

        TESTS::

            sage: RR('nan').exact_rational()
            Traceback (most recent call last):
            ...
            ValueError: Cannot convert NaN or infinity to rational number
            sage: RR('-infinity').exact_rational()
            Traceback (most recent call last):
            ...
            ValueError: Cannot convert NaN or infinity to rational number
        """
        if not mpfr_number_p(self.value):
            raise ValueError, 'Cannot convert NaN or infinity to rational number'

        cdef Integer mantissa = Integer()
        cdef mp_exp_t exponent

        if mpfr_sgn(self.value) == 0:
            return Rational(0)

        exponent = mpfr_get_z_exp(mantissa.value, self.value)

        return Rational(mantissa) * Integer(2) ** exponent