Ticket #12662: trac_12662-qqbar-doctest.patch

File trac_12662-qqbar-doctest.patch, 123.8 KB (added by davidloeffler, 9 years ago)

Patch against 5.0.beta7

  • sage/rings/qqbar.py

    # HG changeset patch
    # User David Loeffler <d.loeffler.01@cantab.net>
    # Date 1331658315 0
    # Node ID 35b6a96717ec281de2d1042d91970a29b821bdcf
    # Parent  68e89260148df131fec1708338ceba3ea964b2bb
    #12662: doctest coverage for QQbar
    
    diff --git a/sage/rings/qqbar.py b/sage/rings/qqbar.py
    a b  
    99This is an implementation of the algebraic numbers (the complex
    1010numbers which are the zero of a polynomial in `\ZZ[x]`; in other
    1111words, the algebraic closure of `\QQ`, with an embedding into `\CC`).
    12 All computations are exact.  We also include an implementation of the
     12All computations are exact. We also include an implementation of the
    1313algebraic reals (the intersection of the algebraic numbers with
    14 `\RR`).  The field of algebraic numbers `\QQbar` is available with
     14`\RR`). The field of algebraic numbers `\QQbar` is available with
    1515abbreviation ``QQbar``; the field of algebraic reals has abbreviation
    1616``AA``.
    1717
     
    4646The multiplicative subgroup of the algebraic numbers generated
    4747by the rational numbers and the roots of unity is handled particularly
    4848efficiently, as long as these roots of unity come from the ``QQbar.zeta()``
    49 method.  Cyclotomic fields in general are fairly efficient, again
     49method. Cyclotomic fields in general are fairly efficient, again
    5050as long as they are derived from ``QQbar.zeta()``.
    5151
    5252An algebraic number can be coerced into ``ComplexIntervalField`` (or
    5353``RealIntervalField``, for algebraic reals); every algebraic number has a
    5454cached interval of the highest precision yet calculated.
    5555
    56 Everything is done with intervals except for comparisons.  By default,
     56Everything is done with intervals except for comparisons. By default,
    5757comparisons compute the two algebraic numbers with 128-bit precision
    5858intervals; if this does not suffice to prove that the numbers are different,
    5959then we fall back on exact computation.
     
    8181For a monic cubic polynomial `x^3 + bx^2 + cx + d` with roots `s1`,
    8282`s2`, `s3`, the discriminant is defined as
    8383`(s1-s2)^2(s1-s3)^2(s2-s3)^2` and can be computed as `b^2c^2 - 4b^3d -
    84 4c^3 + 18bcd - 27d^2`.  We can test that these definitions do give the
     844c^3 + 18bcd - 27d^2`. We can test that these definitions do give the
    8585same result::
    8686
    8787    sage: def disc1(b, c, d):
     
    153153    sage: QQbar(-1)^(1/3)
    154154    0.500000000000000? + 0.866025403784439?*I
    155155
    156 We can explicitly coerce from `\QQ[I]`.  (Technically, this is not quite
     156We can explicitly coerce from `\QQ[I]`. (Technically, this is not quite
    157157kosher, since `\QQ[I]` doesn't come with an embedding; we do not know
    158 whether the field generator is supposed to map to `+I` or `-I`.  We assume
     158whether the field generator is supposed to map to `+I` or `-I`. We assume
    159159that for any quadratic field with polynomial `x^2+1`, the generator maps
    160160to `+I`.)::
    161161
     
    286286    4*zeta60^15 + 5*zeta60^12 + 9*zeta60^10 + 20*zeta60^3 - 3 where a^16 + a^14 - a^10 - a^8 - a^6 + a^2 + 1 = 0 and a in 0.994521895368274? + 0.1045284632676535?*I
    287287
    288288The paper "ARPREC: An Arbitrary Precision Computation Package" by
    289 Bailey, Yozo, Li and Thompson discusses this result.  Evidently it is
     289Bailey, Yozo, Li and Thompson discusses this result. Evidently it is
    290290difficult to find, but we can easily verify it. ::
    291291
    292292    sage: alpha = QQbar.polynomial_root(x^10 + x^9 - x^7 - x^6 - x^5 - x^4 - x^3 + x + 1, RIF(1, 1.2))
     
    308308    -242494609856316402264822833062350847769474540*a^9 + 862295472068289472491654837785947906234680703*a^8 - 829559238431038252116584538075753012193290520*a^7 - 125882239615006638366472766103700441555126185*a^6 + 1399067970863104691667276008776398309383579345*a^5 - 1561176687069361567616835847286958553574223422*a^4 + 761706318888840943058230840550737823821027895*a^3 + 580740464974951394762758666210754821723780266*a^2 - 954587496403409756503464154898858512440951323*a + 546081123623099782018260884934770383777092602 where a^10 - 4*a^9 + 5*a^8 - a^7 - 6*a^6 + 9*a^5 - 6*a^4 - a^3 + 5*a^2 - 4*a + 1 = 0 and a in 0.4440633440090926?
    309309
    310310Given an algebraic number, we can produce a string that will reproduce
    311 that algebraic number if you type the string into Sage.  We can see
     311that algebraic number if you type the string into Sage. We can see
    312312that until exact computation is triggered, an algebraic number keeps
    313313track of the computation steps used to produce that number::
    314314
     
    343343
    344344Note that the ``verify=True`` argument to ``sage_input`` will always trigger
    345345exact computation, so running ``sage_input`` twice in a row on the same number
    346 will actually give different answers.  In the following, running ``sage_input``
     346will actually give different answers. In the following, running ``sage_input``
    347347on ``n`` will also trigger exact computation on ``rt2``, as you can see by the
    348348fact that the third output is different than the first::
    349349
     
    432432
    433433We can convert elements of ``QQbar`` and ``AA`` into the following
    434434types: ``float``, ``complex``, ``RDF``, ``CDF``, ``RR``, ``CC``,
    435 ``RIF``, ``CIF``, ``ZZ``, and ``QQ``, with a few exceptions.  (For the
     435``RIF``, ``CIF``, ``ZZ``, and ``QQ``, with a few exceptions. (For the
    436436arbitrary-precision types, ``RR``, ``CC``, ``RIF``, and ``CIF``, it
    437437can convert into a field of arbitrary precision.)
    438438
    439439Converting from ``QQbar`` to a real type (``float``, ``RDF``, ``RR``,
    440440``RIF``, ``ZZ``, or ``QQ``) succeeds only if the ``QQbar`` is actually
    441 real (has an imaginary component of exactly zero).  Converting from
     441real (has an imaginary component of exactly zero). Converting from
    442442either ``AA`` or ``QQbar`` to ``ZZ`` or ``QQ`` succeeds only if the
    443 number actually is an integer or rational.  If conversion fails, a
     443number actually is an integer or rational. If conversion fails, a
    444444ValueError will be raised.
    445445
    446446Here are examples of all of these conversions::
     
    476476
    477477TESTS:
    478478
    479 Verify that trac 10981 is fixed::
     479Verify that :trac:`10981` is fixed::
    480480
    481481    sage: x = AA['x'].gen()
    482482    sage: P = 1/(1+x^4)
     
    525525
    526526is_SymbolicExpressionRing = None
    527527
    528 def late_import():
     528def _late_import():
     529    r"""
     530    Import the name "is_SymbolicExpressionRing" (which would cause an infinite
     531    loop if imported at startup time).
     532
     533    EXAMPLE::
     534
     535        sage: sage.rings.qqbar._late_import()
     536        sage: sage.rings.qqbar.is_SymbolicExpressionRing == sage.symbolic.ring.is_SymbolicExpressionRing
     537        True
     538    """
    529539    global is_SymbolicExpressionRing
    530540    if is_SymbolicExpressionRing is None:
    531541        import sage.symbolic.ring
    532542        is_SymbolicExpressionRing = sage.symbolic.ring.is_SymbolicExpressionRing
    533543
    534544class AlgebraicField_common(sage.rings.ring.Field):
     545    r"""
     546    Common base class for the classes :class:`~AlgebraicRealField` and
     547    :class:`~AlgebraicField`.
     548    """
     549
    535550    def default_interval_prec(self):
     551        r"""
     552        Return the default interval precision used for root isolation.
     553
     554        EXAMPLES::
     555
     556            sage: AA.default_interval_prec()
     557            64
     558        """
     559
    536560        return 64
    537561
    538562    def is_finite(self):
     563        r"""
     564        Check whether this field is finite. Since this class is only used for
     565        fields of characteristic 0, always returns False.
     566
     567        EXAMPLE::
     568
     569            sage: QQbar.is_finite()
     570            False
     571        """
    539572        return False
    540573
    541574    def characteristic(self):
     575        r"""
     576        Return the characteristic of this field. Since this class is only used
     577        for fields of characteristic 0, always returns 0.
     578
     579        EXAMPLES::
     580
     581            sage: AA.characteristic()
     582            0
     583        """
    542584        return sage.rings.integer.Integer(0)
    543585
    544586    def order(self):
     587        r"""
     588        Return the cardinality of self. Since this class is only used for
     589        fields of characteristic 0, always returns Infinity.
     590
     591        EXAMPLE::
     592
     593            sage: QQbar.order()
     594            +Infinity
     595        """
    545596        return infinity.infinity
    546597
    547598    def common_polynomial(self, poly):
    548599        """
    549600        Given a polynomial with algebraic coefficients, returns a
    550601        wrapper that caches high-precision calculations and
    551         factorizations.  This wrapper can be passed to polynomial_root
     602        factorizations. This wrapper can be passed to polynomial_root
    552603        in place of the polynomial.
    553604
    554605        Using ``common_polynomial`` makes no semantic difference, but will
     
    589640class AlgebraicRealField(_uniq_alg_r, AlgebraicField_common):
    590641    r"""
    591642    The field of algebraic reals.
     643
     644    TESTS::
     645
     646        sage: AA == loads(dumps(AA))
     647        True
    592648    """
    593649
    594650    def __init__(self):
     651        r"""
     652        Standard initialization function.
     653
     654        EXAMPLE:
     655
     656        This function calls functions in superclasses which set the category, so we check that.
     657
     658            sage: QQbar.category() # indirect doctest
     659            Category of fields
     660        """
    595661        AlgebraicField_common.__init__(self, self, ('x',), normalize=False)
    596662
    597663    def _element_constructor_(self, x):
    598664        r"""
    599         Coerce ``x`` into the field of algebraic real numbers.
    600 
    601         """
    602 
     665        Construct an element of the field of algebraic real numbers from ``x``.
     666
     667        EXAMPLE::
     668
     669            sage: QQbar(sqrt(2)) in AA # indirect doctest
     670            True
     671            sage: QQbar(I) in AA
     672            False
     673            sage: AA in AA
     674            False
     675
     676        The following should both return True (this is a bug). ::
     677
     678            sage: sqrt(2) in AA # not tested
     679            False
     680            sage: K.<z> = CyclotomicField(5); z + 1/z in AA # not tested
     681            False
     682        """
    603683        if isinstance(x, AlgebraicReal):
    604684            return x
    605685        elif isinstance(x, AlgebraicNumber):
    606686            if x.imag().is_zero():
    607687                return x.real()
    608688            else:
    609                 raise ValueError, "Cannot coerce algebraic number with non-zero imaginary part to algebraic real"
     689                raise ValueError("Cannot coerce algebraic number with non-zero imaginary part to algebraic real")
    610690        elif hasattr(x, '_algebraic_'):
    611691            return x._algebraic_(AA)
    612692        return AlgebraicReal(x)
    613693
    614694    def _repr_(self):
     695        r"""
     696        String representation of self.
     697
     698        EXAMPLE::
     699
     700            sage: AA._repr_()
     701            'Algebraic Real Field'
     702        """
    615703        return "Algebraic Real Field"
    616704
    617705    # Is there a standard representation for this?
    618706    def _latex_(self):
     707        r"""
     708        Latex representation of self.
     709
     710        EXAMPLE::
     711
     712            sage: AA._latex_()
     713            '\\mathbf{A}'
     714        """
    619715        return "\\mathbf{A}"
    620716
    621717    def _sage_input_(self, sib, coerce):
     
    639735
    640736        TESTS::
    641737
    642             sage: AA.has_coerce_map_from(ZZ)
     738            sage: AA.has_coerce_map_from(ZZ) # indirect doctest
    643739            True
    644740            sage: K.<a> = QuadraticField(7, embedding=AA(7).sqrt()); AA.has_coerce_map_from(K)
    645741            True
     
    655751        return False
    656752
    657753    def completion(self, p, prec, extras = {}):
    658         """
     754        r"""
     755        Return the completion of self at the place `p`. Only implemented for `p
     756        = \infty` at present.
     757
     758        INPUT:
     759
     760        - ``p`` -- either a prime (not implemented at present) or Infinity
     761        - ``prec`` -- precision of approximate field to return
     762        - ``extras`` -- a dict of extra keyword arguments for the ``RealField``
     763          constructor
     764
    659765        EXAMPLES::
    660766
    661767            sage: AA.completion(infinity, 500)
     
    677783           
    678784    def algebraic_closure(self):
    679785        """
     786        Return the algebraic closure of this field, which is the field
     787        `\overline{\QQ}` of algebraic numbers.
     788
    680789        EXAMPLES::
    681790
    682791            sage: AA.algebraic_closure()
     
    684793        """
    685794        return QQbar
    686795
    687     def _is_valid_homomorphism_(self, codomain, im_gens):
    688         try:
    689             return im_gens[0] == codomain._coerce_(self.gen(0))
    690         except TypeError:
    691             return False
    692 
    693     def gens(self):
    694         return (self(1), )
    695 
    696     def gen(self, n=0):
    697         if n == 0:
    698             return self(1)
    699         else:
    700             raise IndexError, "n must be 0"
    701 
    702     def ngens(self):
    703         return 1
     796# These functions make no mathematical sense so I commented them out -- DL
     797#
     798#    def _is_valid_homomorphism_(self, codomain, im_gens):
     799#        r"""
     800#        Attempt to construct a homomorphism from self to codomain sending the
     801#        generators to ``im_gens``. Since this field is not finitely generated,
     802#        this cannot be implemented in a mathematically sensible way; this
     803#        function is provided for compatibility with number fields.
     804#        """
     805#        try:
     806#            return im_gens[0] == codomain._coerce_(self.gen(0))
     807#        except TypeError:
     808#            return False
     809#
     810#    def gens(self):
     811#        return (self(1), )
     812#
     813#    def gen(self, n=0):
     814#        if n == 0:
     815#            return self(1)
     816#        else:
     817#            raise IndexError, "n must be 0"
     818#
     819#    def ngens(self):
     820#        return 1
    704821
    705822    def is_atomic_repr(self):
     823        r"""
     824        Check whether elements of this field have atomic string
     825        representations. Returns True.
     826
     827        EXAMPLE::
     828
     829            sage: AA.is_atomic_repr()
     830            True
     831        """
    706832        return True
    707833
    708834    def zeta(self, n=2):
     835        r"""
     836        Return an `n`-th root of unity in this field. This will raise a
     837        ``ValueError`` if `n \ne \{1, 2\}` since no such root exists.
     838
     839        INPUT:
     840
     841        - ``n`` (integer) -- default 2
     842
     843        EXAMPLE::
     844
     845            sage: AA.zeta(1)
     846            1
     847            sage: AA.zeta(2)
     848            -1
     849            sage: AA.zeta()
     850            -1
     851            sage: AA.zeta(3)
     852            Traceback (most recent call last):
     853            ...
     854            ValueError: no n-th root of unity in algebraic reals
     855
     856        Some silly inputs::
     857
     858            sage: AA.zeta(Mod(-5, 7))
     859            -1
     860            sage: AA.zeta(0)
     861            Traceback (most recent call last):
     862            ...
     863            ValueError: no n-th root of unity in algebraic reals
     864        """
    709865        if n == 1:
    710866            return self(1)
    711867        elif n == 2:
    712868            return self(-1)
    713869        else:
    714             raise ValueError, "no n-th root of unity in algebraic reals"
     870            raise ValueError("no n-th root of unity in algebraic reals")
    715871
    716872    def polynomial_root(self, poly, interval, multiplicity=1):
    717873        r"""
     
    721877
    722878        The polynomial need not be irreducible, or even squarefree; but
    723879        if the given root is a multiple root, its multiplicity must be
    724         specified.  (IMPORTANT NOTE: Currently, multiplicity-`k` roots
     880        specified. (IMPORTANT NOTE: Currently, multiplicity-`k` roots
    725881        are handled by taking the `(k-1)`-st derivative of the polynomial.
    726882        This means that the interval must enclose exactly one root
    727883        of this derivative.)
     
    764920            2.000000000000000?
    765921        """
    766922        if not is_RealIntervalFieldElement(interval):
    767             raise ValueError, "interval argument of .polynomial_root on algebraic real field must be real"
     923            raise ValueError("interval argument of .polynomial_root on algebraic real field must be real")
    768924
    769925        return AlgebraicReal(ANRoot(poly, interval, multiplicity))
    770926
    771927def is_AlgebraicRealField(F):
     928    r"""
     929    Check whether ``F`` is an :class:`~AlgebraicRealField` instance. For internal use.
     930
     931    EXAMPLE::
     932
     933        sage: from sage.rings.qqbar import is_AlgebraicRealField
     934        sage: [is_AlgebraicRealField(x) for x in [AA, QQbar, None, 0, "spam"]]
     935        [True, False, False, False, False]
     936    """
    772937    return isinstance(F, AlgebraicRealField)
    773938
     939# Create the globally unique AlgebraicRealField object.
    774940AA = AlgebraicRealField()
    775941
    776942class AlgebraicField(_uniq_alg, AlgebraicField_common):
    777943    """
    778     The field of algebraic numbers.
     944    The field of all algebraic complex numbers.
    779945    """
    780946
    781947    def __init__(self):
     948        r"""
     949        Standard init function.
     950
     951        We test by setting the category::
     952
     953            sage: QQbar.category() # indirect doctest
     954            Category of fields
     955            sage: QQbar.base_ring()
     956            Algebraic Real Field
     957        """
    782958        AlgebraicField_common.__init__(self, AA, ('I',), normalize=False)
    783959
    784960    def _element_constructor_(self, x):
    785961        """
    786         Coerce x into the field of algebraic numbers.
    787 
    788         """
    789 
     962        Try to construct an element of the field of algebraic numbers from `x`.
     963
     964        EXAMPLES::
     965
     966            sage: sqrt(2) in QQbar # indirect doctest
     967            True
     968            sage: 22/7 in QQbar
     969            True
     970            sage: pi in QQbar
     971            False
     972        """
    790973        if isinstance(x, AlgebraicNumber):
    791974            return x
    792975        elif isinstance(x, AlgebraicReal):
     
    796979        return AlgebraicNumber(x)
    797980
    798981    def _repr_(self):
     982        r"""
     983        String representation of self.
     984
     985        EXAMPLE::
     986
     987            sage: QQbar._repr_()
     988            'Algebraic Field'
     989        """
    799990        return "Algebraic Field"
    800991
    801992    def _latex_(self):
     993        r"""
     994        Latex representation of self.
     995
     996        EXAMPLE::
     997
     998            sage: QQbar._latex_()
     999            '\\overline{\\QQ}'
     1000        """
    8021001        return "\\overline{\\QQ}"
    8031002
    8041003    def _sage_input_(self, sib, coerce):
     
    8171016        return sib.name('QQbar')
    8181017
    8191018    def _coerce_map_from_(self, from_par):
     1019        r"""
     1020        Set up the coercion model.
     1021
     1022        TESTS::
     1023
     1024            sage: QQbar.has_coerce_map_from(ZZ) # indirect doctest
     1025            True
     1026            sage: QQbar.has_coerce_map_from(AA)
     1027            True
     1028            sage: QQbar.has_coerce_map_from(CC)
     1029            False
     1030        """
    8201031        if from_par == ZZ or from_par == QQ or from_par == int or from_par == long:
    8211032            return True
    8221033        if from_par == AA or from_par == QQbar:
    8231034            return True
    824         late_import()
     1035        _late_import()
    8251036        if is_SymbolicExpressionRing(from_par):
    8261037            return True
    8271038        return False
    8281039
    8291040    def completion(self, p, prec, extras = {}):
    830         """
     1041        r"""
     1042        Return the completion of self at the place `p`. Only implemented for `p
     1043        = \infty` at present.
     1044
     1045        INPUT:
     1046
     1047        - ``p`` -- either a prime (not implemented at present) or Infinity
     1048        - ``prec`` -- precision of approximate field to return
     1049        - ``extras`` -- a dict of extra keyword arguments for the ``RealField``
     1050          constructor
     1051
    8311052        EXAMPLES::
    8321053
    8331054            sage: QQbar.completion(infinity, 500)
     
    8491070           
    8501071    def algebraic_closure(self):
    8511072        """
     1073        Return the algebraic closure of this field. As this field is already
     1074        algebraically closed, just returns self.
     1075
    8521076        EXAMPLES::
    8531077
    8541078            sage: QQbar.algebraic_closure()
     
    8581082   
    8591083    def construction(self):
    8601084        """
     1085        Return a functor that constructs self (used by the coercion machinery).
     1086
    8611087        EXAMPLE::
    8621088
    8631089            sage: QQbar.construction()
     
    8671093        from sage.all import QQ
    8681094        return (AlgebraicClosureFunctor(), QQ)
    8691095
    870     def gens(self):
    871         return(QQbar_I, )
    872 
    873     def gen(self, n=0):
    874         if n == 0:
    875             return QQbar_I
    876         else:
    877             raise IndexError, "n must be 0"
    878 
    879     def ngens(self):
    880         return 1
     1096# more nonsense -- DL
     1097#
     1098#    def gens(self):
     1099#        return(QQbar_I, )
     1100#
     1101#    def gen(self, n=0):
     1102#        if n == 0:
     1103#            return QQbar_I
     1104#        else:
     1105#            raise IndexError("n must be 0")
     1106#
     1107#    def ngens(self):
     1108#        return 1
    8811109
    8821110    def is_atomic_repr(self):
     1111        r"""
     1112        Check whether elements of this field have atomic string representations. Returns False.
     1113
     1114        EXAMPLE::
     1115
     1116            sage: QQbar.is_atomic_repr()
     1117            False
     1118        """
    8831119        return False
    8841120
    8851121    def zeta(self, n=4):
    8861122        r"""
    8871123        Returns a primitive `n`'th root of unity, specifically `\exp(2*\pi*i/n)`.
    8881124
     1125        INPUT:
     1126
     1127        - ``n`` (integer) -- default 4
     1128
    8891129        EXAMPLES::
    8901130
    8911131            sage: QQbar.zeta(1)
     
    9131153
    9141154        The polynomial need not be irreducible, or even squarefree; but
    9151155        if the given root is a multiple root, its multiplicity must be
    916         specified.  (IMPORTANT NOTE: Currently, multiplicity-`k` roots
     1156        specified. (IMPORTANT NOTE: Currently, multiplicity-`k` roots
    9171157        are handled by taking the `(k-1)`-st derivative of the polynomial.
    9181158        This means that the interval must enclose exactly one root
    9191159        of this derivative.)
     
    9521192       
    9531193        INPUT:
    9541194       
    955         - ``poly_degree`` - default: 2 - degree of the random
    956           polynomial over the integers of which the returned
    957           algebraic number is a root.  This is not the degree of
    958           the minimal polynomial of the number. Increase this
    959           parameter to achieve a greater diversity of algebraic
    960           numbers, at a cost of greater computation time. You can
    961           also vary the distribution of the coefficients but that
    962           will not vary the degree of the extension containing
    963           the element.
     1195        - ``poly_degree`` - default: 2 - degree of the random polynomial over
     1196          the integers of which the returned algebraic number is a root. This
     1197          is not necessarily the degree of the minimal polynomial of the
     1198          number. Increase this parameter to achieve a greater diversity of
     1199          algebraic numbers, at a cost of greater computation time. You can
     1200          also vary the distribution of the coefficients but that will not vary
     1201          the degree of the extension containing the element.
    9641202         
    965         - ``args``, ``kwds`` - arguments and keywords passed to
    966           the random number generator for elements of ``ZZ``, the
    967           integers.  See
    968           :meth:`~sage.rings.integer_ring.IntegerRing_class.random_element`
    969           for details, or see example below.
     1203        - ``args``, ``kwds`` - arguments and keywords passed to the random
     1204          number generator for elements of ``ZZ``, the integers. See
     1205          :meth:`~sage.rings.integer_ring.IntegerRing_class.random_element` for
     1206          details, or see example below.
    9701207         
    9711208        OUTPUT:
    9721209       
    973         An element of ``QQbar``, the field of algebraic
    974         numbers (see :mod:`sage.rings.qqbar`).
     1210        An element of ``QQbar``, the field of algebraic numbers (see
     1211        :mod:`sage.rings.qqbar`).
    9751212       
    9761213        ALGORITHM:
    9771214       
    9781215        A polynomial with degree between 1 and ``poly_degree``,
    979         with random integer coefficients is created.  A root of this
    980         polynomial is chosen at random.  The default degree is
     1216        with random integer coefficients is created. A root of this
     1217        polynomial is chosen at random. The default degree is
    9811218        2 and the integer coefficients come from a distribution
    982         heavily weighted towards $0, \pm 1, \pm 2$.
     1219        heavily weighted towards `0, \pm 1, \pm 2`.
    9831220       
    9841221        EXAMPLES::
    9851222       
     
    9971234       
    9981235        Parameters for the distribution of the integer coefficients
    9991236        of the polynomials can be passed on to the random element method
    1000         for integers.  For example, current default behavior of this method
     1237        for integers. For example, current default behavior of this method
    10011238        returns zero about 15% of the time; if we do not include zero as a
    10021239        possible coefficient, there will never be a zero constant term, and
    10031240        thus never a zero root. ::
     
    10061243            sage: QQbar(0) in z
    10071244            False
    10081245           
    1009          If you just want real algebraic numbers you can filter them out. 
     1246         If you just want real algebraic numbers you can filter them out.
    10101247         Using an odd degree for the polynomials will insure some degree of
    1011          success.  ::
     1248         success. ::
    10121249         
    10131250            sage: r = []
    10141251            sage: while len(r) < 3:
     
    10301267            ValueError: polynomial degree must be greater than zero, not 0
    10311268           
    10321269        Random vectors already have a 'degree' keyword, so
    1033         we cannot use that for the polynomial's degree.  ::
     1270        we cannot use that for the polynomial's degree. ::
    10341271       
    10351272            sage: v = random_vector(QQbar, degree=2, poly_degree=3)
    10361273            sage: v                                 # random
     
    10631300        return roots[m]
    10641301
    10651302def is_AlgebraicField(F):
     1303    r"""
     1304    Check whether ``F`` is an :class:`~AlgebraicField` instance.
     1305
     1306    EXAMPLE::
     1307
     1308        sage: from sage.rings.qqbar import is_AlgebraicField
     1309        sage: [is_AlgebraicField(x) for x in [AA, QQbar, None, 0, "spam"]]
     1310        [False, True, False, False, False]
     1311    """
    10661312    return isinstance(F, AlgebraicField)
    10671313
     1314# Create the globally unique AlgebraicField object.
    10681315QQbar = AlgebraicField()
    10691316
    10701317def is_AlgebraicField_common(F):
     1318    r"""
     1319    Check whether ``F`` is an :class:`~AlgebraicField_common` instance.
     1320
     1321    EXAMPLE::
     1322
     1323        sage: from sage.rings.qqbar import is_AlgebraicField_common
     1324        sage: [is_AlgebraicField_common(x) for x in [AA, QQbar, None, 0, "spam"]]
     1325        [True, True, False, False, False]
     1326    """
    10711327    return isinstance(F, AlgebraicField_common)
    10721328
    10731329def prec_seq():
     1330    r"""
     1331    Return a generator object which iterates over an infinite increasing
     1332    sequence of precisions to be tried in various numerical computations.
     1333
     1334    Currently just returns powers of 2 starting at 64.
     1335
     1336    EXAMPLE::
     1337
     1338        sage: g = sage.rings.qqbar.prec_seq()
     1339        sage: [g.next(), g.next(), g.next()]
     1340        [64, 128, 256]
     1341    """
    10741342    # XXX Should do some testing to see where the efficiency breaks are
    1075     # in MPFR.  We could also test variants like "bits = bits + bits // 2"
     1343    # in MPFR. We could also test variants like "bits = bits + bits // 2"
    10761344    # (I think this is what MPFR uses internally).
    10771345    bits = 64
    10781346    while True:
     
    10801348        bits = bits * 2
    10811349
    10821350_short_prec_seq = (64, 128, None)
    1083 def short_prec_seq(): return _short_prec_seq
     1351def short_prec_seq():
     1352    r"""
     1353    Return a sequence of precisions to try in cases when an infinite-precision
     1354    computation is possible: returns a couple of small powers of 2 and then
     1355    ``None``.
     1356
     1357    EXAMPLE::
     1358
     1359        sage: from sage.rings.qqbar import short_prec_seq
     1360        sage: short_prec_seq()
     1361        (64, 128, None)
     1362    """
     1363    return _short_prec_seq
    10841364
    10851365def tail_prec_seq():
     1366    r"""
     1367    A generator over precisions larger than those in :func:`~short_prec_seq`.
     1368
     1369    EXAMPLE::
     1370
     1371        sage: from sage.rings.qqbar import tail_prec_seq
     1372        sage: g = tail_prec_seq()
     1373        sage: [g.next(), g.next(), g.next()]
     1374        [256, 512, 1024]
     1375    """
    10861376    bits = 256
    10871377    while True:
    10881378        yield bits
     
    10901380
    10911381def rational_exact_root(r, d):
    10921382    r"""
    1093     Checks whether the rational `r` is an exact `d`'th power.  If so, returns
     1383    Checks whether the rational `r` is an exact `d`'th power. If so, returns
    10941384    the `d`'th root of `r`; otherwise, returns None.
    10951385
    10961386    EXAMPLES::
     
    11131403def clear_denominators(poly):
    11141404    """
    11151405    Takes a monic polynomial and rescales the variable to get a monic
    1116     polynomial with "integral" coefficients.  Works on any univariate
     1406    polynomial with "integral" coefficients. Works on any univariate
    11171407    polynomial whose base ring has a ``denominator()`` method that returns
    11181408    integers; for example, the base ring might be `\QQ` or a number
    11191409    field.
     
    11641454    return change, poly
    11651455
    11661456def do_polred(poly):
    1167     r""" Find the polynomial of lowest discriminant that generates the
    1168     same field as poly, out of those returned by the Pari ``polred``
    1169     routine.  Returns a triple: (``elt_fwd``, ``elt_back``,
    1170     ``new_poly``), where ``new_poly`` is the new polynomial,
    1171     ``elt_fwd`` is a polynomial expression for a root of the new
    1172     polynomial in terms of a root of the original polynomial, and
    1173     ``elt_back`` is a polynomial expression for a root of the original
    1174     polynomial in terms of a root of the new polynomial.
     1457    r"""
     1458    Find the polynomial of lowest discriminant that generates the same field as
     1459    poly, out of those returned by the Pari ``polred`` routine.
     1460
     1461    Returns a triple (``elt_fwd``, ``elt_back``, ``new_poly``), where:
     1462
     1463    * ``new_poly`` is the new polynomial,
     1464    * ``elt_fwd`` is a polynomial expression
     1465      for a root of the new polynomial in terms of a root of the original
     1466      polynomial,
     1467    * ``elt_back`` is a polynomial expression for a root of the original
     1468      polynomial in terms of a root of the new polynomial.
    11751469
    11761470    EXAMPLES::
    11771471
     
    12451539        ifld = intv.parent()
    12461540
    12471541        # We need to verify that pol has exactly one root in the
    1248         # interval intv.  We know (because it is a precondition of
     1542        # interval intv. We know (because it is a precondition of
    12491543        # calling this function) that it has at least one root in the
    12501544        # interval, so we only need to verify that it has at most one
    12511545        # root (that the interval is sufficiently narrow).
    12521546
    12531547        # We do this by computing the derivative of the polynomial
    1254         # over the interval.  If the derivative is bounded away from zero,
     1548        # over the interval. If the derivative is bounded away from zero,
    12551549        # then we know there can be at most one root.
    12561550
    12571551        if not dpol(intv).contains_zero():
     
    12591553
    12601554def find_zero_result(fn, l):
    12611555    """
    1262     ``l`` is a list of some sort.  ``fn`` is a function which maps an element
    1263     of ``l`` and a precision into an interval (either real or complex) of
    1264     that precision, such that for sufficient precision, exactly one
    1265     element of ``l`` results in an interval containing 0.  Returns that
    1266     one element of ``l``.
     1556    ``l`` is a list of some sort. ``fn`` is a function which maps an element of
     1557    ``l`` and a precision into an interval (either real or complex) of that
     1558    precision, such that for sufficient precision, exactly one element of ``l``
     1559    results in an interval containing 0. Returns that one element of ``l``.
    12671560
    12681561    EXAMPLES::
    12691562
     
    12961589    r"""
    12971590    If the interval ``v`` (which may be real or complex) includes some
    12981591    purely real numbers, return ``v'`` containing ``v`` such that
    1299     ``v' == v'.conjugate()``.  Otherwise return ``v`` unchanged. (Note that if
     1592    ``v' == v'.conjugate()``. Otherwise return ``v`` unchanged. (Note that if
    13001593    ``v' == v'.conjugate()``, and ``v'`` includes one non-real root of a real
    13011594    polynomial, then ``v'`` also includes the conjugate of that root.
    13021595    Also note that the diameter of the return value is at most twice
     
    13261619def conjugate_shrink(v):
    13271620    r"""
    13281621    If the interval ``v`` includes some purely real numbers, return
    1329     a real interval containing only those real numbers.  Otherwise
     1622    a real interval containing only those real numbers. Otherwise
    13301623    return ``v`` unchanged.
    13311624
    13321625    If ``v`` includes exactly one root of a real polynomial, and ``v`` was
     
    14891782
    14901783    Note that for the first example, where \sage doesn't realize that
    14911784    the number is real, we get a homomorphism to ``QQbar``; but with
    1492     ``minimal=True``, we get a homomorphism to ``AA``.  Also note
     1785    ``minimal=True``, we get a homomorphism to ``AA``. Also note
    14931786    that the exact answer depends on a Pari function that gives
    14941787    different answers for 32-bit and 64-bit machines::
    14951788
     
    15531846    extensions.
    15541847    """
    15551848    def __init__(self, child1, child1_poly, child2, child2_poly, parent):
     1849        r"""
     1850        EXAMPLE::
     1851
     1852            sage: from sage.rings.qqbar import AlgebraicGeneratorRelation
     1853            sage: c = AlgebraicGeneratorRelation(None, None, None, None, None)
     1854            sage: c
     1855            <class 'sage.rings.qqbar.AlgebraicGeneratorRelation'>
     1856        """
    15561857        self.child1 = child1
    15571858        self.child1_poly = child1_poly
    15581859        self.child2 = child2
     
    15641865class AlgebraicGenerator(SageObject):
    15651866    r"""
    15661867    An ``AlgebraicGenerator`` represents both an algebraic number `\alpha` and
    1567     the number field `\QQ[\alpha]`.  There is a single ``AlgebraicGenerator``
     1868    the number field `\QQ[\alpha]`. There is a single ``AlgebraicGenerator``
    15681869    representing `\QQ` (with `\alpha=0`).
    15691870
    15701871    The ``AlgebraicGenerator`` class is private, and should not be used
     
    16251926        return (AlgebraicGenerator, (self._field, self._root))
    16261927
    16271928    def __hash__(self):
     1929        r"""
     1930        Return a hash value for self. This will depend on the order that
     1931        commands get executed at load time, so we do not test the value that is
     1932        returned, just that it doesn't raise an error.
     1933
     1934        EXAMPLE::
     1935
     1936            sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator
     1937            sage: _.<y> = QQ['y']
     1938            sage: x = polygen(QQbar)
     1939            sage: nf = NumberField(y^2 - y - 1, name='a', check=False)
     1940            sage: root = ANRoot(x^2 - x - 1, RIF(1, 2))
     1941            sage: gen = AlgebraicGenerator(nf, root)
     1942            sage: hash(gen) # random
     1943        """
    16281944        return self._index
    16291945
    16301946    def __cmp__(self, other):
     1947        r"""
     1948        Compare self with another AlgebraicGenerator object.
     1949
     1950        EXAMPLE::
     1951
     1952            sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator
     1953            sage: _.<y> = QQ['y']
     1954            sage: x = polygen(QQbar)
     1955            sage: nf = NumberField(y^2 - y - 1, name='a', check=False)
     1956            sage: root = ANRoot(x^2 - x - 1, RIF(1, 2))
     1957            sage: gen = AlgebraicGenerator(nf, root)
     1958            sage: gen.__cmp__(qq_generator)
     1959            1
     1960        """
    16311961        return cmp(self._index, other._index)
    16321962
    16331963    def set_cyclotomic(self, n):
     1964        r"""
     1965        Store the fact that this is generator for a cyclotomic field.
     1966
     1967        EXAMPLE::
     1968
     1969            sage: y = sage.rings.qqbar.cyclotomic_generator(5) # indirect doctest
     1970            sage: y._cyclotomic
     1971            True
     1972        """
    16341973        self._cyclotomic = True
    16351974        self._cyclotomic_order = ZZ(n)
    16361975
    16371976    def is_complex(self):
     1977        r"""
     1978        Return True if this is a generator for a non-real number field.
     1979
     1980        EXAMPLE::
     1981
     1982            sage: sage.rings.qqbar.cyclotomic_generator(7).is_complex()
     1983            True
     1984            sage: sage.rings.qqbar.qq_generator.is_complex()
     1985            False
     1986        """
    16381987        return self._root.is_complex()
    16391988
    16401989    def _repr_(self):
     1990        r"""
     1991        String representation of self.
     1992
     1993        EXAMPLE::
     1994
     1995            sage: from sage.rings.qqbar import qq_generator, cyclotomic_generator
     1996            sage: qq_generator._repr_()
     1997            'Trivial generator'
     1998
     1999            sage: cyclotomic_generator(7)._repr_()
     2000            '1*e^(2*pi*I*1/7)'
     2001
     2002            sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator
     2003            sage: y = polygen(QQ)
     2004            sage: x = polygen(QQbar)
     2005            sage: nf = NumberField(y^2 - y - 1, name='a', check=False)
     2006            sage: root = ANRoot(x^2 - x - 1, RIF(1, 2))
     2007            sage: gen = AlgebraicGenerator(nf, root)
     2008            sage: gen._repr_()
     2009            'Number Field in a with defining polynomial x^2 - x - 1 with a in 1.618033988749895?'
     2010        """
    16412011        if self._trivial:
    16422012            return 'Trivial generator'
    16432013        else:
     
    16472017                return '%s with a in %s'%(self._field, self._root._interval_fast(53))
    16482018
    16492019    def root_as_algebraic(self):
     2020        r"""
     2021        Return the root attached to self as an algebraic number.
     2022
     2023        EXAMPLE::
     2024
     2025            sage: t = sage.rings.qqbar.qq_generator.root_as_algebraic(); t
     2026            1
     2027            sage: t.parent()
     2028            Algebraic Real Field
     2029        """
    16502030        return self._root_as_algebraic
    16512031
    16522032    def is_trivial(self):
     
    16632043        return self._trivial
    16642044
    16652045    def field(self):
     2046        r"""
     2047        Return the number field attached to self.
     2048
     2049        EXAMPLE::
     2050
     2051            sage: from sage.rings.qqbar import qq_generator, cyclotomic_generator
     2052            sage: qq_generator.field()
     2053            Rational Field
     2054            sage: cyclotomic_generator(3).field()
     2055            Cyclotomic Field of order 3 and degree 2
     2056        """
    16662057        return self._field
    16672058
    16682059    def pari_field(self):
     2060        r"""
     2061        Return the PARI field attached to this generator.
     2062
     2063        EXAMPLE::
     2064
     2065
     2066            sage: from sage.rings.qqbar import qq_generator
     2067            sage: qq_generator.pari_field()
     2068            Traceback (most recent call last):
     2069            ...
     2070            ValueError: No PARI field attached to trivial generator
     2071
     2072            sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator
     2073            sage: y = polygen(QQ)
     2074            sage: x = polygen(QQbar)
     2075            sage: nf = NumberField(y^2 - y - 1, name='a', check=False)
     2076            sage: root = ANRoot(x^2 - x - 1, RIF(1, 2))
     2077            sage: gen = AlgebraicGenerator(nf, root)
     2078            sage: gen.pari_field()
     2079             [y^2 - y - 1, [2, 0], ...]
     2080        """
     2081        if self.is_trivial(): raise ValueError("No PARI field attached to trivial generator")
    16692082        if self._pari_field is None:
    16702083            pari_pol = self._field.pari_polynomial("y")
    16712084            self._pari_field = pari_pol.nfinit(1)
     
    16752088        r"""
    16762089        If this generator is for the algebraic number `\alpha`, return a
    16772090        generator for the complex conjugate of `\alpha`.
     2091
     2092        EXAMPLE::
     2093
     2094            sage: from sage.rings.qqbar import AlgebraicGenerator
     2095            sage: x = polygen(QQ); f = x^4 + x + 17
     2096            sage: nf = NumberField(f,name='a')
     2097            sage: b = f.roots(QQbar)[0][0]
     2098            sage: root = b._descr
     2099            sage: gen = AlgebraicGenerator(nf, root)
     2100            sage: gen.conjugate()
     2101            Number Field in a with defining polynomial x^4 + x + 17 with a in -1.436449997483091? + 1.374535713065812?*I
    16782102        """
    16792103        try:
    16802104            return self._conjugate
     
    16962120        """
    16972121        Returns an interval containing this generator, to the specified
    16982122        precision.
     2123
     2124        EXAMPLE::
     2125
     2126            sage: g = sage.rings.qqbar.cyclotomic_generator(5)
     2127            sage: g._interval_fast(256)
     2128            0.309016994374947424102293417182819058860154589902881431067724311352...? + 0.951056516295153572116439333379382143405698634125750222447305644430...?*I
    16992129        """
    17002130        return self._root._interval_fast(prec)
    17012131
     
    18692299        """
    18702300        Takes an algebraic number which is represented as either a
    18712301        rational or a number field element, and which is in a subfield
    1872         of the field generated by this generator.  Lifts the number
     2302        of the field generated by this generator. Lifts the number
    18732303        into the field of this generator, and returns either a
    18742304        ``Rational`` or a ``NumberFieldElement`` depending on whether
    18752305        this is the trivial generator.
     
    19172347        return self._field(elt.field_element_value().polynomial()(sp))
    19182348
    19192349# These are the functions used to add, subtract, multiply, and divide
    1920 # algebraic numbers.  Basically, we try to compute exactly if the
     2350# algebraic numbers. Basically, we try to compute exactly if the
    19212351# result would be a Gaussian rational, or a rational times a root
    19222352# of unity; or if both arguments are already known to be in the same
    1923 # number field.  Otherwise we fall back to floating-point computation,
     2353# number field. Otherwise we fall back to floating-point computation,
    19242354# to be backed up by exact symbolic computation only as required.
    19252355
    19262356# These choices are motivated partly by efficiency considerations
     
    19302360# than as intervals, as often as possible.
    19312361
    19322362def an_addsub_rational(a, b, sub):
     2363    r"""
     2364    Used to add and subtract algebraic numbers. Used when both are actually rational.
     2365
     2366    EXAMPLE::
     2367
     2368        sage: from sage.rings.qqbar import an_addsub_rational
     2369        sage: f = an_addsub_rational(QQbar(2), QQbar(3/7), False); f
     2370        17/7
     2371        sage: type(f)
     2372        <class 'sage.rings.qqbar.ANRational'>
     2373    """
    19332374    va = a._descr._value
    19342375    vb = b._descr._value
    19352376    if sub:
     
    19392380    return ANRational(v)
    19402381
    19412382def an_muldiv_rational(a, b, div):
     2383    r"""
     2384    Used to multiply and divide algebraic numbers. Used when both are actually rational.
     2385
     2386    EXAMPLE::
     2387
     2388        sage: from sage.rings.qqbar import an_muldiv_rational
     2389        sage: f = an_muldiv_rational(QQbar(2), QQbar(3/7), False); f
     2390        6/7
     2391        sage: type(f)
     2392        <class 'sage.rings.qqbar.ANRational'>
     2393    """
     2394    va = a._descr._value
    19422395    va = a._descr._value
    19432396    vb = b._descr._value
    19442397    if div:
     
    19482401    return ANRational(v)
    19492402
    19502403def an_addsub_zero(a, b, sub):
     2404    r"""
     2405    Used to add and subtract algebraic numbers. Used when one of a and b is zero.
     2406
     2407    EXAMPLES::
     2408
     2409        sage: from sage.rings.qqbar import an_addsub_zero
     2410        sage: f = an_addsub_zero(QQbar(sqrt(2)), QQbar(0), False); f
     2411        Root 1.4142135623730950488? of x^2 - 2
     2412        sage: type(f)
     2413        <class 'sage.rings.qqbar.ANRoot'>
     2414        sage: an_addsub_zero(QQbar(0), QQbar(sqrt(2)), True)
     2415        <class 'sage.rings.qqbar.ANUnaryExpr'>
     2416    """
    19512417    if b._descr.is_rational() and b._descr.rational_value().is_zero():
    19522418        return a._descr
    19532419    # we know a is 0
     
    19572423        return b._descr
    19582424
    19592425def an_muldiv_zero(a, b, div):
     2426    r"""
     2427    Used to multiply and divide algebraic numbers. Used when one of a and b is zero.
     2428
     2429    EXAMPLES::
     2430
     2431        sage: from sage.rings.qqbar import an_muldiv_zero
     2432        sage: f = an_muldiv_zero(QQbar(sqrt(2)), QQbar(0), False); f
     2433        0
     2434        sage: type(f)
     2435        <class 'sage.rings.qqbar.ANRational'>
     2436        sage: an_muldiv_zero(QQbar(sqrt(2)), QQbar(sqrt(0)), True)
     2437        Traceback (most recent call last):
     2438        ...
     2439        ValueError: algebraic number division by zero
     2440    """
    19602441    if b._descr.is_rational() and b._descr.rational_value().is_zero():
    19612442        if div:
    1962             raise ValueError, "algebraic number division by zero"
     2443            raise ValueError("algebraic number division by zero")
    19632444        else:
    19642445            return ANRational(0)
    19652446    # we know a is 0
    19662447    return ANRational(0)
    19672448
    19682449def an_addsub_gaussian(a, b, sub):
     2450    r"""
     2451    Used to add and subtract algebraic numbers when both are in `\QQ(i)`.
     2452
     2453    EXAMPLE::
     2454
     2455        sage: i = QQbar(I)
     2456        sage: from sage.rings.qqbar import an_addsub_gaussian
     2457        sage: x=an_addsub_gaussian(2 + 3*i, 2/3 + 1/4*i, True); x
     2458        11/4*I + 4/3 where a^2 + 1 = 0 and a in 1*I
     2459        sage: type(x)
     2460        <class 'sage.rings.qqbar.ANExtensionElement'>
     2461    """
    19692462    va = a._descr.gaussian_value()
    19702463    vb = b._descr.gaussian_value()
    19712464    if sub:
     
    19752468    return ANExtensionElement(QQbar_I_generator, v)
    19762469
    19772470def an_muldiv_gaussian(a, b, div):
     2471    r"""
     2472    Used to multiply and divide algebraic numbers when both are in `\QQ(i)`.
     2473
     2474    EXAMPLE::
     2475
     2476        sage: i = QQbar(I)
     2477        sage: from sage.rings.qqbar import an_muldiv_gaussian
     2478        sage: x=an_muldiv_gaussian(2 + 3*i, 2/3 + 1/4*i, True); x
     2479        216/73*I + 300/73 where a^2 + 1 = 0 and a in 1*I
     2480        sage: type(x)
     2481        <class 'sage.rings.qqbar.ANExtensionElement'>
     2482    """
    19782483    va = a._descr.gaussian_value()
    19792484    vb = b._descr.gaussian_value()
    19802485    if div:
     
    19842489    return ANExtensionElement(QQbar_I_generator, v)
    19852490
    19862491def an_addsub_expr(a, b, sub):
     2492    r"""
     2493    Add or subtract algebraic numbers represented as multi-part expressions.
     2494
     2495    EXAMPLE::
     2496
     2497        sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3))
     2498        sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5))
     2499        sage: type(a._descr); type(b._descr)
     2500        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2501        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2502        sage: from sage.rings.qqbar import an_addsub_expr
     2503        sage: x = an_addsub_expr(a, b, False); x
     2504        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2505        sage: x.exactify()
     2506        6/7*a^7 + 2/7*a^6 - 71/7*a^5 - 26/7*a^4 + 125/7*a^3 + 72/7*a^2 - 43/7*a - 47/7 where a^8 - 12*a^6 + 23*a^4 - 12*a^2 + 1 = 0 and a in -3.12580...?
     2507    """
    19872508    return ANBinaryExpr(a, b, ('-' if sub else '+'))
    19882509
    19892510def an_muldiv_expr(a, b, div):
     2511    r"""
     2512    Multiply or divide algebraic numbers represented as multi-part expressions.
     2513
     2514    EXAMPLE::
     2515
     2516        sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3))
     2517        sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5))
     2518        sage: type(a._descr)
     2519        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2520        sage: from sage.rings.qqbar import an_muldiv_expr
     2521        sage: x = an_muldiv_expr(a, b, False); x
     2522        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2523        sage: x.exactify()
     2524        -2*a^7 - a^6 + 24*a^5 + 12*a^4 - 46*a^3 - 22*a^2 + 22*a + 9 where a^8 - 12*a^6 + 23*a^4 - 12*a^2 + 1 = 0 and a in -3.1258...?
     2525    """
    19902526    return ANBinaryExpr(a, b, ('/' if div else '*'))
    19912527
    19922528def an_muldiv_rootunity(a, b, div):
     2529    r"""
     2530    Multiply or divide two algebraic numbers represented as a rational multiple
     2531    of a root of unity.
     2532
     2533    EXAMPLE::
     2534
     2535        sage: a = 2*QQbar.zeta(7)
     2536        sage: b = 3*QQbar.zeta(8)
     2537        sage: type(a._descr)
     2538        <class 'sage.rings.qqbar.ANRootOfUnity'>
     2539        sage: from sage.rings.qqbar import an_muldiv_rootunity
     2540        sage: an_muldiv_rootunity(a, b, True)
     2541        2/3*e^(2*pi*I*1/56)
     2542    """
    19932543    ad = a._descr
    19942544    bd = b._descr
    19952545    if div:
     
    19982548        return ANRootOfUnity(ad.angle() + bd.angle(), ad.scale() * bd.scale())
    19992549
    20002550def an_addsub_rootunity(a, b, sub):
     2551    r"""
     2552    Add or subtract two algebraic numbers represented as a rational multiple of
     2553    a root of unity.
     2554
     2555    EXAMPLE::
     2556
     2557        sage: a = 2*QQbar.zeta(7)
     2558        sage: b = 3*QQbar.zeta(8)
     2559        sage: type(a._descr)
     2560        <class 'sage.rings.qqbar.ANRootOfUnity'>
     2561        sage: from sage.rings.qqbar import an_addsub_rootunity
     2562        sage: an_addsub_rootunity(a, b, False)
     2563        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2564        sage: an_addsub_rootunity(a, 3*QQbar.zeta(7), True)
     2565        -1*e^(2*pi*I*1/7)
     2566    """
    20012567    ad = a._descr
    20022568    bd = b._descr
    20032569    if ad._angle == bd._angle:
     
    20092575        return an_addsub_expr(a, b, sub)
    20102576
    20112577def an_muldiv_element(a, b, div):
     2578    r"""
     2579    Multiply or divide two elements represented as elements of number fields.
     2580
     2581    EXAMPLES::
     2582
     2583        sage: a = QQbar(sqrt(2) + sqrt(3)); a.exactify()
     2584        sage: b = QQbar(sqrt(3) + sqrt(5)); b.exactify()
     2585        sage: type(a._descr)
     2586        <class 'sage.rings.qqbar.ANExtensionElement'>
     2587        sage: from sage.rings.qqbar import an_muldiv_element
     2588        sage: an_muldiv_element(a,b,False)
     2589        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2590    """
    20122591    ad = a._descr
    20132592    bd = b._descr
    20142593    adg = ad.generator()
     
    20262605    return ANBinaryExpr(a, b, ('/' if div else '*'))
    20272606
    20282607def an_addsub_element(a, b, sub):
     2608    r"""
     2609    Add or subtract two elements represented as elements of number fields.
     2610
     2611    EXAMPLES::
     2612
     2613        sage: a = QQbar(sqrt(2) + sqrt(3)); a.exactify()
     2614        sage: b = QQbar(sqrt(3) + sqrt(5)); b.exactify()
     2615        sage: from sage.rings.qqbar import an_addsub_element
     2616        sage: an_addsub_element(a,b,False)
     2617        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2618    """
    20292619    ad = a._descr
    20302620    bd = b._descr
    20312621    adg = ad.generator()
     
    21052695        _add_algo[key] = an_addsub_expr
    21062696
    21072697class ANDescr(SageObject):
    2108     r""" An ``AlgebraicNumber`` or ``AlgebraicReal`` is a wrapper
    2109     around an ``ANDescr`` object.  ``ANDescr`` is an abstract base
    2110     class, which should never be directly instantiated; its concrete
    2111     subclasses are ``ANRational``, ``ANBinaryExpr``, ``ANUnaryExpr``,
    2112     ``ANRootOfUnity``, ``ANRoot``, and ``ANExtensionElement``.
    2113     ``ANDescr`` and all of its subclasses are private, and should not
    2114     be used directly.
     2698    r"""
     2699    An ``AlgebraicNumber`` or ``AlgebraicReal`` is a wrapper around an
     2700    ``ANDescr`` object. ``ANDescr`` is an abstract base class, which should
     2701    never be directly instantiated; its concrete subclasses are ``ANRational``,
     2702    ``ANBinaryExpr``, ``ANUnaryExpr``, ``ANRootOfUnity``, ``ANRoot``, and
     2703    ``ANExtensionElement``. ``ANDescr`` and all of its subclasses are for
     2704    internal use, and should not be used directly.
    21152705    """
    21162706    def is_exact(self):
    21172707        """
     
    21602750
    21612751    def is_rational(self):
    21622752        r"""
    2163         Returns ``True`` if self is an ``ANRational`` object.  (Note that
     2753        Returns ``True`` if self is an ``ANRational`` object. (Note that
    21642754        the constructors for ``ANExtensionElement`` and ``ANRootOfUnity``
    21652755        will actually return ``ANRational`` objects for rational numbers.)
    21662756
     
    21902780        """
    21912781        return False
    21922782
     2783    # Unitary operators: the second argument "n" is an AlgebraicNumber_base
     2784    # wrapper around self.
     2785
    21932786    def neg(self, n):
     2787        r"""
     2788        Negation of self.
     2789
     2790        EXAMPLE::
     2791
     2792            sage: a = QQbar(sqrt(2))
     2793            sage: b = a._descr
     2794            sage: b.neg(a)
     2795            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2796        """
    21942797        return ANUnaryExpr(n, '-')
    21952798
    21962799    def invert(self, n):
     2800        r"""
     2801        1/self.
     2802
     2803        EXAMPLE::
     2804
     2805            sage: a = QQbar(sqrt(2))
     2806            sage: b = a._descr
     2807            sage: b.invert(a)
     2808            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2809        """
    21972810        return ANUnaryExpr(n, '~')
    21982811
    21992812    def abs(self, n):
     2813        r"""
     2814        Absolute value of self.
     2815
     2816        EXAMPLE::
     2817
     2818            sage: a = QQbar(sqrt(2))
     2819            sage: b = a._descr
     2820            sage: b.abs(a)
     2821            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2822        """
    22002823        return ANUnaryExpr(n, 'abs')
    22012824
    22022825    def real(self, n):
     2826        r"""
     2827        Real part of self.
     2828
     2829        EXAMPLE::
     2830
     2831            sage: a = QQbar(sqrt(-7))
     2832            sage: b = a._descr
     2833            sage: b.real(a)
     2834            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2835        """
    22032836        if self.is_complex():
    22042837            return ANUnaryExpr(n, 'real')
    22052838        else:
    22062839            return self
    22072840
    22082841    def imag(self, n):
     2842        r"""
     2843        Imaginary part of self.
     2844
     2845        EXAMPLE::
     2846
     2847            sage: a = QQbar(sqrt(-7))
     2848            sage: b = a._descr
     2849            sage: b.imag(a)
     2850            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2851        """
    22092852        if self.is_complex():
    22102853            return ANUnaryExpr(n, 'imag')
    22112854        else:
    22122855            return ANRational(0)
    22132856
    22142857    def conjugate(self, n):
     2858        r"""
     2859        Complex conjugate of self.
     2860
     2861        EXAMPLE::
     2862
     2863            sage: a = QQbar(sqrt(-7))
     2864            sage: b = a._descr
     2865            sage: b.conjugate(a)
     2866            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2867        """
    22152868        if self.is_complex():
    22162869            return ANUnaryExpr(n, 'conjugate')
    22172870        else:
    22182871            return self
    22192872
    22202873    def norm(self, n):
     2874        r"""
     2875        Field norm of self from `\overline{\QQ}` to its real subfield
     2876        `\mathbf{A}`, i.e.~the square of the usual complex absolute value.
     2877
     2878        EXAMPLE::
     2879
     2880            sage: a = QQbar(sqrt(-7))
     2881            sage: b = a._descr
     2882            sage: b.norm(a)
     2883            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2884        """
    22212885        if self.is_complex():
    22222886            return ANUnaryExpr(n, 'norm')
    22232887        else:
     
    22312895
    22322896    ``AlgebraicNumber`` objects can be created using ``QQbar`` (==
    22332897    ``AlgebraicNumberField()``), and ``AlgebraicReal`` objects can be created
    2234     using ``AA`` (== ``AlgebraicRealField()``).  They can be created either by
     2898    using ``AA`` (== ``AlgebraicRealField()``). They can be created either by
    22352899    coercing a rational or a symbolic expression, or by using the
    22362900    ``QQbar.polynomial_root()`` or ``AA.polynomial_root()`` method to
    22372901    construct a particular root of a polynomial with algebraic
    2238     coefficients.  Also, ``AlgebraicNumber`` and ``AlgebraicReal`` are closed
     2902    coefficients. Also, ``AlgebraicNumber`` and ``AlgebraicReal`` are closed
    22392903    under addition, subtraction, multiplication, division (except by
    22402904    0), and rational powers (including roots), except that for a
    22412905    negative ``AlgebraicReal``, taking a power with an even denominator returns
    22422906    an ``AlgebraicNumber`` instead of an ``AlgebraicReal``.
    22432907
    22442908    ``AlgebraicNumber``   and   ``AlgebraicReal``   objects   can   be
    2245     approximated  to  any desired  precision.   They  can be  compared
     2909    approximated  to  any desired  precision. They  can be  compared
    22462910    exactly; if the two numbers are very close, or are equal, this may
    22472911    require exact computation, which can be extremely slow.
    22482912
    22492913    As long as exact computation is not triggered, computation with
    22502914    algebraic numbers should not be too much slower than computation with
    2251     intervals.  As mentioned above, exact computation is triggered
     2915    intervals. As mentioned above, exact computation is triggered
    22522916    when comparing two algebraic numbers which are very close together.
    22532917    This can be an explicit comparison in user code, but the following
    22542918    list of actions (not necessarily complete) can also trigger exact
     
    22852949
    22862950    def __init__(self, parent, x):
    22872951        r"""
    2288         Initialize an algebraic number.  The argument must be either
     2952        Initialize an algebraic number. The argument must be either
    22892953        a rational number, a Gaussian rational, or a subclass of ``ANDescr``.
    22902954       
    22912955        EXAMPLES::
     
    23072971                 list(x.parent().polynomial()) == [1, 0, 1]:
    23082972            self._descr = ANExtensionElement(QQbar_I_generator, QQbar_I_nf(x.list()))
    23092973        else:
    2310             raise TypeError, "Illegal initializer for algebraic number"
     2974            raise TypeError("Illegal initializer for algebraic number")
    23112975
    23122976        self._value = self._descr._interval_fast(64)
    23132977       
     
    23172981
    23182982        EXAMPLES::
    23192983
    2320             sage: AA(22/7)
     2984            sage: AA(22/7) # indirect doctest
    23212985            22/7
    23222986            sage: QQbar(1/3 + 2/7*I)
    23232987            2/7*I + 1/3
     
    23933057        """
    23943058        TESTS::
    23953059
    2396             sage: AA(sqrt(2)) * AA(sqrt(8))
     3060            sage: AA(sqrt(2)) * AA(sqrt(8)) # indirect doctest
    23973061            4.000000000000000?
    23983062        """
    23993063        sd = self._descr
     
    24063070        """
    24073071        TESTS::
    24083072
    2409             sage: AA(sqrt(2)) / AA(sqrt(8))
     3073            sage: AA(sqrt(2)) / AA(sqrt(8)) # indirect doctest
    24103074            0.500000000000000?
    24113075        """
    24123076        sd = self._descr
     
    24313095
    24323096            sage: x = polygen(ZZ)
    24333097            sage: rt1, rt2 = (x^2 - x - 1).roots(ring=AA, multiplicities=False)
    2434             sage: rt1 + rt2
     3098            sage: rt1 + rt2 # indirect doctest
    24353099            1.000000000000000?
    24363100        """
    24373101        sd = self._descr
     
    24443108        """
    24453109        TESTS::
    24463110
    2447             sage: AA(golden_ratio) * 2 - AA(5).sqrt()
     3111            sage: AA(golden_ratio) * 2 - AA(5).sqrt() # indirect doctest
    24483112            1.000000000000000?
    24493113        """
    24503114        sd = self._descr
     
    24573121        """
    24583122        TESTS::
    24593123
    2460             sage: -QQbar(I)
     3124            sage: -QQbar(I) # indirect doctest
    24613125            -1*I
    24623126        """
    24633127        return type(self)(self._descr.neg(self))
     
    25073171            True
    25083172
    25093173        Unfortunately, the hash code for algebraic numbers which are close
    2510         enough to each other are the same.  (This is inevitable, if
     3174        enough to each other are the same. (This is inevitable, if
    25113175        equal algebraic reals give the same hash code and hashing does
    25123176        not always trigger exact computation.)::
    25133177
     
    25263190        # 1, or 2 are presumably not uncommon).
    25273191
    25283192        # So I modify the algebraic real by adding 1/123456789 to it before
    2529         # calling interval_exact().  Then, exact computation will be triggered
     3193        # calling interval_exact(). Then, exact computation will be triggered
    25303194        # by algebraic reals which are sufficiently close to
    2531         # (some floating point number minus 1/123456789).  Hopefully,
     3195        # (some floating point number minus 1/123456789). Hopefully,
    25323196        # -1/123456789 comes up in algebraic real computations far less
    2533         # often than 0 does.  Algebraic numbers have a similar offset added,
     3197        # often than 0 does. Algebraic numbers have a similar offset added,
    25343198        # with an additional complex component of 1/987654321*I.
    25353199
    25363200        # All of this effort to avoid exact computation is probably wasted,
    25373201        # anyway... in almost all uses of hash codes, if the hash codes
    25383202        # match, the next step is to compare for equality; and comparing
    2539         # for equality often requires exact computation.  (If a==b,
     3203        # for equality often requires exact computation. (If a==b,
    25403204        # then checking a==b requires exact computation unless (a is b).)
    25413205
    25423206        if self.parent() is AA:
     
    25803244          return a square root of self in QQbar, otherwise raise a ValueError.
    25813245
    25823246        - ``all`` - bool (default: False); if True, return a list of all square
    2583           roots.  If False, return just one square root, or raise an ValueError
     3247          roots. If False, return just one square root, or raise an ValueError
    25843248          if self is a negative element of AA and extend=False.
    25853249       
    25863250        OUTPUT:
     
    26413305
    26423306        if self.parent() is AA and self<0 and not extend:
    26433307            if not all:
    2644                 raise ValueError, "%s is not a square in AA, being negative. Use extend = True for a square root in QQbar."%self
     3308                raise ValueError("%s is not a square in AA, being negative. Use extend = True for a square root in QQbar."%self)
    26453309            else:
    26463310                return []
    26473311   
     
    28963560        r"""
    28973561        Given a ``RealIntervalField``, compute the value of this number
    28983562        using interval arithmetic of at least the precision of the field,
    2899         and return the value in that field.  (More precision may be used
     3563        and return the value in that field. (More precision may be used
    29003564        in the computation.)  The returned interval may be arbitrarily
    29013565        imprecise, if this number is the result of a sufficiently long
    29023566        computation chain.
     
    29273591    def interval_diameter(self, diam):
    29283592        """
    29293593        Compute an interval representation of self with ``diameter()`` at
    2930         most ``diam``.  The precision of the returned value is unpredictable.
     3594        most ``diam``. The precision of the returned value is unpredictable.
    29313595
    29323596        EXAMPLES::
    29333597
     
    29533617        Given an interval field (real or complex, as appropriate) of
    29543618        precision `p`, compute an interval representation of self with
    29553619        ``diameter()`` at most `2^{-p}`; then round that representation into
    2956         the given field.  Here ``diameter()`` is relative diameter for
     3620        the given field. Here ``diameter()`` is relative diameter for
    29573621        intervals not containing 0, and absolute diameter for
    29583622        intervals that do contain 0; thus, if the returned interval
    29593623        does not contain 0, it has at least `p-1` good bits.
     
    29823646class AlgebraicNumber(AlgebraicNumber_base):
    29833647    r"""
    29843648    The class for algebraic numbers (complex numbers which are the roots
    2985     of a polynomial with integer coefficients).  Much of its functionality
     3649    of a polynomial with integer coefficients). Much of its functionality
    29863650    is inherited from ``AlgebraicNumber_base``.
    29873651    """
    29883652    def __init__(self, x):
     3653        r"""
     3654        Initialize this AlgebraicNumber object.
     3655
     3656        EXAMPLE::
     3657
     3658            sage: t = QQbar.zeta(5)
     3659            sage: type(t)
     3660            <class 'sage.rings.qqbar.AlgebraicNumber'>
     3661        """
    29893662        AlgebraicNumber_base.__init__(self, QQbar, x)
    29903663
    29913664    def __reduce__(self):
     
    30023675
    30033676    def __cmp__(self, other):
    30043677        """
    3005         Compare two algebraic numbers, lexicographically.  (That is,
     3678        Compare two algebraic numbers, lexicographically. (That is,
    30063679        first compare the real components; if the real components are
    30073680        equal, compare the imaginary components.)
    30083681
     
    30543727        return not self._sub_(other).__nonzero__()
    30553728
    30563729    def __ne__(self, other):
     3730        r"""
     3731        Test two algebraic numbers for inequality.
     3732
     3733        EXAMPLES::
     3734
     3735            sage: QQbar.zeta(6) != QQbar(1/2 + I*sqrt(3)/2)
     3736            False
     3737            sage: QQbar(I) != QQbar(I * (2^100+1)/(2^100))
     3738            True
     3739            sage: QQbar(2) != 2
     3740            False
     3741            sage: QQbar(2) != GF(7)(2)
     3742            True
     3743        """
    30573744        return not self.__eq__(other)
    30583745
    30593746    def __nonzero__(self):
    30603747        """
    3061         Check whether self is equal is nonzero.  This is fast if
     3748        Check whether self is equal is nonzero. This is fast if
    30623749        interval arithmetic proves that self is nonzero, but may be
    30633750        slow if the number actually is very close to zero.
    30643751
     
    30883775
    30893776    def __pow__(self, e):
    30903777        r""" ``self**p`` returns the `p`'th power of self (where `p` can
    3091         be an arbitrary rational).  If `p` is `(a/b)`, takes the principal
    3092         `b`'th root of self, then takes that to the `a`'th power.  (Note
     3778        be an arbitrary rational). If `p` is `(a/b)`, takes the principal
     3779        `b`'th root of self, then takes that to the `a`'th power. (Note
    30933780        that this differs from ``__pow__`` on algebraic reals, where real
    30943781        roots are preferred over principal roots if they exist.)
    30953782
     
    32133900    def _mpfr_(self, field):
    32143901        r"""
    32153902        Given a ``RealField``, compute a good approximation to self in
    3216         that field.  Works only if the imaginary component of self is
     3903        that field. Works only if the imaginary component of self is
    32173904        exactly zero; otherwise it raises a ``ValueError``.
    32183905
    32193906        EXAMPLES::
     
    32313918
    32323919    def __float__(self):
    32333920        r"""
    3234         Compute a good float approximation to self.  Works only if the
     3921        Compute a good float approximation to self. Works only if the
    32353922        imaginary component of self is exactly zero; otherwise it
    32363923        raises a ``ValueError``.
    32373924
     
    32753962        return cdf(CC(self))
    32763963
    32773964    def _interval_fast(self, prec):
     3965        r"""
     3966        Shortcut for :meth:`AlgebraicNumber_base.interval_fast` which uses the complex interval field.
     3967
     3968        EXAMPLE::
     3969
     3970            sage: QQbar(sqrt(-5))._interval_fast(100)
     3971            2.236067977499789696409173...?*I
     3972        """
    32783973        return self.interval_fast(ComplexIntervalField(prec))
    32793974
    32803975    def _integer_(self, ZZ=None):
     
    33324027        return AA(self)._rational_()
    33334028
    33344029    def real(self):
     4030        r"""
     4031        Return the real part of self.
     4032
     4033        EXAMPLE::
     4034
     4035            sage: QQbar.zeta(5).real()
     4036            0.3090169943749474?
     4037        """
    33354038        return AlgebraicReal(self._descr.real(self))
    33364039
    33374040    def imag(self):
     4041        r"""
     4042        Return the imaginary part of self.
     4043
     4044        EXAMPLE::
     4045
     4046            sage: QQbar.zeta(7).imag()
     4047            0.7818314824680299?
     4048        """
    33384049        return AlgebraicReal(self._descr.imag(self))
    33394050
    33404051    def conjugate(self):
     
    33544065
    33554066    def norm(self):
    33564067        r"""
    3357         Returns ``self * self.conjugate()``.  This is the algebraic
     4068        Returns ``self * self.conjugate()``. This is the algebraic
    33584069        definition of norm, if we view ``QQbar`` as ``AA[I]``.
    33594070
    33604071        EXAMPLES::
     
    33714082    def interval_exact(self, field):
    33724083        r"""
    33734084        Given a ``ComplexIntervalField``, compute the best possible
    3374         approximation of this number in that field.  Note that if
     4085        approximation of this number in that field. Note that if
    33754086        either the real or imaginary parts of this number are
    33764087        sufficiently close to some floating-point number (and, in
    33774088        particular, if either is exactly representable in floating-point),
     
    33904101            0
    33914102        """
    33924103        if not is_ComplexIntervalField(field):
    3393             raise ValueError, "AlgebraicNumber interval_exact requires a ComplexIntervalField"
     4104            raise ValueError("AlgebraicNumber interval_exact requires a ComplexIntervalField")
    33944105        rfld = field._real_field()
    33954106        re = self.real().interval_exact(rfld)
    33964107        im = self.imag().interval_exact(rfld)
    33974108        return field(re, im)
    33984109
    33994110    def _complex_mpfr_field_(self, field):
     4111        r"""
     4112        Compute an approximation to self in the given field, which may be
     4113        either an interval field (in which case ``self.interval()`` is called)
     4114        or any other complex field (in which case ``self.complex_number()`` is
     4115        called).
     4116
     4117        EXAMPLE::
     4118
     4119            sage: a = QQbar(1 + I).sqrt()
     4120            sage: t = a._complex_mpfr_field_(CIF); t
     4121            1.098684113467810? + 0.4550898605622274?*I
     4122            sage: parent(t)
     4123            Complex Interval Field with 53 bits of precision
     4124            sage: t = a._complex_mpfr_field_(ComplexField(100)); t
     4125            1.0986841134678099660398011952 + 0.45508986056222734130435775782*I
     4126            sage: parent(t)
     4127            Complex Field with 100 bits of precision
     4128        """
    34004129        if is_ComplexIntervalField(field):
    34014130            return self.interval(field)
    34024131        else:
    34034132            return self.complex_number(field)
    34044133
    3405 
    34064134    def complex_number(self, field):
    34074135        r""" Given a ``ComplexField``, compute a good approximation to
    3408         self in that field.  The approximation will be off by at most
     4136        self in that field. The approximation will be off by at most
    34094137        two ulp's in each component, except for components which are
    34104138        very close to zero, which will have an absolute error at most
    34114139        ``2**(-(field.prec()-1))``.
     
    34244152    def complex_exact(self, field):
    34254153        r"""
    34264154        Given a ``ComplexField``, return the best possible approximation of
    3427         this number in that field.  Note that if either component is
     4155        this number in that field. Note that if either component is
    34284156        sufficiently close to the halfway point between two floating-point
    34294157        numbers in the corresponding ``RealField``, then this will trigger
    34304158        exact computation, which may be very slow.
     
    34444172    def multiplicative_order(self):
    34454173        r"""
    34464174        Compute the multiplicative order of this algebraic real
    3447         number.  That is, find the smallest positive integer `n` such
    3448         that `x^n = 1`.  If there is no such `n`, returns ``+Infinity``.
    3449 
    3450         We first check that ``abs(x)`` is very close to 1.  If so, we compute
     4175        number. That is, find the smallest positive integer `n` such
     4176        that `x^n = 1`. If there is no such `n`, returns ``+Infinity``.
     4177
     4178        We first check that ``abs(x)`` is very close to 1. If so, we compute
    34514179        `x` exactly and examine its argument.
    34524180
    34534181        EXAMPLES::
     
    34754203    def rational_argument(self):
    34764204        r"""
    34774205        Returns the argument of self, divided by `2\pi`, as long as this
    3478         result is rational.  Otherwise returns None. Always triggers
     4206        result is rational. Otherwise returns None. Always triggers
    34794207        exact computation.
    34804208
    34814209        EXAMPLES::
     
    34934221            sage: (QQbar.zeta(3)^65536).rational_argument()
    34944222            1/3
    34954223        """
    3496         # This always triggers exact computation.  An alternate method
     4224        # This always triggers exact computation. An alternate method
    34974225        # could almost always avoid exact computation when the result
    34984226        # is None: if we can compute an upper bound on the degree of
    34994227        # this algebraic number without exact computation, we can use
     
    35134241       
    35144242        TESTS:
    35154243
    3516         Both of the following examples, from trac 11728, trigger
    3517         taking the real part below.  This is necessary because
     4244        Both of the following examples, from :trac:`11728`, trigger
     4245        taking the real part below. This is necessary because
    35184246        sometimes a very small (e.g., 1e-17) complex part appears in a
    35194247        complex interval used to create an AlgebraicReal.::
    35204248
     
    35514279        Recompute the interval bounding this number with higher-precision
    35524280        interval arithmetic.
    35534281
     4282        EXAMPLE::
     4283
     4284            sage: a = QQbar(sqrt(2))
     4285            sage: a._more_precision()
     4286
    35544287        TESTS:
    35554288
    35564289        We have to ensure after doing this that self._value is still
    35574290        real which isn't the case without calling _ensure_real (see
    3558         trac 11728)::
     4291        :trac:`11728`)::
    35594292       
    35604293            sage: P = AA[x](1+x^4); a1,a2 = P.factor()[0][0],P.factor()[1][0]; a1*a2
    35614294            x^4 + 1.000000000000000?
     
    36034336    def __pow__(self, e):
    36044337        """
    36054338        ``self**p`` returns the `p`'th power of self (where `p` can be an
    3606         arbitrary rational).  If `p` is `(a/b)`, takes the `b`'th root of
    3607         self, then takes that to the `a`'th power.  If self is negative
     4339        arbitrary rational). If `p` is `(a/b)`, takes the `b`'th root of
     4340        self, then takes that to the `a`'th power. If self is negative
    36084341        and `b` is odd, it takes the real `b`'th root; if self is odd and
    3609         `b` is even, this takes a complex root.  Note that the behavior
     4342        `b` is even, this takes a complex root. Note that the behavior
    36104343        when self is negative and `b` is odd differs from the complex
    36114344        case; algebraic numbers select the principal complex `b`'th
    36124345        root, but algebraic reals select the real root.
     
    37124445        """
    37134446        if self._value.lower().ceiling() > self._value.upper().floor():
    37144447            # The value is known to be non-integral.
    3715             raise ValueError, "Cannot coerce non-integral Algebraic Real %s to Integer" % self
     4448            raise ValueError("Cannot coerce non-integral Algebraic Real %s to Integer" % self)
    37164449
    37174450        self.exactify()
    37184451        if not self._descr.is_rational():
    3719             raise ValueError, "Cannot coerce irrational Algebraic Real %s to Integer" % self
     4452            raise ValueError("Cannot coerce irrational Algebraic Real %s to Integer" % self)
    37204453
    37214454        return ZZ(self._descr.rational_value())
    37224455
     
    37414474        """
    37424475        self.exactify()
    37434476        if not self._descr.is_rational():
    3744             raise ValueError, "Cannot coerce irrational Algebraic Real %s to Rational" % self
     4477            raise ValueError("Cannot coerce irrational Algebraic Real %s to Rational" % self)
    37454478
    37464479        return QQ(self._descr.rational_value())
    37474480
     
    38214554            return self.sign()
    38224555
    38234556    def _interval_fast(self, prec):
     4557        r"""
     4558        Compute an approximation to this ``AlgebraicReal`` object in a real interval field of precision prec.
     4559
     4560        EXAMPLE::
     4561
     4562            sage: t = AA(sqrt(7))
     4563            sage: t._interval_fast(100)
     4564            2.64575131106459059050161575364?
     4565        """
    38244566        return self.interval_fast(RealIntervalField(prec))
    38254567
    38264568    def interval_exact(self, field):
    38274569        """
    38284570        Given a ``RealIntervalField``, compute the best possible
    3829         approximation of this number in that field.  Note that if this
     4571        approximation of this number in that field. Note that if this
    38304572        number is sufficiently close to some floating-point number
    38314573        (and, in particular, if this number is exactly representable in
    38324574        floating-point), then this will trigger exact computation, which
     
    38874629    def real_number(self, field):
    38884630        """
    38894631        Given a ``RealField``, compute a good approximation to self in
    3890         that field.  The approximation will be off by at most two
     4632        that field. The approximation will be off by at most two
    38914633        ulp's, except for numbers which are very close to 0, which
    38924634        will have an absolute error at most
    3893         ``2**(-(field.prec()-1))``.  Also, the rounding mode of the
     4635        ``2**(-(field.prec()-1))``. Also, the rounding mode of the
    38944636        field is respected.
    38954637
    38964638        EXAMPLES::
     
    39634705        return float(RR(self))
    39644706
    39654707    def _complex_mpfr_field_(self, field):
     4708        r"""
     4709        Compute an approximation to this ``AlgebraicReal`` in the given field,
     4710        which may be an interval field (in which case ``self.interval()`` is
     4711        called) or any other real number field (in which case
     4712        ``self.real_number()`` is called.
     4713
     4714        Note that the field ``field`` should be a *complex* field (whose
     4715        ``_real_field()`` method will be called to obtain a real subfield.)
     4716
     4717        EXAMPLE::
     4718
     4719            sage: AA(golden_ratio)._complex_mpfr_field_(ComplexIntervalField(100))
     4720            1.618033988749894848204586834365?
     4721            sage: AA(golden_ratio)._complex_mpfr_field_(ComplexField(100))
     4722            1.6180339887498948482045868344
     4723        """
    39664724        if is_ComplexIntervalField(field):
    39674725            return field(self.interval(field._real_field()))
    39684726        else:
     
    39714729    def real_exact(self, field):
    39724730        r"""
    39734731        Given a ``RealField``, compute the best possible approximation of
    3974         this number in that field.  Note that if this number is
     4732        this number in that field. Note that if this number is
    39754733        sufficiently close to the halfway point between two
    39764734        floating-point numbers in the field (for the default
    39774735        round-to-nearest mode) or if the number is sufficiently close
     
    40374795
    40384796        val = self.interval_exact(rifp1)
    40394797
    4040         # Call the largest floating-point number <= self 'x'.  Then
     4798        # Call the largest floating-point number <= self 'x'. Then
    40414799        # val may be [x .. x], [x .. x + 1/2 ulp],
    40424800        # [x + 1/2 ulp .. x + 1/2 ulp], or [x + 1/2 ulp .. x + 1 ulp];
    40434801        # in the second and fourth cases, the true value is not equal
     
    40584816class ANRational(ANDescr):
    40594817    r"""
    40604818    The subclass of ``ANDescr`` that represents an arbitrary
    4061     rational.  This class is private, and should not be used directly.
     4819    rational. This class is private, and should not be used directly.
    40624820    """
    40634821
    40644822    def __init__(self, x):
     
    40764834        elif isinstance(x, (int, long)):
    40774835            self._value = ZZ(x)
    40784836        else:
    4079             raise TypeError, "Illegal initializer for algebraic number rational"
     4837            raise TypeError("Illegal initializer for algebraic number rational")
    40804838
    40814839    def __reduce__(self):
    40824840        """
     
    40924850        return (ANRational, (self._value, ))
    40934851
    40944852    def _repr_(self):
     4853        r"""
     4854        String representation of self.
     4855
     4856        EXAMPLES::
     4857
     4858            sage: QQbar(2/3)._repr_()
     4859            '2/3'
     4860        """
    40954861        return repr(self._value)
    40964862
    40974863    def handle_sage_input(self, sib, coerce, is_qqbar):
     
    41244890        return (v, False)
    41254891
    41264892    def kind(self):
     4893        r"""
     4894        Return a string describing what kind of element this is. Since this is
     4895        a rational number, the result is either ``'zero'`` or ``'rational'``.
     4896
     4897        EXAMPLES::
     4898
     4899            sage: a = QQbar(3)._descr; type(a)
     4900            <class 'sage.rings.qqbar.ANRational'>
     4901            sage: a.kind()
     4902            'rational'
     4903            sage: a = QQbar(0)._descr; type(a)
     4904            <class 'sage.rings.qqbar.ANRational'>
     4905            sage: a.kind()
     4906            'zero'
     4907        """
    41274908        if self._value.is_zero():
    41284909            return 'zero'
    41294910        else:
    41304911            return 'rational'
    41314912
    41324913    def _interval_fast(self, prec):
     4914        r"""
     4915        Return an approximation to self in a real interval field of precision prec.
     4916
     4917        EXAMPLE::
     4918
     4919            sage: QQbar(355/113)._descr._interval_fast(30)
     4920            3.14159292?
     4921        """
    41334922        return RealIntervalField(prec)(self._value)
    41344923
    41354924    def generator(self):
     4925        r"""
     4926        Return an :class:`AlgebraicGenerator` object associated to this
     4927        element. Returns the trivial generator, since self is rational.
     4928
     4929        EXAMPLE::
     4930
     4931            sage: QQbar(0)._descr.generator()
     4932            Trivial generator
     4933        """
    41364934        return qq_generator
    41374935
    41384936    def is_complex(self):
     4937        r"""
     4938        Return False, since rational numbers are real
     4939
     4940        EXAMPLE::
     4941
     4942            sage: QQbar(1/7)._descr.is_complex()
     4943            False
     4944        """
    41394945        return False
    41404946
    41414947    def is_rational(self):
     4948        r"""
     4949        Return True, since this is a rational number.
     4950
     4951        EXAMPLE::
     4952
     4953            sage: QQbar(34/9)._descr.is_rational()
     4954            True
     4955            sage: QQbar(0)._descr.is_rational()
     4956            True
     4957        """
    41424958        return True
    41434959
    41444960    def rational_value(self):
     4961        r"""
     4962        Return self as a rational number.
     4963
     4964        EXAMPLE::
     4965
     4966            sage: a = QQbar(789/19)
     4967            sage: b = a._descr.rational_value(); b
     4968            789/19
     4969            sage: type(b)
     4970            <type 'sage.rings.rational.Rational'>
     4971        """
    41454972        return self._value
    41464973
    41474974    def exactify(self):
     4975        r"""
     4976        Calculate self exactly. Since self is a rational number, return self.
     4977
     4978        EXAMPLE::
     4979
     4980            sage: a = QQbar(1/3)._descr
     4981            sage: a.exactify() is a
     4982            True
     4983        """
    41484984        return self
    41494985
    41504986    def is_exact(self):
     4987        r"""
     4988        Return True, since rationals are exact.
     4989
     4990        EXAMPLE::
     4991
     4992            sage: QQbar(1/3)._descr.is_exact()
     4993            True
     4994        """
    41514995        return True
    41524996
    41534997    def is_simple(self):
     
    41655009        return True
    41665010
    41675011    def minpoly(self):
     5012        r"""
     5013        Return the min poly of self over `\QQ`.
     5014
     5015        EXAMPLE::
     5016
     5017            sage: QQbar(7)._descr.minpoly()
     5018            x - 7
     5019        """
    41685020        return QQx_x - self._value
    41695021
    41705022    def neg(self, n):
     5023        r"""
     5024        Negation of self.
     5025
     5026        EXAMPLE::
     5027
     5028            sage: a = QQbar(3)
     5029            sage: b = a._descr
     5030            sage: type(b)
     5031            <class 'sage.rings.qqbar.ANRational'>
     5032            sage: b.neg(a)
     5033            -3
     5034        """
    41715035        return ANRational(-self._value)
    41725036
    41735037    def invert(self, n):
     5038        r"""
     5039        1/self.
     5040
     5041        EXAMPLE::
     5042
     5043            sage: a = QQbar(3)
     5044            sage: b = a._descr
     5045            sage: b.invert(a)
     5046            1/3
     5047        """
    41745048        return ANRational(~self._value)
    41755049
    41765050    def abs(self, n):
     5051        r"""
     5052        Absolute value of self.
     5053
     5054        EXAMPLE::
     5055
     5056            sage: a = QQbar(3)
     5057            sage: b = a._descr
     5058            sage: b.abs(a)
     5059            3
     5060        """
    41775061        return ANRational(abs(self._value))
    41785062
    41795063    def rational_argument(self, n):
     5064        r"""
     5065        Return the argument of self divided by `2 \pi`, or ``None`` if this
     5066        element is 0.
     5067
     5068        EXAMPLE::
     5069
     5070            sage: QQbar(3)._descr.rational_argument(None)
     5071            0
     5072            sage: QQbar(-3)._descr.rational_argument(None)
     5073            1/2
     5074            sage: QQbar(0)._descr.rational_argument(None) is None
     5075            True
     5076        """
    41805077        if self._value > 0:
    41815078            return QQ(0)
    41825079        if self._value < 0:
     
    41845081        return None
    41855082
    41865083    def gaussian_value(self):
     5084        r"""
     5085        Return self as an element of `\QQ(i)`.
     5086
     5087        EXAMPLE::
     5088
     5089            sage: a = QQbar(3)
     5090            sage: b = a._descr
     5091            sage: x = b.gaussian_value(); x
     5092            3
     5093            sage: x.parent()
     5094            Number Field in I with defining polynomial x^2 + 1
     5095        """
    41875096        return QQbar_I_nf(self._value)
    41885097
    41895098    def angle(self):
     5099        r"""
     5100        Return a rational number `q \in (-1/2, 1/2]` such that ``self`` is a rational multiple of
     5101        `e^{2\pi i q}`. Always returns 0, since this element is rational.
     5102
     5103        EXAMPLE::
     5104
     5105            sage: QQbar(3)._descr.angle()
     5106            0
     5107            sage: QQbar(-3)._descr.angle()
     5108            0
     5109            sage: QQbar(0)._descr.angle()
     5110            0
     5111        """
    41905112        return QQ_0
    41915113
    41925114    def scale(self):
     5115        r"""
     5116        Return a rational number `r` such that ``self`` is equal to `r e^{2 \pi
     5117        i q}` for some `q \in (-1/2, 1/2]`.  In other words, just return self
     5118        as a rational number.
     5119
     5120        EXAMPLE::
     5121
     5122            sage: QQbar(-3)._descr.scale()
     5123            -3
     5124        """
    41935125        return self._value
    41945126
    41955127class ANRootOfUnity(ANDescr):
    41965128    r"""
    41975129    The subclass of ``ANDescr`` that represents a rational multiplied
    4198     by a root of unity.  This class is private, and should not be
     5130    by a root of unity. This class is private, and should not be
    41995131    used directly.
    42005132
    42015133    Such numbers are represented by a "rational angle" and a rational
    4202     scale.  The "rational angle" is the argument of the number, divided by
     5134    scale. The "rational angle" is the argument of the number, divided by
    42035135    `2\pi`; so given angle `\alpha` and scale `s`, the number is:
    42045136    `s(\cos(2\pi\alpha) + \sin(2\pi\alpha)i)`; or equivalently
    42055137    `s(e^{2\pi\alpha i})`.
    42065138
    42075139    We normalize so that `0<\alpha<\frac{1}{2}`; this requires
    4208     allowing both positive and negative scales.  (Attempts to create
     5140    allowing both positive and negative scales. (Attempts to create
    42095141    an ``ANRootOfUnity`` with an angle which is a multiple of
    42105142    `\frac{1}{2}` end up creating an ``ANRational`` instead.)
    42115143    """
     
    42135145    def __new__(self, angle, scale):
    42145146        r"""
    42155147        Construct an ``ANRootOfUnity`` from a rational angle and a rational
    4216         scale.  If the number is actually a real rational, returns an
     5148        scale. If the number is actually a real rational, returns an
    42175149        ``ANRational`` instead.
    42185150        """
    42195151        if scale.is_zero():
     
    42345166        """
    42355167        Construct an ``ANRootOfUnity`` from a rational angle and a rational
    42365168        scale.
    4237         """
    4238 
     5169
     5170        EXAMPLE::
     5171
     5172            sage: type((2/3 * QQbar.zeta(7))._descr) # indirect doctest
     5173            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5174        """
    42395175        angle2 = angle * 2
    42405176        fl2 = angle2.floor()
    42415177        angle2 = angle2 - fl2
     
    42595195        return (ANRootOfUnity, (self._angle, self._scale))
    42605196
    42615197    def _repr_(self):
     5198        r"""
     5199        String representation of this ``ANRootOfUnity`` element.
     5200
     5201        EXAMPLE::
     5202
     5203            sage: t = QQbar.zeta(3) * 5; type(t._descr)
     5204            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5205            sage: t._descr._repr_()
     5206            '5*e^(2*pi*I*1/3)'
     5207        """
    42625208        return "%s*e^(2*pi*I*%s)"%(self._scale, self._angle)
    42635209
    42645210    def handle_sage_input(self, sib, coerce, is_qqbar):
     
    43125258            return (v, True)
    43135259
    43145260    def kind(self):
     5261        r"""
     5262        Return a string describing what kind of element this is.
     5263
     5264        EXAMPLE::
     5265
     5266            sage: QQbar.zeta(4)._descr.kind()
     5267            'imaginary'
     5268            sage: QQbar.zeta(5)._descr.kind()
     5269            'rootunity'
     5270        """
    43155271        if self._angle == QQ_1_4:
    43165272            return 'imaginary'
    43175273        else:
    43185274            return 'rootunity'
    43195275
    43205276    def _interval_fast(self, prec):
     5277        r"""
     5278        Calculate an approximation to self in an interval field of precision prec.
     5279
     5280        EXAMPLE::
     5281
     5282            sage: QQbar.zeta(5)._descr._interval_fast(100)
     5283            0.30901699437494742410229341719? + 0.95105651629515357211643933338?*I
     5284        """
    43215285        argument = self._angle * RealIntervalField(prec).pi() * 2
    43225286        if self._angle == QQ_1_4:
    43235287            return ComplexIntervalField(prec)(0, self._scale)
     
    43255289            return ComplexIntervalField(prec)(argument.cos(), argument.sin()) * self._scale
    43265290
    43275291    def generator(self):
     5292        r"""
     5293        Return an :class:`AlgebraicGenerator` object corresponding to this element.
     5294
     5295        EXAMPLE::
     5296
     5297            sage: t = (QQbar.zeta(17)^13)._descr
     5298            sage: type(t)
     5299            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5300            sage: t.generator()
     5301            1*e^(2*pi*I*1/34)
     5302        """
    43285303        return cyclotomic_generator(self._angle.denominator())
    43295304
    43305305    def field_element_value(self):
     5306        r"""
     5307        Return self as an element of a cyclotomic field.
     5308
     5309        EXAMPLE::
     5310
     5311            sage: t = (QQbar.zeta(17)^13)._descr
     5312            sage: type(t)
     5313            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5314            sage: s = t.field_element_value(); s
     5315            -zeta34^9
     5316            sage: s.parent()
     5317            Cyclotomic Field of order 34 and degree 16
     5318        """
    43315319        gen = self.generator()
    43325320        f = gen._field
    43335321        a = f.gen()
    43345322        return self._scale * a ** self._angle.numerator()
    43355323
    43365324    def is_complex(self):
     5325        r"""
     5326        Return True, since this class is only used for complex algebraic numbers.
     5327
     5328        EXAMPLE::
     5329
     5330            sage: t = (QQbar.zeta(17)^13)._descr
     5331            sage: type(t)
     5332            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5333            sage: t.is_complex()
     5334            True
     5335        """
    43375336        return True
    43385337
    43395338    def exactify(self):
     5339        r"""
     5340        Return self, since ``ANRootOfUnity`` elements are exact.
     5341
     5342        EXAMPLE::
     5343
     5344            sage: t = (QQbar.zeta(17)^13)._descr
     5345            sage: type(t)
     5346            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5347            sage: t.exactify() is t
     5348            True
     5349        """
    43405350        return self
    43415351
    43425352    def is_exact(self):
     5353        r"""
     5354        Return True, since ``ANRootOfUnity`` elements are exact.
     5355
     5356        EXAMPLE::
     5357
     5358            sage: t = (QQbar.zeta(17)^13)._descr
     5359            sage: type(t)
     5360            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5361            sage: t.is_exact()
     5362            True
     5363        """
    43435364        return True
    43445365
    43455366    def is_simple(self):
     
    43775398        p = p / p.leading_coefficient()
    43785399        return p
    43795400
     5401    # These all ignore "n".
     5402
    43805403    def neg(self, n):
     5404        r"""
     5405        Negation of self.
     5406
     5407        EXAMPLE::
     5408
     5409            sage: a = QQbar.zeta(17)^5 * 4/3; a._descr
     5410            4/3*e^(2*pi*I*5/17)
     5411            sage: a._descr.neg(None)
     5412            -4/3*e^(2*pi*I*5/17)
     5413        """
    43815414        return ANRootOfUnity(self._angle, -self._scale)
    43825415
    43835416    def invert(self, n):
     5417        r"""
     5418        1/self.
     5419
     5420        EXAMPLE::
     5421
     5422            sage: a = QQbar.zeta(17)^5 * 4/3; a._descr
     5423            4/3*e^(2*pi*I*5/17)
     5424            sage: a._descr.invert(None)
     5425            -3/4*e^(2*pi*I*7/34)
     5426        """
    43845427        # We want ANRootOfUnity(-self._angle, ~self._scale);
    43855428        # but that's not normalized, so we pre-normalize it to:
    43865429        return ANRootOfUnity(QQ_1_2 - self._angle, -~self._scale)
    43875430
    43885431    def conjugate(self, n):
     5432        r"""
     5433        Complex conjugate of self.
     5434
     5435        EXAMPLE::
     5436
     5437            sage: a = QQbar.zeta(17)^5 * 4/3; a._descr
     5438            4/3*e^(2*pi*I*5/17)
     5439            sage: a._descr.conjugate(None)
     5440            -4/3*e^(2*pi*I*7/34)
     5441        """
    43895442        # We want ANRootOfUnity(-self._angle, self._scale);
    43905443        # but that's not normalized, so we pre-normalize it to:
    43915444        return ANRootOfUnity(QQ_1_2 - self._angle, -self._scale)
    43925445
    43935446    def abs(self, n):
     5447        r"""
     5448        Absolute value of self.
     5449
     5450        EXAMPLE::
     5451
     5452            sage: a = -QQbar.zeta(17)^5 * 4/3; a._descr
     5453            -4/3*e^(2*pi*I*5/17)
     5454            sage: a._descr.abs(None)
     5455            4/3
     5456        """
    43945457        return ANRational(abs(self._scale))
    43955458
    43965459    def norm(self, n):
     5460        r"""
     5461        Norm (square of absolute value) of self.
     5462
     5463        EXAMPLE::
     5464
     5465            sage: a = -QQbar.zeta(17)^5 * 4/3; a._descr
     5466            -4/3*e^(2*pi*I*5/17)
     5467            sage: a._descr.norm(None)
     5468            16/9
     5469        """
    43975470        return ANRational(self._scale * self._scale)
    43985471
    43995472    def rational_argument(self, n):
     5473        r"""
     5474        Return the rational `\theta \in (-1/2, 1/2)` such that self represents
     5475        a positive rational multiple of `e^{2 \pi i \theta}`.
     5476
     5477        EXAMPLE::
     5478
     5479            sage: (-QQbar.zeta(3))._descr.angle()
     5480            1/3
     5481            sage: (-QQbar.zeta(3))._descr.rational_argument(None)
     5482            -1/6
     5483        """
    44005484        if self._scale > 0:
    44015485            return self._angle
    44025486        else:
    44035487            return self._angle - QQ_1_2
    44045488   
    44055489    def gaussian_value(self):
     5490        r"""
     5491        Return self as an element of `\QQ(i)`` (assuming this is possible).
     5492
     5493        EXAMPLE::
     5494
     5495            sage: (-17*QQbar.zeta(4))._descr.gaussian_value()
     5496            -17*I
     5497            sage: (-17*QQbar.zeta(5))._descr.gaussian_value()
     5498            Traceback (most recent call last):
     5499            ...
     5500            AssertionError
     5501        """
    44065502        assert(self._angle == QQ_1_4)
    44075503        return QQbar_I_nf(self._scale * QQbar_I_nf.gen())
    44085504
    44095505    def angle(self):
     5506        r"""
     5507        Return the rational `\theta \in [0, 1/2)` such that self represents a
     5508        rational multiple of `e^{2 \pi i \theta}`.
     5509
     5510        EXAMPLE::
     5511
     5512            sage: (-QQbar.zeta(3))._descr.angle()
     5513            1/3
     5514            sage: (-QQbar.zeta(3))._descr.rational_argument(None)
     5515            -1/6
     5516        """
    44105517        return self._angle
    44115518
    44125519    def scale(self):
     5520        r"""
     5521        Return the scale of self, the unique rational `r` such that self is
     5522        equal to `re^{2\pi i \theta}` for some `theta \in (-1/2, 1/2]`. This is
     5523        `\pm 1` times ``self.abs()``.
     5524
     5525        EXAMPLE::
     5526
     5527            sage: (QQbar.zeta(5)^3)._descr.scale()
     5528            -1
     5529        """
    44135530        return self._scale
    44145531
    44155532def is_AlgebraicReal(x):
     5533    r"""
     5534    Test if ``x`` is an instance of :class:`~AlgebraicReal`. For internal use.
     5535
     5536    EXAMPLE::
     5537
     5538        sage: from sage.rings.qqbar import is_AlgebraicReal
     5539        sage: is_AlgebraicReal(AA(sqrt(2)))
     5540        True
     5541        sage: is_AlgebraicReal(QQbar(sqrt(2)))
     5542        False
     5543        sage: is_AlgebraicReal("spam")
     5544        False
     5545    """
    44165546    return isinstance(x, AlgebraicReal)
    44175547
    44185548def is_AlgebraicNumber(x):
     5549    r"""
     5550    Test if ``x`` is an instance of :class:`~AlgebraicNumber`. For internal use.
     5551
     5552    EXAMPLE::
     5553
     5554        sage: from sage.rings.qqbar import is_AlgebraicNumber
     5555        sage: is_AlgebraicNumber(AA(sqrt(2)))
     5556        False
     5557        sage: is_AlgebraicNumber(QQbar(sqrt(2)))
     5558        True
     5559        sage: is_AlgebraicNumber("spam")
     5560        False
     5561    """
    44195562    return isinstance(x, AlgebraicNumber)
    44205563
    44215564QQbarPoly = PolynomialRing(QQbar, 'x')
     
    44275570
    44285571    If multiple algebraic numbers are created as roots of a single
    44295572    polynomial, this allows the polynomial and information about
    4430     the polynomial to be shared.  This reduces work if the polynomial
     5573    the polynomial to be shared. This reduces work if the polynomial
    44315574    must be recomputed at higher precision, or if it must be factored.
    44325575
    44335576    This class is private, and should only be constructed by
    44345577    ``AA.common_polynomial()`` or ``QQbar.common_polynomial()``, and should
    44355578    only be used as an argument to ``AA.polynomial_root()`` or
    4436     ``QQbar.polynomial_root()``.  (It doesn't matter whether you create
     5579    ``QQbar.polynomial_root()``. (It doesn't matter whether you create
    44375580    the common polynomial with ``AA.common_polynomial()`` or
    44385581    ``QQbar.common_polynomial()``.)
    44395582
     
    44485591    """
    44495592
    44505593    def __init__(self, poly):
     5594        r"""
     5595        Initialize this AlgebraicPolynomialTracker object.
     5596
     5597        EXAMPLE::
     5598
     5599            sage: x = polygen(QQbar)
     5600            sage: P = QQbar.common_polynomial(x^2 - x - 1)
     5601            sage: type(P) # indirect doctest
     5602            <class 'sage.rings.qqbar.AlgebraicPolynomialTracker'>
     5603        """
    44515604        if not is_Polynomial(poly):
    4452             raise ValueError, "Trying to create AlgebraicPolynomialTracker on non-Polynomial"
     5605            raise ValueError("Trying to create AlgebraicPolynomialTracker on non-Polynomial")
    44535606        if isinstance(poly.base_ring(), AlgebraicField_common):
    44545607            complex = is_AlgebraicField(poly.base_ring())
    44555608        else:
     
    45025655            {call: {getattr: {atomic:AA}.common_polynomial}({binop:- {binop:* {call: {atomic:sqrt}({call: {atomic:AA}({atomic:2})})} {binop:** {gen:x {constr_parent: {subscr: {atomic:AA}[{atomic:'x'}]} with gens: ('x',)}} {atomic:2}}} {call: {atomic:sqrt}({call: {atomic:AA}({atomic:3})})}})}
    45035656        """
    45045657        # XXX It would be nicer to skip the "AA.common_polynomial()"
    4505         # wrapper if the polynomial is not actually shared.  But
     5658        # wrapper if the polynomial is not actually shared. But
    45065659        # sage_input.py isn't quite that generic.
    45075660        v = sib.name('AA').common_polynomial(self._poly)
    45085661        sib.id_cache(self, v, 'cp')
    45095662        return v
    45105663
    45115664    def _repr_(self):
     5665        r"""
     5666        String representation of self.
     5667
     5668        EXAMPLE::
     5669
     5670            sage: x = polygen(QQ)
     5671            sage: AA.common_polynomial(x^3 - 7)._repr_()
     5672            'x^3 - 7'
     5673        """
    45125674        return repr(self._poly)
    45135675
    45145676    def poly(self):
     5677        r"""
     5678        Return the underlying polynomial of self.
     5679
     5680        EXAMPLE::
     5681
     5682            sage: x = polygen(QQ); f = x^3 - 7
     5683            sage: g = AA.common_polynomial(f)
     5684            sage: g.poly() == f
     5685            True
     5686        """
    45155687        return self._poly
    45165688
    45175689    def is_complex(self):
     5690        r"""
     5691        Return True if the coefficients of this polynomial are non-real.
     5692
     5693        EXAMPLE::
     5694
     5695            sage: x = polygen(QQ); f = x^3 - 7
     5696            sage: g = AA.common_polynomial(f)
     5697            sage: g.is_complex()
     5698            False
     5699            sage: QQbar.common_polynomial(x^3 - QQbar(I)).is_complex()
     5700            True
     5701        """
    45185702        return self._complex
    45195703
    45205704    def complex_roots(self, prec, multiplicity):
    45215705        """
     5706        Find the roots of self in the complex field to precision prec.
     5707
    45225708        EXAMPLES::
    45235709
    45245710            sage: x = polygen(ZZ)
     
    45545740        Compute a common field that holds all of the algebraic coefficients
    45555741        of this polynomial, then factor the polynomial over that field.
    45565742        Store the factors for later use (ignoring multiplicity).
     5743
     5744        EXAMPLE::
     5745
     5746            sage: x = polygen(AA)
     5747            sage: p = sqrt(AA(2)) * x^2 - sqrt(AA(3))
     5748            sage: cp = AA.common_polynomial(p)
     5749            sage: cp._exact
     5750            False
     5751            sage: cp.exactify()
     5752            sage: cp._exact
     5753            True
    45575754        """
    45585755        if self._exact:
    45595756            return
     
    45825779            self._factors = [fac_exp[0] for fac_exp in fp.factor()]
    45835780
    45845781    def factors(self):
     5782        r"""
     5783        EXAMPLE::
     5784
     5785            sage: x=polygen(QQ); f=QQbar.common_polynomial(x^4 + 4)
     5786            sage: f.factors()
     5787            [y^2 - 2*y + 2, y^2 + 2*y + 2]
     5788        """
    45855789        self.exactify()
    45865790        return self._factors
    45875791
    45885792    def generator(self):
     5793        r"""
     5794        Return an :class:`AlgebraicGenerator` for a number field containing all
     5795        the coefficients of self.
     5796
     5797        EXAMPLE::
     5798
     5799            sage: x = polygen(AA)
     5800            sage: p = sqrt(AA(2)) * x^2 - sqrt(AA(3))
     5801            sage: cp = AA.common_polynomial(p)
     5802            sage: cp.generator()
     5803            Number Field in a with defining polynomial y^4 - 4*y^2 + 1 with a in 1.931851652578137?
     5804        """
    45895805        self.exactify()
    45905806        return self._gen
    45915807
     
    45965812    This class is private, and should not be used directly.
    45975813    """
    45985814    def __init__(self, poly, interval, multiplicity=1, is_pow=None):
     5815        r"""
     5816        Initialize this ``ANRoot`` object.
     5817
     5818        EXAMPLE::
     5819
     5820            sage: x = polygen(QQ); f = (x^3 + x + 1).roots(AA,multiplicities=False)[0]._descr
     5821            sage: type(f) # indirect doctest
     5822            <class 'sage.rings.qqbar.ANRoot'>
     5823        """
    45995824        if not isinstance(poly, AlgebraicPolynomialTracker):
    46005825            poly = AlgebraicPolynomialTracker(poly)
    46015826        self._poly = poly
     
    46215846        return (ANRoot, (self._poly, self._interval, self._multiplicity))
    46225847
    46235848    def _repr_(self):
     5849        r"""
     5850        String representation of self.
     5851
     5852        EXAMPLE::
     5853
     5854            sage: x=polygen(QQ); v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]
     5855            sage: v._descr._repr_()
     5856            'Root 1.618033988749894849? of x^2 - x - 1'
     5857        """
    46245858        return 'Root %s of %s'%(self._interval, self._poly)
    46255859
    46265860    def handle_sage_input(self, sib, coerce, is_qqbar):
     
    46355869            # Verified
    46365870            sqrt(AA(3)).nth_root(3)
    46375871
    4638         These two examples are too big to verify quickly.  (Verification
     5872        These two examples are too big to verify quickly. (Verification
    46395873        would create a field of degree 28.)::
    46405874
    46415875            sage: sage_input((sqrt(AA(3))^(5/7))^(9/4))
     
    46925926        return (parent.polynomial_root(poly, sib(good_intv)), True)
    46935927
    46945928    def kind(self):
     5929        r"""
     5930        Return a string indicating what kind of element this is.
     5931
     5932        EXAMPLE::
     5933
     5934            sage: (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.kind()
     5935            'other'
     5936        """
    46955937        return 'other'
    46965938
    46975939    def is_complex(self):
     5940        r"""
     5941        Whether this is a root in `\overline{\QQ}` (rather than `\mathbf{A}`).
     5942        Note that this may return True even if the root is actually real, as
     5943        the second example shows; it does *not* trigger exact computation to
     5944        see if the root is real.
     5945
     5946        EXAMPLE::
     5947
     5948            sage: x = polygen(QQ)
     5949            sage: (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.is_complex()
     5950            False
     5951            sage: (x^2 - x - 1).roots(ring=QQbar, multiplicities=False)[1]._descr.is_complex()
     5952            True
     5953        """
    46985954        return self._complex
    46995955
    47005956    def conjugate(self, n):
     5957        r"""
     5958        Complex conjugate of this ANRoot object.
     5959
     5960        EXAMPLE::
     5961
     5962            sage: a = (x^2 + 23).roots(ring=QQbar, multiplicities=False)[0]
     5963            sage: b = a._descr
     5964            sage: type(b)
     5965            <class 'sage.rings.qqbar.ANRoot'>
     5966            sage: c = b.conjugate(a); c
     5967            <class 'sage.rings.qqbar.ANUnaryExpr'>
     5968            sage: c.exactify()
     5969            -2*a + 1 where a^2 - a + 6 = 0 and a in 0.50000000000000000? - 2.397915761656360?*I
     5970        """
    47015971        if not self._complex:
    47025972            return self
    47035973        if not self._complex_poly:
     
    47065976        return ANUnaryExpr(n, 'conjugate')
    47075977
    47085978    def refine_interval(self, interval, prec):
     5979        r"""
     5980        Takes an interval which is assumed to enclose exactly one root
     5981        of the polynomial (or, with multiplicity=`k`, exactly one root
     5982        of the `k-1`-st derivative); and a precision, in bits.
     5983
     5984        Tries to find a narrow interval enclosing the root using
     5985        interval arithmetic of the given precision. (No particular
     5986        number of resulting bits of precision is guaranteed.)
     5987
     5988        Uses a combination of Newton's method (adapted for interval
     5989        arithmetic) and bisection. The algorithm will converge very
     5990        quickly if started with a sufficiently narrow interval.
     5991
     5992        EXAMPLES::
     5993
     5994            sage: from sage.rings.qqbar import ANRoot
     5995            sage: x = polygen(AA)
     5996            sage: rt2 = ANRoot(x^2 - 2, RIF(0, 2))
     5997            sage: rt2.refine_interval(RIF(0, 2), 75)
     5998            1.4142135623730950488017?
     5999        """
    47096000        if self._complex or self._complex_poly:
    47106001            v = self._complex_refine_interval(interval, prec)
    47116002            if self._complex:
     
    47176008
    47186009    def _real_refine_interval(self, interval, prec):
    47196010        r"""
    4720         Takes an interval which is assumed to enclose exactly one root
    4721         of the polynomial (or, with multiplicity=`k`, exactly one root
    4722         of the `k-1`-st derivative); and a precision, in bits.
    4723 
    4724         Tries to find a narrow interval enclosing the root using
    4725         interval arithmetic of the given precision.  (No particular
    4726         number of resulting bits of precision is guaranteed.)
    4727 
    4728         Uses a combination of Newton's method (adapted for interval
    4729         arithmetic) and bisection.  The algorithm will converge very
    4730         quickly if started with a sufficiently narrow interval.
     6011        Does the calculation for ``refine_interval``.
    47316012
    47326013        EXAMPLES::
    47336014
    47346015            sage: from sage.rings.qqbar import ANRoot
    47356016            sage: x = polygen(AA)
    47366017            sage: rt2 = ANRoot(x^2 - 2, RIF(0, 2))
    4737             sage: rt2.refine_interval(RIF(0, 2), 75)
     6018            sage: rt2.refine_interval(RIF(0, 2), 75) # indirect doctest
    47386019            1.4142135623730950488017?
    47396020        """
    47406021        # Don't throw away bits in the original interval; doing so might
     
    48066087                # print interval_p
    48076088                # print linfo['endpoint'], linfo['value'], linfo['sign']
    48086089                # print uinfo['endpoint'], uinfo['value'], uinfo['sign']
    4809                 raise ValueError, "Refining interval that does not bound unique root!"
     6090                raise ValueError("Refining interval that does not bound unique root!")
    48106091
    48116092            # Use a simple algorithm:
    4812             # Try an interval Newton-Raphson step.  If this does not add at
     6093            # Try an interval Newton-Raphson step. If this does not add at
    48136094            # least one bit of information, or if it fails (because the
    48146095            # slope is not bounded away from zero), then try bisection.
    48156096            # If this fails because the value at the midpoint is not
     
    48996180        of the `k-1`-st derivative); and a precision, in bits.
    49006181
    49016182        Tries to find a narrow interval enclosing the root using
    4902         interval arithmetic of the given precision.  (No particular
     6183        interval arithmetic of the given precision. (No particular
    49036184        number of resulting bits of precision is guaranteed.)
    49046185
    4905         Uses Newton's method (adapted for interval arithmetic).  The
     6186        Uses Newton's method (adapted for interval arithmetic). The
    49066187        algorithm will converge very quickly if started with a
    4907         sufficiently narrow interval.  If Newton's method fails, then
     6188        sufficiently narrow interval. If Newton's method fails, then
    49086189        we falls back on computing all the roots of the polynomial
    49096190        numerically, and select the appropriate root.
    49106191
     
    49146195            sage: x = polygen(QQbar)
    49156196            sage: intv = CIF(RIF(0, 1), RIF(0.1, 1))
    49166197            sage: rt = ANRoot(x^5 - 1, intv)
    4917             sage: new_intv = rt.refine_interval(intv, 53); new_intv
     6198            sage: new_intv = rt.refine_interval(intv, 53); new_intv # indirect doctest
    49186199            0.3090169943749474241? + 0.951056516295153573?*I
    49196200            sage: rt.refine_interval(new_intv, 70)
    49206201            0.30901699437494742411? + 0.95105651629515357212?*I
     
    49726253                new_diam = interval.diameter()
    49736254
    49746255                if new_diam == 0:
    4975                     # Wow; we nailed it exactly.  (This may happen
     6256                    # Wow; we nailed it exactly. (This may happen
    49766257                    # whenever the root is exactly equal to some
    49776258                    # floating-point number, and cannot happen
    49786259                    # if the root is not equal to a floating-point
     
    49806261                    return interval
    49816262
    49826263                if new_diam == diam:
    4983                     # We're not getting any better.  There are two
    4984                     # possible reasons for this.  Either we have
     6264                    # We're not getting any better. There are two
     6265                    # possible reasons for this. Either we have
    49856266                    # refined as much as possible given the imprecision
    49866267                    # of our interval polynomial, and we have the best
    49876268                    # answer we're going to get at this precision;
     
    49926273
    49936274                    # I do not have a formal proof, but I believe the
    49946275                    # following test differentiates between these two
    4995                     # behaviors.  (If I'm wrong, we might get bad behavior
     6276                    # behaviors. (If I'm wrong, we might get bad behavior
    49966277                    # like infinite loops, but we still won't actually
    49976278                    # return a wrong answer.)
    49986279
     
    50056286                        return interval
    50066287
    50076288                    # The center of the current interval is known
    5008                     # not to be a root.  This should let us divide
     6289                    # not to be a root. This should let us divide
    50096290                    # the interval in half, and improve on our previous
    5010                     # estimates.  I can only think of two reasons why
     6291                    # estimates. I can only think of two reasons why
    50116292                    # it might not:
    50126293                    # 1) the "center" of the interval is actually
    50136294                    # on one of the edges of the interval (because the
     
    50326313                    # whether the diameter is less than pi/2; in that
    50336314                    # case, no matter the value of "val" (as long as
    50346315                    # "val" is fairly precise), "val / slope" should
    5035                     # be bounded away from zero.  But we compare
     6316                    # be bounded away from zero. But we compare
    50366317                    # against 1 instead, in the hopes that this might
    50376318                    # be slightly faster.
    50386319
     
    50466327        """
    50476328        Find a precise approximation to the unique root in interval,
    50486329        by finding a precise approximation to all roots of the
    5049         polynomial, and checking which one is in interval.  Slow but sure.
     6330        polynomial, and checking which one is in interval. Slow but sure.
    50506331
    50516332        EXAMPLES::
    50526333
     
    50666347            return our_root[0]
    50676348
    50686349        if len(our_root) == 0:
    5069             raise ValueError, "Complex root interval does not include any roots"
     6350            raise ValueError("Complex root interval does not include any roots")
    50706351
    50716352        # We have more than one root that overlap the current interval.
    50726353        # Technically, this might not be an error; perhaps the actual
     
    50766357        # But it seems far more likely that the provided interval is
    50776358        # just too big.
    50786359
    5079         raise ValueError, "Complex root interval probably includes multiple roots"
     6360        raise ValueError("Complex root interval probably includes multiple roots")
    50806361
    50816362    def exactify(self):
    50826363        """
     
    51896470       
    51906471    def _more_precision(self):
    51916472        """
    5192         Recompute the interval enclosing this root at higher
     6473        Recompute the interval enclosing this ``ANRoot`` object at higher
    51936474        precision.
     6475
     6476        EXAMPLE::
     6477
     6478            sage: x = polygen(QQ); y = (x^3 + x + 1).roots(AA,multiplicities=False)[0]
     6479            sage: z = y._descr
     6480            sage: z._interval.prec()
     6481            64
     6482            sage: z._more_precision()
     6483            sage: z._interval.prec()
     6484            128
    51946485        """
    51956486        prec = self._interval.prec()
    51966487        self._interval = self.refine_interval(self._interval, prec*2)
     
    51996490        """
    52006491        Given a RealIntervalField, compute the value of this number
    52016492        using interval arithmetic of at least the precision of the field,
    5202         and return the value in that field.  (More precision may be used
     6493        and return the value in that field. (More precision may be used
    52036494        in the computation.)
     6495
     6496        EXAMPLE::
     6497
     6498            sage: x = polygen(QQ); y = (x^3 + x + 1).roots(AA,multiplicities=False)[0]._descr
     6499            sage: y._interval_fast(128)
     6500            -0.68232780382801932736948373971104825689?
    52046501        """
    52056502        if prec == self._interval.prec():
    52066503            return self._interval
     
    52136510
    52146511_cyclotomic_gen_cache = {}
    52156512def cyclotomic_generator(n):
     6513    r"""
     6514    Return an :class:`AlgebraicGenerator` object corresponding to the generator
     6515    `e^{2 \pi I / n}` of the `n`-th cyclotomic field.
     6516
     6517    EXAMPLE::
     6518
     6519        sage: from sage.rings.qqbar import cyclotomic_generator
     6520        sage: g=cyclotomic_generator(7); g
     6521        1*e^(2*pi*I*1/7)
     6522        sage: type(g)
     6523        <class 'sage.rings.qqbar.AlgebraicGenerator'>
     6524    """
    52166525    try:
    52176526        return _cyclotomic_gen_cache[n]
    52186527    except KeyError:
     
    52286537class ANExtensionElement(ANDescr):
    52296538    r"""
    52306539    The subclass of ``ANDescr`` that represents a number field
    5231     element in terms of a specific generator.  Consists of a polynomial
     6540    element in terms of a specific generator. Consists of a polynomial
    52326541    with rational coefficients in terms of the generator, and the
    52336542    generator itself, an ``AlgebraicGenerator``.
    52346543    """
     
    53176626        rt = sib(self._generator.root_as_algebraic())
    53186627        # For the best fidelity, we really ought to somehow ensure
    53196628        # that rt is exactified, but sage_input doesn't support that
    5320         # nicely.  Skip it for now.
     6629        # nicely. Skip it for now.
    53216630        # The following is copied with slight mods from polynomial_element.pyx
    53226631        coeffs = [sib(c, True) for c in self._value.list()]
    53236632        terms = []
     
    53366645        return (v, True)
    53376646       
    53386647    def kind(self):
     6648        r"""
     6649        Return a string describing what kind of element this is.
     6650
     6651        EXAMPLE::
     6652
     6653            sage: x = QQbar(sqrt(2) + sqrt(3))
     6654            sage: x.exactify()
     6655            sage: x._descr.kind()
     6656            'element'
     6657            sage: x = QQbar(I) + 1
     6658            sage: x.exactify()
     6659            sage: x._descr.kind()
     6660            'gaussian'
     6661        """
    53396662        if self._generator is QQbar_I_generator:
    53406663            return 'gaussian'
    53416664        else:
    53426665            return 'element'
    53436666
    53446667    def is_complex(self):
     6668        r"""
     6669        Return True if the number field that defines this element is not real.
     6670        This does not imply that the element itself is definitely non-real, as
     6671        in the example below.
     6672
     6673        EXAMPLE::
     6674
     6675            sage: rt2 = QQbar(sqrt(2))
     6676            sage: rtm3 = QQbar(sqrt(-3))
     6677            sage: x = rtm3 + rt2 - rtm3
     6678            sage: x.exactify()
     6679            sage: y = x._descr
     6680            sage: type(y)
     6681            <class 'sage.rings.qqbar.ANExtensionElement'>
     6682            sage: y.is_complex()
     6683            True
     6684            sage: x.imag() == 0
     6685            True
     6686        """
    53456687        return not self._exactly_real
    53466688
    53476689    def is_exact(self):
     6690        r"""
     6691        Return True, since ANExtensionElements are exact.
     6692
     6693        EXAMPLE::
     6694
     6695            sage: rt2 = QQbar(sqrt(2))
     6696            sage: rtm3 = QQbar(sqrt(-3))
     6697            sage: x = rtm3 + rt2 - rtm3
     6698            sage: x.exactify()
     6699            sage: y = x._descr
     6700            sage: type(y)
     6701            <class 'sage.rings.qqbar.ANExtensionElement'>
     6702            sage: y.is_exact()
     6703            True
     6704        """
    53486705        return True
    53496706
    53506707    def is_simple(self):
     
    53806737            return self._is_simple
    53816738
    53826739    def is_field_element(self):
     6740        r"""
     6741        Return True if self is an element of a number field (always true for ANExtensionElements)
     6742
     6743        EXAMPLE::
     6744
     6745            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6746            sage: v.is_field_element()
     6747            True
     6748        """
    53836749        return True
    53846750
    53856751    def generator(self):
     6752        r"""
     6753        Return the :class:`~AlgebraicGenerator` object corresponding to self.
     6754
     6755        EXAMPLE::
     6756
     6757            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6758            sage: v.generator()
     6759            Number Field in a with defining polynomial y^2 - y - 1 with a in 1.618033988749895?
     6760        """
    53866761        return self._generator
    53876762
    53886763    def exactify(self):
     6764        r"""
     6765        Return an exact representation of self. Since self is already exact,
     6766        just return self.
     6767
     6768        EXAMPLE::
     6769
     6770            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6771            sage: type(v)
     6772            <class 'sage.rings.qqbar.ANExtensionElement'>
     6773            sage: v.exactify() is v
     6774            True
     6775        """
    53896776        return self
    53906777
    53916778    def field_element_value(self):
     6779        r"""
     6780        Return the underlying number field element.
     6781
     6782        EXAMPLE::
     6783
     6784            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6785            sage: v.field_element_value()
     6786            a
     6787        """
    53926788        return self._value
    53936789
    53946790    def minpoly(self):
     
    53976793
    53986794        EXAMPLES::
    53996795
    5400             sage: a = AA(sqrt(2)) + QQbar(I); a
    5401             1.414213562373095? + 1*I
    5402             sage: p = a.minpoly(); p
    5403             x^4 - 2*x^2 + 9
    5404             sage: p(a)
    5405             0
     6796            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6797            sage: type(v)
     6798            <class 'sage.rings.qqbar.ANExtensionElement'>
     6799            sage: v.minpoly()
     6800            x^2 - x - 1
    54066801        """
    54076802        try:
    54086803            return self._minpoly
     
    54356830        if self.is_simple():
    54366831            return self
    54376832
    5438         # This is very inefficient... 
     6833        # This is very inefficient...
    54396834        # for instance, the .exactify() call will try to factor poly,
    54406835        # even though we know that poly is irreducible
    54416836        poly = self.minpoly()
     
    54516846            return v.real()
    54526847        return v
    54536848
     6849    # for these three functions the argument n is not used (but it is there
     6850    # anyway for compatibility)
     6851
    54546852    def neg(self, n):
     6853        r"""
     6854        Negation of self.
     6855
     6856        EXAMPLE::
     6857
     6858            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     6859            sage: a.exactify()
     6860            sage: b = a._descr
     6861            sage: type(b)
     6862            <class 'sage.rings.qqbar.ANExtensionElement'>
     6863            sage: b.neg(a)
     6864            1/2*a^3 - a^2 + 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? - 0.7071067811865475?*I
     6865            sage: b.neg("ham spam and eggs")
     6866            1/2*a^3 - a^2 + 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? - 0.7071067811865475?*I
     6867        """
    54556868        return ANExtensionElement(self._generator, -self._value)
    54566869
    54576870    def invert(self, n):
     6871        r"""
     6872        1/self.
     6873
     6874        EXAMPLE::
     6875
     6876            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     6877            sage: a.exactify()
     6878            sage: b = a._descr
     6879            sage: type(b)
     6880            <class 'sage.rings.qqbar.ANExtensionElement'>
     6881            sage: b.invert(a)
     6882            -1/2*a^3 - a^2 + 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? - 0.7071067811865475?*I
     6883            sage: b.invert("ham spam and eggs")
     6884            -1/2*a^3 - a^2 + 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? - 0.7071067811865475?*I
     6885        """
    54586886        return ANExtensionElement(self._generator, ~self._value)
    54596887
    54606888    def conjugate(self, n):
     6889        r"""
     6890        Negation of self.
     6891
     6892        EXAMPLE::
     6893
     6894            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     6895            sage: a.exactify()
     6896            sage: b = a._descr
     6897            sage: type(b)
     6898            <class 'sage.rings.qqbar.ANExtensionElement'>
     6899            sage: b.conjugate(a)
     6900            -1/2*a^3 + a^2 - 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? + 0.7071067811865475?*I
     6901            sage: b.conjugate("ham spam and eggs")
     6902            -1/2*a^3 + a^2 - 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? + 0.7071067811865475?*I
     6903        """
    54616904        if self._exactly_real:
    54626905            return self
    54636906        else:
    54646907            return ANExtensionElement(self._generator.conjugate(), self._value)
    54656908
     6909    # The rest of these unary operations do actually use n, which is an
     6910    # AlgebraicNumber pointing to self.
     6911
    54666912    def norm(self, n):
     6913        r"""
     6914        Norm of self (square of complex absolute value)
     6915
     6916        EXAMPLE::
     6917
     6918            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     6919            sage: a.exactify()
     6920            sage: b = a._descr
     6921            sage: type(b)
     6922            <class 'sage.rings.qqbar.ANExtensionElement'>
     6923            sage: b.norm(a)
     6924            <class 'sage.rings.qqbar.ANUnaryExpr'>
     6925        """
    54676926        if self._exactly_real:
    54686927            return (n*n)._descr
    54696928        elif self._generator is QQbar_I_generator:
     
    54726931            return ANUnaryExpr(n, 'norm')
    54736932
    54746933    def abs(self, n):
     6934        r"""
     6935        Return the absolute value of self (square root of the norm).
     6936
     6937        EXAMPLE::
     6938
     6939            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     6940            sage: a.exactify()
     6941            sage: b = a._descr
     6942            sage: type(b)
     6943            <class 'sage.rings.qqbar.ANExtensionElement'>
     6944            sage: b.abs(a)
     6945            Root 3.146264369941972342? of x^2 - 9.89897948556636?
     6946        """
    54756947        return AlgebraicReal(self.norm(n)).sqrt()._descr
    54766948
    54776949    def rational_argument(self, n):
    54786950        r"""
    5479         If the argument of self is `2\pi` times some rational number,
    5480         return that rational; otherwise, return None.
    5481         """
    5482 
     6951        If the argument of self is `2\pi` times some rational number in `[1/2,
     6952        -1/2)`, return that rational; otherwise, return ``None``.
     6953
     6954        EXAMPLE::
     6955
     6956            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(3))
     6957            sage: a.exactify()
     6958            sage: b = a._descr
     6959            sage: type(b)
     6960            <class 'sage.rings.qqbar.ANExtensionElement'>
     6961            sage: b.rational_argument(a) is None
     6962            True
     6963            sage: x = polygen(QQ)
     6964            sage: a = (x^4 + 1).roots(QQbar, multiplicities=False)[0]
     6965            sage: a.exactify()
     6966            sage: b = a._descr
     6967            sage: b.rational_argument(a)
     6968            -3/8
     6969        """
    54836970        # If the argument of self is 2*pi times some rational number a/b,
    54846971        # then self/abs(self) is a root of the b'th cyclotomic polynomial.
    54856972        # This implies that the algebraic degree of self is at least
    5486         # phi(b).  Working backward, we know that the algebraic degree
     6973        # phi(b). Working backward, we know that the algebraic degree
    54876974        # of self is at most the degree of the generator, so that gives
    5488         # an upper bound on phi(b).  According to
     6975        # an upper bound on phi(b). According to
    54896976        # http://mathworld.wolfram.com/TotientFunction.html,
    54906977        # phi(b) >= sqrt(b) for b > 6; this gives us an upper bound on b.
    54916978        # We then check to see if this is possible; if so, we test
     
    55157002        raise NotImplementedError
    55167003
    55177004    def gaussian_value(self):
     7005        r"""
     7006        Return self as an element of `\QQ(i)`.
     7007
     7008        EXAMPLE::
     7009
     7010            sage: a = QQbar(I) + 3/7
     7011            sage: a.exactify()
     7012            sage: b = a._descr
     7013            sage: type(b)
     7014            <class 'sage.rings.qqbar.ANExtensionElement'>
     7015            sage: b.gaussian_value()
     7016            I + 3/7
     7017
     7018        A non-example::
     7019
     7020            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     7021            sage: a.exactify()
     7022            sage: b = a._descr
     7023            sage: type(b)
     7024            <class 'sage.rings.qqbar.ANExtensionElement'>
     7025            sage: b.gaussian_value()
     7026            Traceback (most recent call last):
     7027            ...
     7028            AssertionError
     7029        """
    55187030        assert(self._generator is QQbar_I_generator)
    55197031        return self._value
    55207032
    55217033class ANUnaryExpr(ANDescr):
    55227034    def __init__(self, arg, op):
     7035        r"""
     7036        Initialize this ANUnaryExpr.
     7037
     7038        EXAMPLE::
     7039
     7040            sage: t = ~QQbar(sqrt(2)); type(t._descr) # indirect doctest
     7041            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7042        """
    55237043        self._arg = arg
    55247044        self._op = op
    55257045        self._complex = True
     
    56147134        return (v, True)
    56157135
    56167136    def kind(self):
     7137        r"""
     7138        Return a string describing what kind of element this is.
     7139
     7140        EXAMPLE::
     7141
     7142            sage: x = -QQbar(sqrt(2))
     7143            sage: y = x._descr
     7144            sage: type(y)
     7145            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7146            sage: y.kind()
     7147            'other'
     7148        """
    56177149        return 'other'
    56187150
    56197151    def is_complex(self):
     7152        r"""
     7153        Return whether or not this element is complex. Note that this is a data
     7154        type check, and triggers no computations -- if it returns False, the
     7155        element might still be real, it just doesn't know it yet.
     7156
     7157        EXAMPLE::
     7158
     7159            sage: t = AA(sqrt(2))
     7160            sage: s = (-t)._descr
     7161            sage: s
     7162            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7163            sage: s.is_complex()
     7164            False
     7165            sage: QQbar(-sqrt(2))._descr.is_complex()
     7166            True
     7167        """
    56207168        return self._complex
    56217169
    56227170    def _interval_fast(self, prec):
     7171        r"""
     7172        Calculate an approximation to this ``ANUnaryExpr`` object in an interval field of precision ``prec``.
     7173
     7174        EXAMPLE::
     7175
     7176            sage: t = AA(sqrt(2))
     7177            sage: s = (-t)._descr
     7178            sage: s
     7179            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7180            sage: s._interval_fast(150)
     7181            -1.414213562373095048801688724209698078569671876?
     7182        """
    56237183        op = self._op
    56247184
    56257185        v = self._arg._interval_fast(prec)
     
    56657225        raise NotImplementedError
    56667226
    56677227    def exactify(self):
     7228        r"""
     7229        Trigger exact computation of self.
     7230
     7231        EXAMPLE::
     7232
     7233            sage: v = (-QQbar(sqrt(2)))._descr
     7234            sage: type(v)
     7235            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7236            sage: v.exactify()
     7237            -a where a^2 - 2 = 0 and a in 1.414213562373095?
     7238        """
    56687239        op = self._op
    56697240        arg = self._arg
    56707241
     
    57207291
    57217292class ANBinaryExpr(ANDescr):
    57227293    def __init__(self, left, right, op):
     7294        r"""
     7295        Initialize this ANBinaryExpr.
     7296
     7297        EXAMPLE::
     7298
     7299            sage: t = QQbar(sqrt(2)) + QQbar(sqrt(3)); type(t._descr) # indirect doctest
     7300            <class 'sage.rings.qqbar.ANBinaryExpr'>
     7301        """
    57237302        self._left = left
    57247303        self._right = right
    57257304        self._op = op
     
    57957374        op = self._op
    57967375
    57977376        # We want 2+QQbar.zeta(3) and QQbar.zeta(3)+2, not
    5798         # QQbar(2)+QQbar.zeta(3).  So we want to pass coerced=True to
     7377        # QQbar(2)+QQbar.zeta(3). So we want to pass coerced=True to
    57997378        # an argument if it is rational (but if both arguments are
    58007379        # rational, we only want to set it for one of them).
    58017380
     
    58397418        return (v, True)
    58407419
    58417420    def kind(self):
     7421        r"""
     7422        Return a string describing what kind of element this is. Returns ``'other'``.
     7423
     7424        EXAMPLE::
     7425
     7426            sage: x = (QQbar(sqrt(2)) + QQbar(sqrt(5)))._descr
     7427            sage: type(x)
     7428            <class 'sage.rings.qqbar.ANBinaryExpr'>
     7429            sage: x.kind()
     7430            'other'
     7431        """
    58427432        return 'other'
    58437433
    58447434    def is_complex(self):
     7435        r"""
     7436        Whether this element is complex. Does not trigger exact computation, so
     7437        may return True even if the element is real.
     7438
     7439        EXAMPLE::
     7440
     7441            sage: x = (QQbar(sqrt(-2)) / QQbar(sqrt(-5)))._descr
     7442            sage: x.is_complex()
     7443            True
     7444        """
    58457445        return self._complex
    58467446
    58477447    def _interval_fast(self, prec):
     7448        r"""
     7449        Calculate an approximation to self in an interval field of precision prec.
     7450
     7451        EXAMPLE::
     7452
     7453            sage: x = (QQbar(sqrt(-2)) / QQbar(sqrt(-5)))._descr
     7454            sage: y= x._interval_fast(64); y
     7455            0.632455532033675867?
     7456            sage: y.parent()
     7457            Complex Interval Field with 64 bits of precision
     7458        """
    58487459        op = self._op
    58497460
    58507461        lv = self._left._interval_fast(prec)
     
    58747485            sage: rt2c = QQbar.zeta(3) + AA(sqrt(2)) - QQbar.zeta(3)
    58757486            sage: rt2c.exactify()
    58767487       
    5877         We check to make sure that this method still works even.  We
     7488        We check to make sure that this method still works even. We
    58787489        do this by increasing the recursion level at each step and
    58797490        decrease it before we return::
    58807491
     
    59257536#     # heptadecagon.)
    59267537#     # Formulas from:
    59277538#     # Weisstein, Eric W. "Trigonometry Angles--Pi/17." From
    5928 #     # MathWorld--A Wolfram Web Resource. 
     7539#     # MathWorld--A Wolfram Web Resource.
    59297540#     # http://mathworld.wolfram.com/TrigonometryAnglesPi17.html
    59307541
    59317542#     rt17 = AA(17).sqrt()
     
    59737584    This code indirectly uses a huge amount of sage, despite the fact
    59747585    that qqbar is imported rather early on in the sage loading. This function
    59757586    is called at the end of sage.all.
     7587
     7588    EXAMPLE::
     7589
     7590        sage: sage.rings.qqbar.QQbar_I_generator # indirect doctest
     7591        Number Field in I with defining polynomial x^2 + 1 with a in 1*I
    59767592    """
    59777593    global ZZX_x, AA_0, QQbar_I, AA_hash_offset, QQbar_hash_offset, QQbar_I_generator, QQbar_I_nf
    59787594    global QQ_0, QQ_1, QQ_1_2, QQ_1_4, RR_1_10
     
    60037619AA_golden_ratio = None
    60047620
    60057621def get_AA_golden_ratio():
     7622    r"""
     7623    Return the golden ratio as an element of the algebraic real field. Used by
     7624    :meth:`sage.symbolic.constants.golden_ratio._algebraic_`.
     7625
     7626    EXAMPLE::
     7627
     7628        sage: AA(golden_ratio) # indirect doctest
     7629        1.618033988749895?
     7630    """
    60067631    global AA_golden_ratio
    60077632    if AA_golden_ratio is None:
    60087633        AA_golden_ratio_nf = NumberField(ZZX_x**2 - ZZX_x - 1, 'phi')