Ticket #12662: trac_12662-qqbar-doctest-v2.patch

File trac_12662-qqbar-doctest-v2.patch, 142.4 KB (added by davidloeffler, 10 years ago)

Apply only this patch. Patch against 5.0.beta10

  • sage/rings/qqbar.py

    # HG changeset patch
    # User David Loeffler <d.loeffler.01@cantab.net>
    # Date 1331658315 0
    # Node ID 9c0d75429fa3692a7f036326628441a2aa2596ab
    # Parent  66e568c3d082ee389659bd257efa500e5a8e5955
    #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
     
    3030
    3131- the sum, difference, product, or quotient of algebraic numbers
    3232
    33 - the negation, inverse, absolute value, norm, real part, 
     33- the negation, inverse, absolute value, norm, real part,
    3434  imaginary part, or complex conjugate of an algebraic number
    3535
    3636- a particular root of a polynomial, given as a polynomial with
     
    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
     
    207207    sage: a
    208208    1.000000000000000?
    209209    sage: a == 1
    210     True 
     210    True
    211211
    212212Algebraic numbers which are known to be rational print as rationals;
    213213otherwise they print as intervals (with 53-bit precision)::
     
    252252    sage: r.abs() == 2
    253253    True
    254254    sage: r.norm() == 4
    255     True   
     255    True
    256256    sage: (r+I).norm().minpoly()
    257257    x^2 - 10*x + 13
    258258    sage: r = AA.polynomial_root(x^2 - x - 1, RIF(-1, 0)); r
     
    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
     
    341341    sage: sage_input(z3_3 * z4_4 * z5_5)
    342342    -60*QQbar.zeta(60)^17
    343343
    344 Note that the ``verify=True`` argument to ``sage_input`` will always trigger 
     344Note 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``
    347 on ``n`` will also trigger exact computation on ``rt2``, as you can see by the 
     346will actually give different answers. In the following, running ``sage_input``
     347on ``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
    350350    sage: rt2 = AA(sqrt(2))
     
    416416    True
    417417
    418418    sage: t.exactify(); type(t._descr)
    419     <class 'sage.rings.qqbar.ANExtensionElement'>   
     419    <class 'sage.rings.qqbar.ANExtensionElement'>
    420420    sage: loads(dumps(t)) == QQbar(sqrt(2))
    421421    True
    422422
     
    424424    <class 'sage.rings.qqbar.ANUnaryExpr'>
    425425    sage: loads(dumps(t)) == 1/QQbar(sqrt(2))
    426426    True
    427    
     427
    428428    sage: t = QQbar(sqrt(2)) + QQbar(sqrt(3)); type(t._descr)
    429429    <class 'sage.rings.qqbar.ANBinaryExpr'>
    430430    sage: loads(dumps(t)) == QQbar(sqrt(2)) + QQbar(sqrt(3))
     
    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()
    482     sage: P = 1/(1+x^4) 
    483     sage: P.partial_fraction_decomposition() 
     482    sage: P = 1/(1+x^4)
     483    sage: P.partial_fraction_decomposition()
    484484    (0, [(-0.3535533905932738?*x + 1/2)/(x^2 - 1.414213562373095?*x + 1), (0.3535533905932738?*x + 1/2)/(x^2 + 1.414213562373095?*x + 1)])
    485485"""
    486486
     
    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
     
    574625            0.?e-18 + 2.236067977499790?*I
    575626            sage: b = QQbar.polynomial_root(p, RIF(1, 2)); b
    576627            1.732050807568878?
    577            
     628
    578629        These "common polynomials" can be shared between real and
    579630        complex roots::
    580631
     
    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)
     
    674780            return create_RealField(prec, **extras)
    675781        else:
    676782            raise NotImplementedError
    677            
     783
    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()
     
    685794        return QQbar
    686795
    687796    def _is_valid_homomorphism_(self, codomain, im_gens):
     797        r"""
     798        Attempt to construct a homomorphism from self to codomain sending the
     799        generators to ``im_gens``. Since this field is not finitely generated,
     800        this cannot be implemented in a mathematically sensible way, and we
     801        just test that there exists a canonical coercion.
     802
     803        EXAMPLE::
     804
     805            sage: AA._is_valid_homomorphism_(QQbar, [QQbar(1)])
     806            True
     807            sage: AA._is_valid_homomorphism_(QQ, [QQ(1)])
     808            False
     809        """
    688810        try:
    689811            return im_gens[0] == codomain._coerce_(self.gen(0))
    690812        except TypeError:
    691813            return False
    692814
    693815    def gens(self):
     816        r"""
     817        Return a set of generators for this field. As this field is not
     818        finitely generated, we opt for just returning 1.
     819
     820        EXAMPLE::
     821
     822            sage: AA.gens()
     823            (1,)
     824        """
    694825        return (self(1), )
    695826
    696827    def gen(self, n=0):
     828        r"""
     829        Return the `n`-th element of the tuple returned by :meth:`gens`.
     830
     831        EXAMPLE::
     832
     833            sage: AA.gen(0)
     834            1
     835            sage: AA.gen(1)
     836            Traceback (most recent call last):
     837            ...
     838            IndexError: n must be 0
     839        """
    697840        if n == 0:
    698841            return self(1)
    699842        else:
    700843            raise IndexError, "n must be 0"
    701844
    702845    def ngens(self):
     846        r"""
     847        Return the size of the tuple returned by :meth:`gens`.
     848
     849        EXAMPLE::
     850
     851            sage: AA.ngens()
     852            1
     853        """
    703854        return 1
    704855
    705856    def is_atomic_repr(self):
     857        r"""
     858        Check whether elements of this field have atomic string
     859        representations. Returns True.
     860
     861        EXAMPLE::
     862
     863            sage: AA.is_atomic_repr()
     864            True
     865        """
    706866        return True
    707867
    708868    def zeta(self, n=2):
     869        r"""
     870        Return an `n`-th root of unity in this field. This will raise a
     871        ``ValueError`` if `n \ne \{1, 2\}` since no such root exists.
     872
     873        INPUT:
     874
     875        - ``n`` (integer) -- default 2
     876
     877        EXAMPLE::
     878
     879            sage: AA.zeta(1)
     880            1
     881            sage: AA.zeta(2)
     882            -1
     883            sage: AA.zeta()
     884            -1
     885            sage: AA.zeta(3)
     886            Traceback (most recent call last):
     887            ...
     888            ValueError: no n-th root of unity in algebraic reals
     889
     890        Some silly inputs::
     891
     892            sage: AA.zeta(Mod(-5, 7))
     893            -1
     894            sage: AA.zeta(0)
     895            Traceback (most recent call last):
     896            ...
     897            ValueError: no n-th root of unity in algebraic reals
     898        """
    709899        if n == 1:
    710900            return self(1)
    711901        elif n == 2:
    712902            return self(-1)
    713903        else:
    714             raise ValueError, "no n-th root of unity in algebraic reals"
     904            raise ValueError("no n-th root of unity in algebraic reals")
    715905
    716906    def polynomial_root(self, poly, interval, multiplicity=1):
    717907        r"""
     
    721911
    722912        The polynomial need not be irreducible, or even squarefree; but
    723913        if the given root is a multiple root, its multiplicity must be
    724         specified.  (IMPORTANT NOTE: Currently, multiplicity-`k` roots
     914        specified. (IMPORTANT NOTE: Currently, multiplicity-`k` roots
    725915        are handled by taking the `(k-1)`-st derivative of the polynomial.
    726916        This means that the interval must enclose exactly one root
    727917        of this derivative.)
     
    764954            2.000000000000000?
    765955        """
    766956        if not is_RealIntervalFieldElement(interval):
    767             raise ValueError, "interval argument of .polynomial_root on algebraic real field must be real"
     957            raise ValueError("interval argument of .polynomial_root on algebraic real field must be real")
    768958
    769959        return AlgebraicReal(ANRoot(poly, interval, multiplicity))
    770960
    771961def is_AlgebraicRealField(F):
     962    r"""
     963    Check whether ``F`` is an :class:`~AlgebraicRealField` instance. For internal use.
     964
     965    EXAMPLE::
     966
     967        sage: from sage.rings.qqbar import is_AlgebraicRealField
     968        sage: [is_AlgebraicRealField(x) for x in [AA, QQbar, None, 0, "spam"]]
     969        [True, False, False, False, False]
     970    """
    772971    return isinstance(F, AlgebraicRealField)
    773972
     973# Create the globally unique AlgebraicRealField object.
    774974AA = AlgebraicRealField()
    775975
    776976class AlgebraicField(_uniq_alg, AlgebraicField_common):
    777977    """
    778     The field of algebraic numbers.
     978    The field of all algebraic complex numbers.
    779979    """
    780980
    781981    def __init__(self):
     982        r"""
     983        Standard init function.
     984
     985        We test by setting the category::
     986
     987            sage: QQbar.category() # indirect doctest
     988            Category of fields
     989            sage: QQbar.base_ring()
     990            Algebraic Real Field
     991        """
    782992        AlgebraicField_common.__init__(self, AA, ('I',), normalize=False)
    783993
    784994    def _element_constructor_(self, x):
    785995        """
    786         Coerce x into the field of algebraic numbers.
    787 
    788         """
    789 
     996        Try to construct an element of the field of algebraic numbers from `x`.
     997
     998        EXAMPLES::
     999
     1000            sage: sqrt(2) in QQbar # indirect doctest
     1001            True
     1002            sage: 22/7 in QQbar
     1003            True
     1004            sage: pi in QQbar
     1005            False
     1006        """
    7901007        if isinstance(x, AlgebraicNumber):
    7911008            return x
    7921009        elif isinstance(x, AlgebraicReal):
     
    7961013        return AlgebraicNumber(x)
    7971014
    7981015    def _repr_(self):
     1016        r"""
     1017        String representation of self.
     1018
     1019        EXAMPLE::
     1020
     1021            sage: QQbar._repr_()
     1022            'Algebraic Field'
     1023        """
    7991024        return "Algebraic Field"
    8001025
    8011026    def _latex_(self):
     1027        r"""
     1028        Latex representation of self.
     1029
     1030        EXAMPLE::
     1031
     1032            sage: QQbar._latex_()
     1033            '\\overline{\\QQ}'
     1034        """
    8021035        return "\\overline{\\QQ}"
    8031036
    8041037    def _sage_input_(self, sib, coerce):
     
    8171050        return sib.name('QQbar')
    8181051
    8191052    def _coerce_map_from_(self, from_par):
     1053        r"""
     1054        Set up the coercion model.
     1055
     1056        TESTS::
     1057
     1058            sage: QQbar.has_coerce_map_from(ZZ) # indirect doctest
     1059            True
     1060            sage: QQbar.has_coerce_map_from(AA)
     1061            True
     1062            sage: QQbar.has_coerce_map_from(CC)
     1063            False
     1064        """
    8201065        if from_par == ZZ or from_par == QQ or from_par == int or from_par == long:
    8211066            return True
    8221067        if from_par == AA or from_par == QQbar:
    8231068            return True
    824         late_import()
     1069        _late_import()
    8251070        if is_SymbolicExpressionRing(from_par):
    8261071            return True
    8271072        return False
    8281073
    8291074    def completion(self, p, prec, extras = {}):
    830         """
     1075        r"""
     1076        Return the completion of self at the place `p`. Only implemented for `p
     1077        = \infty` at present.
     1078
     1079        INPUT:
     1080
     1081        - ``p`` -- either a prime (not implemented at present) or Infinity
     1082        - ``prec`` -- precision of approximate field to return
     1083        - ``extras`` -- a dict of extra keyword arguments for the ``RealField``
     1084          constructor
     1085
    8311086        EXAMPLES::
    8321087
    8331088            sage: QQbar.completion(infinity, 500)
     
    8461101            return create_RealField(prec, **extras).complex_field()
    8471102        else:
    8481103            raise NotImplementedError
    849            
     1104
    8501105    def algebraic_closure(self):
    8511106        """
     1107        Return the algebraic closure of this field. As this field is already
     1108        algebraically closed, just returns self.
     1109
    8521110        EXAMPLES::
    8531111
    8541112            sage: QQbar.algebraic_closure()
    8551113            Algebraic Field
    8561114        """
    8571115        return self
    858    
     1116
    8591117    def construction(self):
    8601118        """
     1119        Return a functor that constructs self (used by the coercion machinery).
     1120
    8611121        EXAMPLE::
    8621122
    8631123            sage: QQbar.construction()
     
    8681128        return (AlgebraicClosureFunctor(), QQ)
    8691129
    8701130    def gens(self):
     1131        r"""
     1132        Return a set of generators for this field. As this field is not
     1133        finitely generated over its prime field, we opt for just returning I.
     1134
     1135        EXAMPLE::
     1136
     1137            sage: QQbar.gens()
     1138            (1*I,)
     1139        """
    8711140        return(QQbar_I, )
    8721141
    8731142    def gen(self, n=0):
     1143        r"""
     1144        Return the `n`-th element of the tuple returned by :meth:`gens`.
     1145
     1146        EXAMPLE::
     1147
     1148            sage: QQbar.gen(0)
     1149            1*I
     1150            sage: QQbar.gen(1)
     1151            Traceback (most recent call last):
     1152            ...
     1153            IndexError: n must be 0
     1154        """
    8741155        if n == 0:
    8751156            return QQbar_I
    8761157        else:
    877             raise IndexError, "n must be 0"
     1158            raise IndexError("n must be 0")
    8781159
    8791160    def ngens(self):
     1161        r"""
     1162        Return the size of the tuple returned by :meth:`gens`.
     1163
     1164        EXAMPLE::
     1165
     1166            sage: QQbar.ngens()
     1167            1
     1168        """
    8801169        return 1
    8811170
    8821171    def is_atomic_repr(self):
     1172        r"""
     1173        Check whether elements of this field have atomic string representations. Returns False.
     1174
     1175        EXAMPLE::
     1176
     1177            sage: QQbar.is_atomic_repr()
     1178            False
     1179        """
    8831180        return False
    8841181
    8851182    def zeta(self, n=4):
    8861183        r"""
    8871184        Returns a primitive `n`'th root of unity, specifically `\exp(2*\pi*i/n)`.
    8881185
     1186        INPUT:
     1187
     1188        - ``n`` (integer) -- default 4
     1189
    8891190        EXAMPLES::
    8901191
    8911192            sage: QQbar.zeta(1)
     
    9131214
    9141215        The polynomial need not be irreducible, or even squarefree; but
    9151216        if the given root is a multiple root, its multiplicity must be
    916         specified.  (IMPORTANT NOTE: Currently, multiplicity-`k` roots
     1217        specified. (IMPORTANT NOTE: Currently, multiplicity-`k` roots
    9171218        are handled by taking the `(k-1)`-st derivative of the polynomial.
    9181219        This means that the interval must enclose exactly one root
    9191220        of this derivative.)
     
    9491250    def random_element(self, poly_degree=2, *args, **kwds):
    9501251        r"""
    9511252        Returns a random algebraic number.
    952        
     1253
    9531254        INPUT:
    954        
    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.
    964          
    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.
    970          
     1255
     1256        - ``poly_degree`` - default: 2 - degree of the random polynomial over
     1257          the integers of which the returned algebraic number is a root. This
     1258          is not necessarily the degree of the minimal polynomial of the
     1259          number. Increase this parameter to achieve a greater diversity of
     1260          algebraic numbers, at a cost of greater computation time. You can
     1261          also vary the distribution of the coefficients but that will not vary
     1262          the degree of the extension containing the element.
     1263
     1264        - ``args``, ``kwds`` - arguments and keywords passed to the random
     1265          number generator for elements of ``ZZ``, the integers. See
     1266          :meth:`~sage.rings.integer_ring.IntegerRing_class.random_element` for
     1267          details, or see example below.
     1268
    9711269        OUTPUT:
    972        
    973         An element of ``QQbar``, the field of algebraic
    974         numbers (see :mod:`sage.rings.qqbar`).
    975        
     1270
     1271        An element of ``QQbar``, the field of algebraic numbers (see
     1272        :mod:`sage.rings.qqbar`).
     1273
    9761274        ALGORITHM:
    977        
     1275
    9781276        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
    981         2 and the integer coefficients come from a distribution 
    982         heavily weighted towards $0, \pm 1, \pm 2$.
    983        
     1277        with random integer coefficients is created. A root of this
     1278        polynomial is chosen at random. The default degree is
     1279        2 and the integer coefficients come from a distribution
     1280        heavily weighted towards `0, \pm 1, \pm 2`.
     1281
    9841282        EXAMPLES::
    985        
     1283
    9861284            sage: a = QQbar.random_element()
    9871285            sage: a                         # random
    9881286            0.2626138748742799? + 0.8769062830975992?*I
    9891287            sage: a in QQbar
    9901288            True
    991        
     1289
    9921290            sage: b = QQbar.random_element(poly_degree=20)
    9931291            sage: b                         # random
    9941292            -0.8642649077479498? - 0.5995098147478391?*I
    9951293            sage: b in QQbar
    9961294            True
    997        
     1295
    9981296        Parameters for the distribution of the integer coefficients
    9991297        of the polynomials can be passed on to the random element method
    1000         for integers.  For example, current default behavior of this method
     1298        for integers. For example, current default behavior of this method
    10011299        returns zero about 15% of the time; if we do not include zero as a
    10021300        possible coefficient, there will never be a zero constant term, and
    10031301        thus never a zero root. ::
    1004        
     1302
    10051303            sage: z = [QQbar.random_element(x=1, y=10) for _ in range(20)]
    10061304            sage: QQbar(0) in z
    10071305            False
    1008            
    1009          If you just want real algebraic numbers you can filter them out. 
     1306
     1307         If you just want real algebraic numbers you can filter them out.
    10101308         Using an odd degree for the polynomials will insure some degree of
    1011          success.  ::
    1012          
     1309         success. ::
     1310
    10131311            sage: r = []
    10141312            sage: while len(r) < 3:
    10151313            ...     x = QQbar.random_element(poly_degree=3)
     
    10171315            ...       r.append(x)
    10181316            sage: (len(r) == 3) and all([z in AA for z in r])
    10191317            True
    1020            
     1318
    10211319        TESTS:
    1022        
     1320
    10231321            sage: QQbar.random_element('junk')
    10241322            Traceback (most recent call last):
    10251323            ...
     
    10281326            Traceback (most recent call last):
    10291327            ...
    10301328            ValueError: polynomial degree must be greater than zero, not 0
    1031            
     1329
    10321330        Random vectors already have a 'degree' keyword, so
    1033         we cannot use that for the polynomial's degree.  ::
    1034        
     1331        we cannot use that for the polynomial's degree. ::
     1332
    10351333            sage: v = random_vector(QQbar, degree=2, poly_degree=3)
    10361334            sage: v                                 # random
    10371335            (0.4694381338921299?, -0.500000000000000? + 0.866025403784439?*I)
     
    10511349        # degree zero polynomials have no roots
    10521350        # totally zero poly has degree -1
    10531351        # add a random leading term
    1054         if p.degree() < 1:   
     1352        if p.degree() < 1:
    10551353            g = R.gen(0)
    10561354            m = sage.misc.prandom.randint(1, poly_degree)
    10571355            p = p + g**m
    10581356        roots = p.roots(ring=QQbar, multiplicities=False)
    1059        
     1357
    10601358        # p will have at least one root; pick one at random
    10611359        # could we instead just compute one root "randomly"?
    10621360        m = sage.misc.prandom.randint(0, len(roots)-1)
    10631361        return roots[m]
    10641362
    10651363def is_AlgebraicField(F):
     1364    r"""
     1365    Check whether ``F`` is an :class:`~AlgebraicField` instance.
     1366
     1367    EXAMPLE::
     1368
     1369        sage: from sage.rings.qqbar import is_AlgebraicField
     1370        sage: [is_AlgebraicField(x) for x in [AA, QQbar, None, 0, "spam"]]
     1371        [False, True, False, False, False]
     1372    """
    10661373    return isinstance(F, AlgebraicField)
    10671374
     1375# Create the globally unique AlgebraicField object.
    10681376QQbar = AlgebraicField()
    10691377
    10701378def is_AlgebraicField_common(F):
     1379    r"""
     1380    Check whether ``F`` is an :class:`~AlgebraicField_common` instance.
     1381
     1382    EXAMPLE::
     1383
     1384        sage: from sage.rings.qqbar import is_AlgebraicField_common
     1385        sage: [is_AlgebraicField_common(x) for x in [AA, QQbar, None, 0, "spam"]]
     1386        [True, True, False, False, False]
     1387    """
    10711388    return isinstance(F, AlgebraicField_common)
    10721389
    10731390def prec_seq():
     1391    r"""
     1392    Return a generator object which iterates over an infinite increasing
     1393    sequence of precisions to be tried in various numerical computations.
     1394
     1395    Currently just returns powers of 2 starting at 64.
     1396
     1397    EXAMPLE::
     1398
     1399        sage: g = sage.rings.qqbar.prec_seq()
     1400        sage: [g.next(), g.next(), g.next()]
     1401        [64, 128, 256]
     1402    """
    10741403    # 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"
     1404    # in MPFR. We could also test variants like "bits = bits + bits // 2"
    10761405    # (I think this is what MPFR uses internally).
    10771406    bits = 64
    10781407    while True:
     
    10801409        bits = bits * 2
    10811410
    10821411_short_prec_seq = (64, 128, None)
    1083 def short_prec_seq(): return _short_prec_seq
     1412def short_prec_seq():
     1413    r"""
     1414    Return a sequence of precisions to try in cases when an infinite-precision
     1415    computation is possible: returns a couple of small powers of 2 and then
     1416    ``None``.
     1417
     1418    EXAMPLE::
     1419
     1420        sage: from sage.rings.qqbar import short_prec_seq
     1421        sage: short_prec_seq()
     1422        (64, 128, None)
     1423    """
     1424    return _short_prec_seq
    10841425
    10851426def tail_prec_seq():
     1427    r"""
     1428    A generator over precisions larger than those in :func:`~short_prec_seq`.
     1429
     1430    EXAMPLE::
     1431
     1432        sage: from sage.rings.qqbar import tail_prec_seq
     1433        sage: g = tail_prec_seq()
     1434        sage: [g.next(), g.next(), g.next()]
     1435        [256, 512, 1024]
     1436    """
    10861437    bits = 256
    10871438    while True:
    10881439        yield bits
     
    10901441
    10911442def rational_exact_root(r, d):
    10921443    r"""
    1093     Checks whether the rational `r` is an exact `d`'th power.  If so, returns
     1444    Checks whether the rational `r` is an exact `d`'th power. If so, returns
    10941445    the `d`'th root of `r`; otherwise, returns None.
    10951446
    10961447    EXAMPLES::
     
    11131464def clear_denominators(poly):
    11141465    """
    11151466    Takes a monic polynomial and rescales the variable to get a monic
    1116     polynomial with "integral" coefficients.  Works on any univariate
     1467    polynomial with "integral" coefficients. Works on any univariate
    11171468    polynomial whose base ring has a ``denominator()`` method that returns
    11181469    integers; for example, the base ring might be `\QQ` or a number
    11191470    field.
     
    11641515    return change, poly
    11651516
    11661517def 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.
     1518    r"""
     1519    Find the polynomial of lowest discriminant that generates the same field as
     1520    poly, out of those returned by the Pari ``polred`` routine.
     1521
     1522    Returns a triple (``elt_fwd``, ``elt_back``, ``new_poly``), where:
     1523
     1524    * ``new_poly`` is the new polynomial,
     1525    * ``elt_fwd`` is a polynomial expression
     1526      for a root of the new polynomial in terms of a root of the original
     1527      polynomial,
     1528    * ``elt_back`` is a polynomial expression for a root of the original
     1529      polynomial in terms of a root of the new polynomial.
    11751530
    11761531    EXAMPLES::
    11771532
     
    11921547
    11931548    best = None
    11941549    best_discr = None
    1195    
     1550
    11961551    for i in range(red_table.nrows()):
    11971552        red_poly = red_table[i,1]
    11981553        if red_poly.poldegree() < degree:
     
    12451600        ifld = intv.parent()
    12461601
    12471602        # We need to verify that pol has exactly one root in the
    1248         # interval intv.  We know (because it is a precondition of
     1603        # interval intv. We know (because it is a precondition of
    12491604        # calling this function) that it has at least one root in the
    12501605        # interval, so we only need to verify that it has at most one
    12511606        # root (that the interval is sufficiently narrow).
    12521607
    12531608        # We do this by computing the derivative of the polynomial
    1254         # over the interval.  If the derivative is bounded away from zero,
     1609        # over the interval. If the derivative is bounded away from zero,
    12551610        # then we know there can be at most one root.
    12561611
    12571612        if not dpol(intv).contains_zero():
     
    12591614
    12601615def find_zero_result(fn, l):
    12611616    """
    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``.
     1617    ``l`` is a list of some sort. ``fn`` is a function which maps an element of
     1618    ``l`` and a precision into an interval (either real or complex) of that
     1619    precision, such that for sufficient precision, exactly one element of ``l``
     1620    results in an interval containing 0. Returns that one element of ``l``.
    12671621
    12681622    EXAMPLES::
    12691623
     
    12961650    r"""
    12971651    If the interval ``v`` (which may be real or complex) includes some
    12981652    purely real numbers, return ``v'`` containing ``v`` such that
    1299     ``v' == v'.conjugate()``.  Otherwise return ``v`` unchanged. (Note that if
     1653    ``v' == v'.conjugate()``. Otherwise return ``v`` unchanged. (Note that if
    13001654    ``v' == v'.conjugate()``, and ``v'`` includes one non-real root of a real
    13011655    polynomial, then ``v'`` also includes the conjugate of that root.
    13021656    Also note that the diameter of the return value is at most twice
     
    13261680def conjugate_shrink(v):
    13271681    r"""
    13281682    If the interval ``v`` includes some purely real numbers, return
    1329     a real interval containing only those real numbers.  Otherwise
     1683    a real interval containing only those real numbers. Otherwise
    13301684    return ``v`` unchanged.
    13311685
    13321686    If ``v`` includes exactly one root of a real polynomial, and ``v`` was
     
    13541708    return v
    13551709
    13561710def number_field_elements_from_algebraics(numbers, minimal=False):
    1357     r""" 
     1711    r"""
    13581712    Given a sequence of elements of either ``AA`` or ``QQbar``
    13591713    (or a mixture), computes a number field containing all of these
    13601714    elements, these elements as members of that number field, and a
     
    13831737        sage: rts = p.roots(ring=QQbar, multiplicities=False)
    13841738        sage: splitting = number_field_elements_from_algebraics(rts)[0]; splitting
    13851739        Number Field in a with defining polynomial y^6 + 169*y^4 + 7968*y^2 + 121088
    1386         sage: p.roots(ring=splitting)       
     1740        sage: p.roots(ring=splitting)
    13871741        [(-9/2176*a^4 - 1121/2176*a^2 - 1625/136, 1), (9/17408*a^5 + 9/4352*a^4 + 1121/17408*a^3 + 1121/4352*a^2 + 1489/1088*a + 1489/272, 1), (-9/17408*a^5 + 9/4352*a^4 - 1121/17408*a^3 + 1121/4352*a^2 - 1489/1088*a + 1489/272, 1)]
    13881742
    13891743        sage: rt2 = AA(sqrt(2)); rt2
     
    14361790            To:   Algebraic Real Field
    14371791            Defn: 1 |--> 1)
    14381792
    1439     Or we can just pass in symbolic expressions, as long as they can be 
     1793    Or we can just pass in symbolic expressions, as long as they can be
    14401794    coerced into ``QQbar``::
    14411795
    14421796        sage: number_field_elements_from_algebraics((sqrt(7), sqrt(9), sqrt(11)))
     
    14871841            To:   Algebraic Field
    14881842            Defn: a |--> -0.7071067811865475? + 0.7071067811865475?*I)
    14891843
    1490     Note that for the first example, where \sage doesn't realize that 
     1844    Note that for the first example, where \sage doesn't realize that
    14911845    the number is real, we get a homomorphism to ``QQbar``; but with
    1492     ``minimal=True``, we get a homomorphism to ``AA``.  Also note
     1846    ``minimal=True``, we get a homomorphism to ``AA``. Also note
    14931847    that the exact answer depends on a Pari function that gives
    14941848    different answers for 32-bit and 64-bit machines::
    14951849
     
    15351889        nums = nums[0]
    15361890
    15371891    hom = fld.hom([gen.root_as_algebraic()])
    1538    
     1892
    15391893    return (fld, nums, hom)
    15401894
    15411895# Cache some commonly-used polynomial rings
     
    15491903
    15501904class AlgebraicGeneratorRelation(SageObject):
    15511905    """
    1552     A simple class for maintaining relations in the lattice of algebraic 
     1906    A simple class for maintaining relations in the lattice of algebraic
    15531907    extensions.
    15541908    """
    15551909    def __init__(self, child1, child1_poly, child2, child2_poly, parent):
     1910        r"""
     1911        EXAMPLE::
     1912
     1913            sage: from sage.rings.qqbar import AlgebraicGeneratorRelation
     1914            sage: c = AlgebraicGeneratorRelation(None, None, None, None, None)
     1915            sage: c
     1916            <class 'sage.rings.qqbar.AlgebraicGeneratorRelation'>
     1917        """
    15561918        self.child1 = child1
    15571919        self.child1_poly = child1_poly
    15581920        self.child2 = child2
     
    15641926class AlgebraicGenerator(SageObject):
    15651927    r"""
    15661928    An ``AlgebraicGenerator`` represents both an algebraic number `\alpha` and
    1567     the number field `\QQ[\alpha]`.  There is a single ``AlgebraicGenerator``
     1929    the number field `\QQ[\alpha]`. There is a single ``AlgebraicGenerator``
    15681930    representing `\QQ` (with `\alpha=0`).
    15691931
    15701932    The ``AlgebraicGenerator`` class is private, and should not be used
     
    15951957            True
    15961958            sage: nf = NumberField(y^2 + 1, name='a', check=False)
    15971959            sage: root = ANRoot(x^2 + 1, CIF(0, 1))
    1598             sage: x = AlgebraicGenerator(nf, root); x       
     1960            sage: x = AlgebraicGenerator(nf, root); x
    15991961            Number Field in a with defining polynomial y^2 + 1 with a in 1*I
    16001962        """
    16011963        self._field = field
     
    16251987        return (AlgebraicGenerator, (self._field, self._root))
    16261988
    16271989    def __hash__(self):
     1990        r"""
     1991        Return a hash value for self. This will depend on the order that
     1992        commands get executed at load time, so we do not test the value that is
     1993        returned, just that it doesn't raise an error.
     1994
     1995        EXAMPLE::
     1996
     1997            sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator
     1998            sage: _.<y> = QQ['y']
     1999            sage: x = polygen(QQbar)
     2000            sage: nf = NumberField(y^2 - y - 1, name='a', check=False)
     2001            sage: root = ANRoot(x^2 - x - 1, RIF(1, 2))
     2002            sage: gen = AlgebraicGenerator(nf, root)
     2003            sage: hash(gen) # random
     2004        """
    16282005        return self._index
    16292006
    16302007    def __cmp__(self, other):
     2008        r"""
     2009        Compare self with another AlgebraicGenerator object.
     2010
     2011        EXAMPLE::
     2012
     2013            sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator
     2014            sage: _.<y> = QQ['y']
     2015            sage: x = polygen(QQbar)
     2016            sage: nf = NumberField(y^2 - y - 1, name='a', check=False)
     2017            sage: root = ANRoot(x^2 - x - 1, RIF(1, 2))
     2018            sage: gen = AlgebraicGenerator(nf, root)
     2019            sage: gen.__cmp__(qq_generator)
     2020            1
     2021        """
    16312022        return cmp(self._index, other._index)
    16322023
    16332024    def set_cyclotomic(self, n):
     2025        r"""
     2026        Store the fact that this is generator for a cyclotomic field.
     2027
     2028        EXAMPLE::
     2029
     2030            sage: y = sage.rings.qqbar.cyclotomic_generator(5) # indirect doctest
     2031            sage: y._cyclotomic
     2032            True
     2033        """
    16342034        self._cyclotomic = True
    16352035        self._cyclotomic_order = ZZ(n)
    16362036
    16372037    def is_complex(self):
     2038        r"""
     2039        Return True if this is a generator for a non-real number field.
     2040
     2041        EXAMPLE::
     2042
     2043            sage: sage.rings.qqbar.cyclotomic_generator(7).is_complex()
     2044            True
     2045            sage: sage.rings.qqbar.qq_generator.is_complex()
     2046            False
     2047        """
    16382048        return self._root.is_complex()
    16392049
    16402050    def _repr_(self):
     2051        r"""
     2052        String representation of self.
     2053
     2054        EXAMPLE::
     2055
     2056            sage: from sage.rings.qqbar import qq_generator, cyclotomic_generator
     2057            sage: qq_generator._repr_()
     2058            'Trivial generator'
     2059
     2060            sage: cyclotomic_generator(7)._repr_()
     2061            '1*e^(2*pi*I*1/7)'
     2062
     2063            sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator
     2064            sage: y = polygen(QQ)
     2065            sage: x = polygen(QQbar)
     2066            sage: nf = NumberField(y^2 - y - 1, name='a', check=False)
     2067            sage: root = ANRoot(x^2 - x - 1, RIF(1, 2))
     2068            sage: gen = AlgebraicGenerator(nf, root)
     2069            sage: gen._repr_()
     2070            'Number Field in a with defining polynomial x^2 - x - 1 with a in 1.618033988749895?'
     2071        """
    16412072        if self._trivial:
    16422073            return 'Trivial generator'
    16432074        else:
     
    16472078                return '%s with a in %s'%(self._field, self._root._interval_fast(53))
    16482079
    16492080    def root_as_algebraic(self):
     2081        r"""
     2082        Return the root attached to self as an algebraic number.
     2083
     2084        EXAMPLE::
     2085
     2086            sage: t = sage.rings.qqbar.qq_generator.root_as_algebraic(); t
     2087            1
     2088            sage: t.parent()
     2089            Algebraic Real Field
     2090        """
    16502091        return self._root_as_algebraic
    16512092
    16522093    def is_trivial(self):
     
    16632104        return self._trivial
    16642105
    16652106    def field(self):
     2107        r"""
     2108        Return the number field attached to self.
     2109
     2110        EXAMPLE::
     2111
     2112            sage: from sage.rings.qqbar import qq_generator, cyclotomic_generator
     2113            sage: qq_generator.field()
     2114            Rational Field
     2115            sage: cyclotomic_generator(3).field()
     2116            Cyclotomic Field of order 3 and degree 2
     2117        """
    16662118        return self._field
    16672119
    16682120    def pari_field(self):
     2121        r"""
     2122        Return the PARI field attached to this generator.
     2123
     2124        EXAMPLE::
     2125
     2126
     2127            sage: from sage.rings.qqbar import qq_generator
     2128            sage: qq_generator.pari_field()
     2129            Traceback (most recent call last):
     2130            ...
     2131            ValueError: No PARI field attached to trivial generator
     2132
     2133            sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator
     2134            sage: y = polygen(QQ)
     2135            sage: x = polygen(QQbar)
     2136            sage: nf = NumberField(y^2 - y - 1, name='a', check=False)
     2137            sage: root = ANRoot(x^2 - x - 1, RIF(1, 2))
     2138            sage: gen = AlgebraicGenerator(nf, root)
     2139            sage: gen.pari_field()
     2140             [y^2 - y - 1, [2, 0], ...]
     2141        """
     2142        if self.is_trivial(): raise ValueError("No PARI field attached to trivial generator")
    16692143        if self._pari_field is None:
    16702144            pari_pol = self._field.pari_polynomial("y")
    16712145            self._pari_field = pari_pol.nfinit(1)
     
    16752149        r"""
    16762150        If this generator is for the algebraic number `\alpha`, return a
    16772151        generator for the complex conjugate of `\alpha`.
     2152
     2153        EXAMPLE::
     2154
     2155            sage: from sage.rings.qqbar import AlgebraicGenerator
     2156            sage: x = polygen(QQ); f = x^4 + x + 17
     2157            sage: nf = NumberField(f,name='a')
     2158            sage: b = f.roots(QQbar)[0][0]
     2159            sage: root = b._descr
     2160            sage: gen = AlgebraicGenerator(nf, root)
     2161            sage: gen.conjugate()
     2162            Number Field in a with defining polynomial x^4 + x + 17 with a in -1.436449997483091? + 1.374535713065812?*I
    16782163        """
    16792164        try:
    16802165            return self._conjugate
     
    16962181        """
    16972182        Returns an interval containing this generator, to the specified
    16982183        precision.
     2184
     2185        EXAMPLE::
     2186
     2187            sage: g = sage.rings.qqbar.cyclotomic_generator(5)
     2188            sage: g._interval_fast(256)
     2189            0.309016994374947424102293417182819058860154589902881431067724311352...? + 0.951056516295153572116439333379382143405698634125750222447305644430...?*I
    16992190        """
    17002191        return self._root._interval_fast(prec)
    17012192
     
    17932284        red_back_x = QQx(red_back)
    17942285
    17952286        new_nf = NumberField(red_pol, name='a', check=False)
    1796        
     2287
    17972288        self_pol_sage = QQx(self_pol.lift())
    17982289
    17992290        new_nf_a = new_nf.gen()
     
    18092300        self._unions[other] = rel
    18102301        other._unions[self] = rel
    18112302        return new_gen
    1812    
     2303
    18132304    def super_poly(self, super, checked=None):
    18142305        r"""
    18152306        Given a generator ``gen`` and another generator ``super``, where ``super``
     
    18432334            -a^3 + 3*a
    18442335            sage: gen3.super_poly(gen2_3)
    18452336            -a^2 + 2
    1846        
     2337
    18472338        """
    18482339        if checked is None:
    18492340            checked = {}
     
    18692360        """
    18702361        Takes an algebraic number which is represented as either a
    18712362        rational or a number field element, and which is in a subfield
    1872         of the field generated by this generator.  Lifts the number
     2363        of the field generated by this generator. Lifts the number
    18732364        into the field of this generator, and returns either a
    18742365        ``Rational`` or a ``NumberFieldElement`` depending on whether
    18752366        this is the trivial generator.
     
    18992390            sage: gen2_3(ANRational(1/7))
    19002391            1/7
    19012392            sage: gen2_3(sqrt3)
    1902             -a^2 + 2           
     2393            -a^2 + 2
    19032394        """
    19042395        if self._trivial:
    19052396            return elt.rational_value()
     
    19172408        return self._field(elt.field_element_value().polynomial()(sp))
    19182409
    19192410# These are the functions used to add, subtract, multiply, and divide
    1920 # algebraic numbers.  Basically, we try to compute exactly if the
     2411# algebraic numbers. Basically, we try to compute exactly if the
    19212412# result would be a Gaussian rational, or a rational times a root
    19222413# 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,
     2414# number field. Otherwise we fall back to floating-point computation,
    19242415# to be backed up by exact symbolic computation only as required.
    19252416
    19262417# These choices are motivated partly by efficiency considerations
     
    19302421# than as intervals, as often as possible.
    19312422
    19322423def an_addsub_rational(a, b, sub):
     2424    r"""
     2425    Used to add and subtract algebraic numbers. Used when both are actually rational.
     2426
     2427    EXAMPLE::
     2428
     2429        sage: from sage.rings.qqbar import an_addsub_rational
     2430        sage: f = an_addsub_rational(QQbar(2), QQbar(3/7), False); f
     2431        17/7
     2432        sage: type(f)
     2433        <class 'sage.rings.qqbar.ANRational'>
     2434    """
    19332435    va = a._descr._value
    19342436    vb = b._descr._value
    19352437    if sub:
     
    19392441    return ANRational(v)
    19402442
    19412443def an_muldiv_rational(a, b, div):
     2444    r"""
     2445    Used to multiply and divide algebraic numbers. Used when both are actually rational.
     2446
     2447    EXAMPLE::
     2448
     2449        sage: from sage.rings.qqbar import an_muldiv_rational
     2450        sage: f = an_muldiv_rational(QQbar(2), QQbar(3/7), False); f
     2451        6/7
     2452        sage: type(f)
     2453        <class 'sage.rings.qqbar.ANRational'>
     2454    """
     2455    va = a._descr._value
    19422456    va = a._descr._value
    19432457    vb = b._descr._value
    19442458    if div:
     
    19482462    return ANRational(v)
    19492463
    19502464def an_addsub_zero(a, b, sub):
     2465    r"""
     2466    Used to add and subtract algebraic numbers. Used when one of a and b is zero.
     2467
     2468    EXAMPLES::
     2469
     2470        sage: from sage.rings.qqbar import an_addsub_zero
     2471        sage: f = an_addsub_zero(QQbar(sqrt(2)), QQbar(0), False); f
     2472        Root 1.4142135623730950488? of x^2 - 2
     2473        sage: type(f)
     2474        <class 'sage.rings.qqbar.ANRoot'>
     2475        sage: an_addsub_zero(QQbar(0), QQbar(sqrt(2)), True)
     2476        <class 'sage.rings.qqbar.ANUnaryExpr'>
     2477    """
    19512478    if b._descr.is_rational() and b._descr.rational_value().is_zero():
    19522479        return a._descr
    19532480    # we know a is 0
     
    19572484        return b._descr
    19582485
    19592486def an_muldiv_zero(a, b, div):
     2487    r"""
     2488    Used to multiply and divide algebraic numbers. Used when one of a and b is zero.
     2489
     2490    EXAMPLES::
     2491
     2492        sage: from sage.rings.qqbar import an_muldiv_zero
     2493        sage: f = an_muldiv_zero(QQbar(sqrt(2)), QQbar(0), False); f
     2494        0
     2495        sage: type(f)
     2496        <class 'sage.rings.qqbar.ANRational'>
     2497        sage: an_muldiv_zero(QQbar(sqrt(2)), QQbar(sqrt(0)), True)
     2498        Traceback (most recent call last):
     2499        ...
     2500        ValueError: algebraic number division by zero
     2501    """
    19602502    if b._descr.is_rational() and b._descr.rational_value().is_zero():
    19612503        if div:
    1962             raise ValueError, "algebraic number division by zero"
     2504            raise ValueError("algebraic number division by zero")
    19632505        else:
    19642506            return ANRational(0)
    19652507    # we know a is 0
    19662508    return ANRational(0)
    19672509
    19682510def an_addsub_gaussian(a, b, sub):
     2511    r"""
     2512    Used to add and subtract algebraic numbers when both are in `\QQ(i)`.
     2513
     2514    EXAMPLE::
     2515
     2516        sage: i = QQbar(I)
     2517        sage: from sage.rings.qqbar import an_addsub_gaussian
     2518        sage: x=an_addsub_gaussian(2 + 3*i, 2/3 + 1/4*i, True); x
     2519        11/4*I + 4/3 where a^2 + 1 = 0 and a in 1*I
     2520        sage: type(x)
     2521        <class 'sage.rings.qqbar.ANExtensionElement'>
     2522    """
    19692523    va = a._descr.gaussian_value()
    19702524    vb = b._descr.gaussian_value()
    19712525    if sub:
     
    19752529    return ANExtensionElement(QQbar_I_generator, v)
    19762530
    19772531def an_muldiv_gaussian(a, b, div):
     2532    r"""
     2533    Used to multiply and divide algebraic numbers when both are in `\QQ(i)`.
     2534
     2535    EXAMPLE::
     2536
     2537        sage: i = QQbar(I)
     2538        sage: from sage.rings.qqbar import an_muldiv_gaussian
     2539        sage: x=an_muldiv_gaussian(2 + 3*i, 2/3 + 1/4*i, True); x
     2540        216/73*I + 300/73 where a^2 + 1 = 0 and a in 1*I
     2541        sage: type(x)
     2542        <class 'sage.rings.qqbar.ANExtensionElement'>
     2543    """
    19782544    va = a._descr.gaussian_value()
    19792545    vb = b._descr.gaussian_value()
    19802546    if div:
     
    19842550    return ANExtensionElement(QQbar_I_generator, v)
    19852551
    19862552def an_addsub_expr(a, b, sub):
     2553    r"""
     2554    Add or subtract algebraic numbers represented as multi-part expressions.
     2555
     2556    EXAMPLE::
     2557
     2558        sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3))
     2559        sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5))
     2560        sage: type(a._descr); type(b._descr)
     2561        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2562        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2563        sage: from sage.rings.qqbar import an_addsub_expr
     2564        sage: x = an_addsub_expr(a, b, False); x
     2565        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2566        sage: x.exactify()
     2567        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...?
     2568    """
    19872569    return ANBinaryExpr(a, b, ('-' if sub else '+'))
    19882570
    19892571def an_muldiv_expr(a, b, div):
     2572    r"""
     2573    Multiply or divide algebraic numbers represented as multi-part expressions.
     2574
     2575    EXAMPLE::
     2576
     2577        sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3))
     2578        sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5))
     2579        sage: type(a._descr)
     2580        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2581        sage: from sage.rings.qqbar import an_muldiv_expr
     2582        sage: x = an_muldiv_expr(a, b, False); x
     2583        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2584        sage: x.exactify()
     2585        -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...?
     2586    """
    19902587    return ANBinaryExpr(a, b, ('/' if div else '*'))
    19912588
    19922589def an_muldiv_rootunity(a, b, div):
     2590    r"""
     2591    Multiply or divide two algebraic numbers represented as a rational multiple
     2592    of a root of unity.
     2593
     2594    EXAMPLE::
     2595
     2596        sage: a = 2*QQbar.zeta(7)
     2597        sage: b = 3*QQbar.zeta(8)
     2598        sage: type(a._descr)
     2599        <class 'sage.rings.qqbar.ANRootOfUnity'>
     2600        sage: from sage.rings.qqbar import an_muldiv_rootunity
     2601        sage: an_muldiv_rootunity(a, b, True)
     2602        2/3*e^(2*pi*I*1/56)
     2603    """
    19932604    ad = a._descr
    19942605    bd = b._descr
    19952606    if div:
     
    19982609        return ANRootOfUnity(ad.angle() + bd.angle(), ad.scale() * bd.scale())
    19992610
    20002611def an_addsub_rootunity(a, b, sub):
     2612    r"""
     2613    Add or subtract two algebraic numbers represented as a rational multiple of
     2614    a root of unity.
     2615
     2616    EXAMPLE::
     2617
     2618        sage: a = 2*QQbar.zeta(7)
     2619        sage: b = 3*QQbar.zeta(8)
     2620        sage: type(a._descr)
     2621        <class 'sage.rings.qqbar.ANRootOfUnity'>
     2622        sage: from sage.rings.qqbar import an_addsub_rootunity
     2623        sage: an_addsub_rootunity(a, b, False)
     2624        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2625        sage: an_addsub_rootunity(a, 3*QQbar.zeta(7), True)
     2626        -1*e^(2*pi*I*1/7)
     2627    """
    20012628    ad = a._descr
    20022629    bd = b._descr
    20032630    if ad._angle == bd._angle:
     
    20092636        return an_addsub_expr(a, b, sub)
    20102637
    20112638def an_muldiv_element(a, b, div):
     2639    r"""
     2640    Multiply or divide two elements represented as elements of number fields.
     2641
     2642    EXAMPLES::
     2643
     2644        sage: a = QQbar(sqrt(2) + sqrt(3)); a.exactify()
     2645        sage: b = QQbar(sqrt(3) + sqrt(5)); b.exactify()
     2646        sage: type(a._descr)
     2647        <class 'sage.rings.qqbar.ANExtensionElement'>
     2648        sage: from sage.rings.qqbar import an_muldiv_element
     2649        sage: an_muldiv_element(a,b,False)
     2650        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2651    """
    20122652    ad = a._descr
    20132653    bd = b._descr
    20142654    adg = ad.generator()
     
    20262666    return ANBinaryExpr(a, b, ('/' if div else '*'))
    20272667
    20282668def an_addsub_element(a, b, sub):
     2669    r"""
     2670    Add or subtract two elements represented as elements of number fields.
     2671
     2672    EXAMPLES::
     2673
     2674        sage: a = QQbar(sqrt(2) + sqrt(3)); a.exactify()
     2675        sage: b = QQbar(sqrt(3) + sqrt(5)); b.exactify()
     2676        sage: from sage.rings.qqbar import an_addsub_element
     2677        sage: an_addsub_element(a,b,False)
     2678        <class 'sage.rings.qqbar.ANBinaryExpr'>
     2679    """
    20292680    ad = a._descr
    20302681    bd = b._descr
    20312682    adg = ad.generator()
     
    21052756        _add_algo[key] = an_addsub_expr
    21062757
    21072758class 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.
     2759    r"""
     2760    An ``AlgebraicNumber`` or ``AlgebraicReal`` is a wrapper around an
     2761    ``ANDescr`` object. ``ANDescr`` is an abstract base class, which should
     2762    never be directly instantiated; its concrete subclasses are ``ANRational``,
     2763    ``ANBinaryExpr``, ``ANUnaryExpr``, ``ANRootOfUnity``, ``ANRoot``, and
     2764    ``ANExtensionElement``. ``ANDescr`` and all of its subclasses are for
     2765    internal use, and should not be used directly.
    21152766    """
    21162767    def is_exact(self):
    21172768        """
     
    21602811
    21612812    def is_rational(self):
    21622813        r"""
    2163         Returns ``True`` if self is an ``ANRational`` object.  (Note that
     2814        Returns ``True`` if self is an ``ANRational`` object. (Note that
    21642815        the constructors for ``ANExtensionElement`` and ``ANRootOfUnity``
    21652816        will actually return ``ANRational`` objects for rational numbers.)
    21662817
     
    21902841        """
    21912842        return False
    21922843
     2844    # Unitary operators: the second argument "n" is an AlgebraicNumber_base
     2845    # wrapper around self.
     2846
    21932847    def neg(self, n):
     2848        r"""
     2849        Negation of self.
     2850
     2851        EXAMPLE::
     2852
     2853            sage: a = QQbar(sqrt(2))
     2854            sage: b = a._descr
     2855            sage: b.neg(a)
     2856            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2857        """
    21942858        return ANUnaryExpr(n, '-')
    21952859
    21962860    def invert(self, n):
     2861        r"""
     2862        1/self.
     2863
     2864        EXAMPLE::
     2865
     2866            sage: a = QQbar(sqrt(2))
     2867            sage: b = a._descr
     2868            sage: b.invert(a)
     2869            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2870        """
    21972871        return ANUnaryExpr(n, '~')
    21982872
    21992873    def abs(self, n):
     2874        r"""
     2875        Absolute value of self.
     2876
     2877        EXAMPLE::
     2878
     2879            sage: a = QQbar(sqrt(2))
     2880            sage: b = a._descr
     2881            sage: b.abs(a)
     2882            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2883        """
    22002884        return ANUnaryExpr(n, 'abs')
    22012885
    22022886    def real(self, n):
     2887        r"""
     2888        Real part of self.
     2889
     2890        EXAMPLE::
     2891
     2892            sage: a = QQbar(sqrt(-7))
     2893            sage: b = a._descr
     2894            sage: b.real(a)
     2895            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2896        """
    22032897        if self.is_complex():
    22042898            return ANUnaryExpr(n, 'real')
    22052899        else:
    22062900            return self
    22072901
    22082902    def imag(self, n):
     2903        r"""
     2904        Imaginary part of self.
     2905
     2906        EXAMPLE::
     2907
     2908            sage: a = QQbar(sqrt(-7))
     2909            sage: b = a._descr
     2910            sage: b.imag(a)
     2911            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2912        """
    22092913        if self.is_complex():
    22102914            return ANUnaryExpr(n, 'imag')
    22112915        else:
    22122916            return ANRational(0)
    22132917
    22142918    def conjugate(self, n):
     2919        r"""
     2920        Complex conjugate of self.
     2921
     2922        EXAMPLE::
     2923
     2924            sage: a = QQbar(sqrt(-7))
     2925            sage: b = a._descr
     2926            sage: b.conjugate(a)
     2927            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2928        """
    22152929        if self.is_complex():
    22162930            return ANUnaryExpr(n, 'conjugate')
    22172931        else:
    22182932            return self
    22192933
    22202934    def norm(self, n):
     2935        r"""
     2936        Field norm of self from `\overline{\QQ}` to its real subfield
     2937        `\mathbf{A}`, i.e.~the square of the usual complex absolute value.
     2938
     2939        EXAMPLE::
     2940
     2941            sage: a = QQbar(sqrt(-7))
     2942            sage: b = a._descr
     2943            sage: b.norm(a)
     2944            <class 'sage.rings.qqbar.ANUnaryExpr'>
     2945        """
    22212946        if self.is_complex():
    22222947            return ANUnaryExpr(n, 'norm')
    22232948        else:
     
    22312956
    22322957    ``AlgebraicNumber`` objects can be created using ``QQbar`` (==
    22332958    ``AlgebraicNumberField()``), and ``AlgebraicReal`` objects can be created
    2234     using ``AA`` (== ``AlgebraicRealField()``).  They can be created either by
     2959    using ``AA`` (== ``AlgebraicRealField()``). They can be created either by
    22352960    coercing a rational or a symbolic expression, or by using the
    22362961    ``QQbar.polynomial_root()`` or ``AA.polynomial_root()`` method to
    22372962    construct a particular root of a polynomial with algebraic
    2238     coefficients.  Also, ``AlgebraicNumber`` and ``AlgebraicReal`` are closed
     2963    coefficients. Also, ``AlgebraicNumber`` and ``AlgebraicReal`` are closed
    22392964    under addition, subtraction, multiplication, division (except by
    22402965    0), and rational powers (including roots), except that for a
    22412966    negative ``AlgebraicReal``, taking a power with an even denominator returns
    22422967    an ``AlgebraicNumber`` instead of an ``AlgebraicReal``.
    22432968
    22442969    ``AlgebraicNumber``   and   ``AlgebraicReal``   objects   can   be
    2245     approximated  to  any desired  precision.   They  can be  compared
     2970    approximated  to  any desired  precision. They  can be  compared
    22462971    exactly; if the two numbers are very close, or are equal, this may
    22472972    require exact computation, which can be extremely slow.
    22482973
    22492974    As long as exact computation is not triggered, computation with
    22502975    algebraic numbers should not be too much slower than computation with
    2251     intervals.  As mentioned above, exact computation is triggered
     2976    intervals. As mentioned above, exact computation is triggered
    22522977    when comparing two algebraic numbers which are very close together.
    22532978    This can be an explicit comparison in user code, but the following
    22542979    list of actions (not necessarily complete) can also trigger exact
     
    22853010
    22863011    def __init__(self, parent, x):
    22873012        r"""
    2288         Initialize an algebraic number.  The argument must be either
     3013        Initialize an algebraic number. The argument must be either
    22893014        a rational number, a Gaussian rational, or a subclass of ``ANDescr``.
    2290        
     3015
    22913016        EXAMPLES::
    22923017
    22933018            sage: from sage.rings.qqbar import ANRootOfUnity
     
    23073032                 list(x.parent().polynomial()) == [1, 0, 1]:
    23083033            self._descr = ANExtensionElement(QQbar_I_generator, QQbar_I_nf(x.list()))
    23093034        else:
    2310             raise TypeError, "Illegal initializer for algebraic number"
     3035            raise TypeError("Illegal initializer for algebraic number")
    23113036
    23123037        self._value = self._descr._interval_fast(64)
    2313        
     3038
    23143039    def _repr_(self):
    23153040        """
    23163041        Returns the print representation of this number.
    23173042
    23183043        EXAMPLES::
    23193044
    2320             sage: AA(22/7)
     3045            sage: AA(22/7) # indirect doctest
    23213046            22/7
    23223047            sage: QQbar(1/3 + 2/7*I)
    23233048            2/7*I + 1/3
     
    23933118        """
    23943119        TESTS::
    23953120
    2396             sage: AA(sqrt(2)) * AA(sqrt(8))
     3121            sage: AA(sqrt(2)) * AA(sqrt(8)) # indirect doctest
    23973122            4.000000000000000?
    23983123        """
    23993124        sd = self._descr
     
    24063131        """
    24073132        TESTS::
    24083133
    2409             sage: AA(sqrt(2)) / AA(sqrt(8))
     3134            sage: AA(sqrt(2)) / AA(sqrt(8)) # indirect doctest
    24103135            0.500000000000000?
    24113136        """
    24123137        sd = self._descr
     
    24313156
    24323157            sage: x = polygen(ZZ)
    24333158            sage: rt1, rt2 = (x^2 - x - 1).roots(ring=AA, multiplicities=False)
    2434             sage: rt1 + rt2
     3159            sage: rt1 + rt2 # indirect doctest
    24353160            1.000000000000000?
    24363161        """
    24373162        sd = self._descr
     
    24443169        """
    24453170        TESTS::
    24463171
    2447             sage: AA(golden_ratio) * 2 - AA(5).sqrt()
     3172            sage: AA(golden_ratio) * 2 - AA(5).sqrt() # indirect doctest
    24483173            1.000000000000000?
    24493174        """
    24503175        sd = self._descr
     
    24573182        """
    24583183        TESTS::
    24593184
    2460             sage: -QQbar(I)
     3185            sage: -QQbar(I) # indirect doctest
    24613186            -1*I
    24623187        """
    24633188        return type(self)(self._descr.neg(self))
     
    25033228
    25043229            sage: h1 = hash(QQbar.zeta(6))
    25053230            sage: h2 = hash(QQbar(1/2 + I*sqrt(3)/2))
    2506             sage: h1 == h2           
     3231            sage: h1 == h2
    25073232            True
    25083233
    25093234        Unfortunately, the hash code for algebraic numbers which are close
    2510         enough to each other are the same.  (This is inevitable, if
     3235        enough to each other are the same. (This is inevitable, if
    25113236        equal algebraic reals give the same hash code and hashing does
    25123237        not always trigger exact computation.)::
    25133238
     
    25263251        # 1, or 2 are presumably not uncommon).
    25273252
    25283253        # So I modify the algebraic real by adding 1/123456789 to it before
    2529         # calling interval_exact().  Then, exact computation will be triggered
     3254        # calling interval_exact(). Then, exact computation will be triggered
    25303255        # by algebraic reals which are sufficiently close to
    2531         # (some floating point number minus 1/123456789).  Hopefully,
     3256        # (some floating point number minus 1/123456789). Hopefully,
    25323257        # -1/123456789 comes up in algebraic real computations far less
    2533         # often than 0 does.  Algebraic numbers have a similar offset added,
     3258        # often than 0 does. Algebraic numbers have a similar offset added,
    25343259        # with an additional complex component of 1/987654321*I.
    25353260
    25363261        # All of this effort to avoid exact computation is probably wasted,
    25373262        # anyway... in almost all uses of hash codes, if the hash codes
    25383263        # match, the next step is to compare for equality; and comparing
    2539         # for equality often requires exact computation.  (If a==b,
     3264        # for equality often requires exact computation. (If a==b,
    25403265        # then checking a==b requires exact computation unless (a is b).)
    25413266
    25423267        if self.parent() is AA:
     
    25803305          return a square root of self in QQbar, otherwise raise a ValueError.
    25813306
    25823307        - ``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
     3308          roots. If False, return just one square root, or raise an ValueError
    25843309          if self is a negative element of AA and extend=False.
    2585        
     3310
    25863311        OUTPUT:
    25873312
    25883313        Either the principal square root of self, or a list of its
     
    25973322            0.7071067811865475? + 0.7071067811865475?*I
    25983323            sage: QQbar(I).sqrt(all=True)
    25993324            [0.7071067811865475? + 0.7071067811865475?*I, -0.7071067811865475? - 0.7071067811865475?*I]
    2600            
     3325
    26013326            sage: a = QQbar(0)
    26023327            sage: a.sqrt()
    26033328            0
    26043329            sage: a.sqrt(all=True)
    26053330            [0]
    2606            
     3331
    26073332            sage: a = AA(0)
    26083333            sage: a.sqrt()
    26093334            0
    26103335            sage: a.sqrt(all=True)
    26113336            [0]
    2612            
     3337
    26133338        This second example just shows that the program doesn't care where 0
    2614         is defined, it gives the same answer regardless. After all, how many 
     3339        is defined, it gives the same answer regardless. After all, how many
    26153340        ways can you square-root zero?
    26163341
    26173342        ::
    2618            
     3343
    26193344            sage: AA(-2).sqrt()
    26203345            1.414213562373095?*I
    26213346
    26223347            sage: AA(-2).sqrt(all=True)
    26233348            [1.414213562373095?*I, -1.414213562373095?*I]
    2624            
     3349
    26253350            sage: AA(-2).sqrt(extend=False)
    26263351            Traceback (most recent call last):
    26273352            ...
     
    26303355
    26313356        """
    26323357        # deal with 0 first:
    2633        
     3358
    26343359        if self.is_zero():
    26353360            if all:
    26363361                return [self]
     
    26413366
    26423367        if self.parent() is AA and self<0 and not extend:
    26433368            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
    2645             else: 
     3369                raise ValueError("%s is not a square in AA, being negative. Use extend = True for a square root in QQbar."%self)
     3370            else:
    26463371                return []
    2647    
     3372
    26483373        root = self.__pow__(~ZZ(2))
    26493374
    26503375        if all:
     
    28963621        r"""
    28973622        Given a ``RealIntervalField``, compute the value of this number
    28983623        using interval arithmetic of at least the precision of the field,
    2899         and return the value in that field.  (More precision may be used
     3624        and return the value in that field. (More precision may be used
    29003625        in the computation.)  The returned interval may be arbitrarily
    29013626        imprecise, if this number is the result of a sufficiently long
    29023627        computation chain.
     
    29273652    def interval_diameter(self, diam):
    29283653        """
    29293654        Compute an interval representation of self with ``diameter()`` at
    2930         most ``diam``.  The precision of the returned value is unpredictable.
     3655        most ``diam``. The precision of the returned value is unpredictable.
    29313656
    29323657        EXAMPLES::
    29333658
     
    29533678        Given an interval field (real or complex, as appropriate) of
    29543679        precision `p`, compute an interval representation of self with
    29553680        ``diameter()`` at most `2^{-p}`; then round that representation into
    2956         the given field.  Here ``diameter()`` is relative diameter for
     3681        the given field. Here ``diameter()`` is relative diameter for
    29573682        intervals not containing 0, and absolute diameter for
    29583683        intervals that do contain 0; thus, if the returned interval
    29593684        does not contain 0, it has at least `p-1` good bits.
     
    29823707class AlgebraicNumber(AlgebraicNumber_base):
    29833708    r"""
    29843709    The class for algebraic numbers (complex numbers which are the roots
    2985     of a polynomial with integer coefficients).  Much of its functionality
     3710    of a polynomial with integer coefficients). Much of its functionality
    29863711    is inherited from ``AlgebraicNumber_base``.
    29873712    """
    29883713    def __init__(self, x):
     3714        r"""
     3715        Initialize this AlgebraicNumber object.
     3716
     3717        EXAMPLE::
     3718
     3719            sage: t = QQbar.zeta(5)
     3720            sage: type(t)
     3721            <class 'sage.rings.qqbar.AlgebraicNumber'>
     3722        """
    29893723        AlgebraicNumber_base.__init__(self, QQbar, x)
    29903724
    29913725    def __reduce__(self):
     
    30023736
    30033737    def __cmp__(self, other):
    30043738        """
    3005         Compare two algebraic numbers, lexicographically.  (That is,
     3739        Compare two algebraic numbers, lexicographically. (That is,
    30063740        first compare the real components; if the real components are
    30073741        equal, compare the imaginary components.)
    30083742
     
    30543788        return not self._sub_(other).__nonzero__()
    30553789
    30563790    def __ne__(self, other):
     3791        r"""
     3792        Test two algebraic numbers for inequality.
     3793
     3794        EXAMPLES::
     3795
     3796            sage: QQbar.zeta(6) != QQbar(1/2 + I*sqrt(3)/2)
     3797            False
     3798            sage: QQbar(I) != QQbar(I * (2^100+1)/(2^100))
     3799            True
     3800            sage: QQbar(2) != 2
     3801            False
     3802            sage: QQbar(2) != GF(7)(2)
     3803            True
     3804        """
    30573805        return not self.__eq__(other)
    30583806
    30593807    def __nonzero__(self):
    30603808        """
    3061         Check whether self is equal is nonzero.  This is fast if
     3809        Check whether self is equal is nonzero. This is fast if
    30623810        interval arithmetic proves that self is nonzero, but may be
    30633811        slow if the number actually is very close to zero.
    30643812
     
    30883836
    30893837    def __pow__(self, e):
    30903838        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
     3839        be an arbitrary rational). If `p` is `(a/b)`, takes the principal
     3840        `b`'th root of self, then takes that to the `a`'th power. (Note
    30933841        that this differs from ``__pow__`` on algebraic reals, where real
    30943842        roots are preferred over principal roots if they exist.)
    30953843
     
    31233871            2
    31243872            sage: a = QQbar.zeta(7)^(1/3); a
    31253873            0.9555728057861407? + 0.2947551744109043?*I
    3126             sage: a == QQbar.zeta(21)           
     3874            sage: a == QQbar.zeta(21)
    31273875            True
    31283876            sage: QQbar.zeta(7)^6
    31293877            0.6234898018587335? - 0.7818314824680299?*I
     
    31813929                    if val.imag().is_zero() and val.real() < 0:
    31823930                        argument_is_pi = True
    31833931                    break
    3184        
     3932
    31853933        target_abs = abs(val) ** e
    31863934        target_arg = argument * e
    31873935
     
    32133961    def _mpfr_(self, field):
    32143962        r"""
    32153963        Given a ``RealField``, compute a good approximation to self in
    3216         that field.  Works only if the imaginary component of self is
     3964        that field. Works only if the imaginary component of self is
    32173965        exactly zero; otherwise it raises a ``ValueError``.
    32183966
    32193967        EXAMPLES::
     
    32313979
    32323980    def __float__(self):
    32333981        r"""
    3234         Compute a good float approximation to self.  Works only if the
     3982        Compute a good float approximation to self. Works only if the
    32353983        imaginary component of self is exactly zero; otherwise it
    32363984        raises a ``ValueError``.
    32373985
     
    32473995            ValueError: Cannot coerce algebraic number with non-zero imaginary part to algebraic real
    32483996        """
    32493997        return AA(self).__float__()
    3250        
     3998
    32513999    def __complex__(self):
    32524000        r"""
    32534001        Compute a good complex approximation to self.
     
    32754023        return cdf(CC(self))
    32764024
    32774025    def _interval_fast(self, prec):
     4026        r"""
     4027        Shortcut for :meth:`AlgebraicNumber_base.interval_fast` which uses the complex interval field.
     4028
     4029        EXAMPLE::
     4030
     4031            sage: QQbar(sqrt(-5))._interval_fast(100)
     4032            2.236067977499789696409173...?*I
     4033        """
    32784034        return self.interval_fast(ComplexIntervalField(prec))
    32794035
    32804036    def _integer_(self, ZZ=None):
     
    33324088        return AA(self)._rational_()
    33334089
    33344090    def real(self):
     4091        r"""
     4092        Return the real part of self.
     4093
     4094        EXAMPLE::
     4095
     4096            sage: QQbar.zeta(5).real()
     4097            0.3090169943749474?
     4098        """
    33354099        return AlgebraicReal(self._descr.real(self))
    33364100
    33374101    def imag(self):
     4102        r"""
     4103        Return the imaginary part of self.
     4104
     4105        EXAMPLE::
     4106
     4107            sage: QQbar.zeta(7).imag()
     4108            0.7818314824680299?
     4109        """
    33384110        return AlgebraicReal(self._descr.imag(self))
    33394111
    33404112    def conjugate(self):
     
    33544126
    33554127    def norm(self):
    33564128        r"""
    3357         Returns ``self * self.conjugate()``.  This is the algebraic
     4129        Returns ``self * self.conjugate()``. This is the algebraic
    33584130        definition of norm, if we view ``QQbar`` as ``AA[I]``.
    33594131
    33604132        EXAMPLES::
     
    33714143    def interval_exact(self, field):
    33724144        r"""
    33734145        Given a ``ComplexIntervalField``, compute the best possible
    3374         approximation of this number in that field.  Note that if
     4146        approximation of this number in that field. Note that if
    33754147        either the real or imaginary parts of this number are
    33764148        sufficiently close to some floating-point number (and, in
    33774149        particular, if either is exactly representable in floating-point),
     
    33904162            0
    33914163        """
    33924164        if not is_ComplexIntervalField(field):
    3393             raise ValueError, "AlgebraicNumber interval_exact requires a ComplexIntervalField"
     4165            raise ValueError("AlgebraicNumber interval_exact requires a ComplexIntervalField")
    33944166        rfld = field._real_field()
    33954167        re = self.real().interval_exact(rfld)
    33964168        im = self.imag().interval_exact(rfld)
    33974169        return field(re, im)
    33984170
    33994171    def _complex_mpfr_field_(self, field):
     4172        r"""
     4173        Compute an approximation to self in the given field, which may be
     4174        either an interval field (in which case ``self.interval()`` is called)
     4175        or any other complex field (in which case ``self.complex_number()`` is
     4176        called).
     4177
     4178        EXAMPLE::
     4179
     4180            sage: a = QQbar(1 + I).sqrt()
     4181            sage: t = a._complex_mpfr_field_(CIF); t
     4182            1.098684113467810? + 0.4550898605622274?*I
     4183            sage: parent(t)
     4184            Complex Interval Field with 53 bits of precision
     4185            sage: t = a._complex_mpfr_field_(ComplexField(100)); t
     4186            1.0986841134678099660398011952 + 0.45508986056222734130435775782*I
     4187            sage: parent(t)
     4188            Complex Field with 100 bits of precision
     4189        """
    34004190        if is_ComplexIntervalField(field):
    34014191            return self.interval(field)
    34024192        else:
    34034193            return self.complex_number(field)
    34044194
    3405 
    34064195    def complex_number(self, field):
    34074196        r""" Given a ``ComplexField``, compute a good approximation to
    3408         self in that field.  The approximation will be off by at most
     4197        self in that field. The approximation will be off by at most
    34094198        two ulp's in each component, except for components which are
    34104199        very close to zero, which will have an absolute error at most
    34114200        ``2**(-(field.prec()-1))``.
     
    34244213    def complex_exact(self, field):
    34254214        r"""
    34264215        Given a ``ComplexField``, return the best possible approximation of
    3427         this number in that field.  Note that if either component is
     4216        this number in that field. Note that if either component is
    34284217        sufficiently close to the halfway point between two floating-point
    34294218        numbers in the corresponding ``RealField``, then this will trigger
    34304219        exact computation, which may be very slow.
     
    34394228        rfld = field._real_field()
    34404229        re = self.real().real_exact(rfld)
    34414230        im = self.imag().real_exact(rfld)
    3442         return field(re, im)       
     4231        return field(re, im)
    34434232
    34444233    def multiplicative_order(self):
    34454234        r"""
    34464235        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
     4236        number. That is, find the smallest positive integer `n` such
     4237        that `x^n = 1`. If there is no such `n`, returns ``+Infinity``.
     4238
     4239        We first check that ``abs(x)`` is very close to 1. If so, we compute
    34514240        `x` exactly and examine its argument.
    34524241
    34534242        EXAMPLES::
     
    34754264    def rational_argument(self):
    34764265        r"""
    34774266        Returns the argument of self, divided by `2\pi`, as long as this
    3478         result is rational.  Otherwise returns None. Always triggers
     4267        result is rational. Otherwise returns None. Always triggers
    34794268        exact computation.
    34804269
    34814270        EXAMPLES::
     
    34934282            sage: (QQbar.zeta(3)^65536).rational_argument()
    34944283            1/3
    34954284        """
    3496         # This always triggers exact computation.  An alternate method
     4285        # This always triggers exact computation. An alternate method
    34974286        # could almost always avoid exact computation when the result
    34984287        # is None: if we can compute an upper bound on the degree of
    34994288        # this algebraic number without exact computation, we can use
     
    35104299    def __init__(self, x):
    35114300        """
    35124301        Create an algebraic real from x, possibly taking the real part of x.
    3513        
     4302
    35144303        TESTS:
    35154304
    3516         Both of the following examples, from trac 11728, trigger
    3517         taking the real part below.  This is necessary because
     4305        Both of the following examples, from :trac:`11728`, trigger
     4306        taking the real part below. This is necessary because
    35184307        sometimes a very small (e.g., 1e-17) complex part appears in a
    35194308        complex interval used to create an AlgebraicReal.::
    35204309
     
    35324321        part.
    35334322
    35344323        EXAMPLES::
    3535        
     4324
    35364325            sage: a = QQbar((-1)^(1/4)); b = AA(a^3-a); b._value
    35374326            -1.4142135623730950488?
    35384327            sage: b._value = a._value; b._value
     
    35514340        Recompute the interval bounding this number with higher-precision
    35524341        interval arithmetic.
    35534342
     4343        EXAMPLE::
     4344
     4345            sage: a = QQbar(sqrt(2))
     4346            sage: a._more_precision()
     4347
    35544348        TESTS:
    35554349
    35564350        We have to ensure after doing this that self._value is still
    35574351        real which isn't the case without calling _ensure_real (see
    3558         trac 11728)::
    3559        
     4352        :trac:`11728`)::
     4353
    35604354            sage: P = AA[x](1+x^4); a1,a2 = P.factor()[0][0],P.factor()[1][0]; a1*a2
    35614355            x^4 + 1.000000000000000?
    35624356            sage: a1,a2
     
    36034397    def __pow__(self, e):
    36044398        """
    36054399        ``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
     4400        arbitrary rational). If `p` is `(a/b)`, takes the `b`'th root of
     4401        self, then takes that to the `a`'th power. If self is negative
    36084402        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
     4403        `b` is even, this takes a complex root. Note that the behavior
    36104404        when self is negative and `b` is odd differs from the complex
    36114405        case; algebraic numbers select the principal complex `b`'th
    36124406        root, but algebraic reals select the real root.
     
    37124506        """
    37134507        if self._value.lower().ceiling() > self._value.upper().floor():
    37144508            # The value is known to be non-integral.
    3715             raise ValueError, "Cannot coerce non-integral Algebraic Real %s to Integer" % self
     4509            raise ValueError("Cannot coerce non-integral Algebraic Real %s to Integer" % self)
    37164510
    37174511        self.exactify()
    37184512        if not self._descr.is_rational():
    3719             raise ValueError, "Cannot coerce irrational Algebraic Real %s to Integer" % self
     4513            raise ValueError("Cannot coerce irrational Algebraic Real %s to Integer" % self)
    37204514
    37214515        return ZZ(self._descr.rational_value())
    37224516
     
    37414535        """
    37424536        self.exactify()
    37434537        if not self._descr.is_rational():
    3744             raise ValueError, "Cannot coerce irrational Algebraic Real %s to Rational" % self
     4538            raise ValueError("Cannot coerce irrational Algebraic Real %s to Rational" % self)
    37454539
    37464540        return QQ(self._descr.rational_value())
    37474541
     
    38214615            return self.sign()
    38224616
    38234617    def _interval_fast(self, prec):
     4618        r"""
     4619        Compute an approximation to this ``AlgebraicReal`` object in a real interval field of precision prec.
     4620
     4621        EXAMPLE::
     4622
     4623            sage: t = AA(sqrt(7))
     4624            sage: t._interval_fast(100)
     4625            2.64575131106459059050161575364?
     4626        """
    38244627        return self.interval_fast(RealIntervalField(prec))
    38254628
    38264629    def interval_exact(self, field):
    38274630        """
    38284631        Given a ``RealIntervalField``, compute the best possible
    3829         approximation of this number in that field.  Note that if this
     4632        approximation of this number in that field. Note that if this
    38304633        number is sufficiently close to some floating-point number
    38314634        (and, in particular, if this number is exactly representable in
    38324635        floating-point), then this will trigger exact computation, which
     
    38874690    def real_number(self, field):
    38884691        """
    38894692        Given a ``RealField``, compute a good approximation to self in
    3890         that field.  The approximation will be off by at most two
     4693        that field. The approximation will be off by at most two
    38914694        ulp's, except for numbers which are very close to 0, which
    38924695        will have an absolute error at most
    3893         ``2**(-(field.prec()-1))``.  Also, the rounding mode of the
     4696        ``2**(-(field.prec()-1))``. Also, the rounding mode of the
    38944697        field is respected.
    38954698
    38964699        EXAMPLES::
     
    39634766        return float(RR(self))
    39644767
    39654768    def _complex_mpfr_field_(self, field):
     4769        r"""
     4770        Compute an approximation to this ``AlgebraicReal`` in the given field,
     4771        which may be an interval field (in which case ``self.interval()`` is
     4772        called) or any other real number field (in which case
     4773        ``self.real_number()`` is called.
     4774
     4775        Note that the field ``field`` should be a *complex* field (whose
     4776        ``_real_field()`` method will be called to obtain a real subfield.)
     4777
     4778        EXAMPLE::
     4779
     4780            sage: AA(golden_ratio)._complex_mpfr_field_(ComplexIntervalField(100))
     4781            1.618033988749894848204586834365?
     4782            sage: AA(golden_ratio)._complex_mpfr_field_(ComplexField(100))
     4783            1.6180339887498948482045868344
     4784        """
    39664785        if is_ComplexIntervalField(field):
    39674786            return field(self.interval(field._real_field()))
    39684787        else:
     
    39714790    def real_exact(self, field):
    39724791        r"""
    39734792        Given a ``RealField``, compute the best possible approximation of
    3974         this number in that field.  Note that if this number is
     4793        this number in that field. Note that if this number is
    39754794        sufficiently close to the halfway point between two
    39764795        floating-point numbers in the field (for the default
    39774796        round-to-nearest mode) or if the number is sufficiently close
     
    40374856
    40384857        val = self.interval_exact(rifp1)
    40394858
    4040         # Call the largest floating-point number <= self 'x'.  Then
     4859        # Call the largest floating-point number <= self 'x'. Then
    40414860        # val may be [x .. x], [x .. x + 1/2 ulp],
    40424861        # [x + 1/2 ulp .. x + 1/2 ulp], or [x + 1/2 ulp .. x + 1 ulp];
    40434862        # in the second and fourth cases, the true value is not equal
     
    40584877class ANRational(ANDescr):
    40594878    r"""
    40604879    The subclass of ``ANDescr`` that represents an arbitrary
    4061     rational.  This class is private, and should not be used directly.
     4880    rational. This class is private, and should not be used directly.
    40624881    """
    40634882
    40644883    def __init__(self, x):
     
    40764895        elif isinstance(x, (int, long)):
    40774896            self._value = ZZ(x)
    40784897        else:
    4079             raise TypeError, "Illegal initializer for algebraic number rational"
     4898            raise TypeError("Illegal initializer for algebraic number rational")
    40804899
    40814900    def __reduce__(self):
    40824901        """
     
    40844903
    40854904        EXAMPLES::
    40864905
    4087             sage: t = AA(5/2); type(t._descr)           
     4906            sage: t = AA(5/2); type(t._descr)
    40884907            <class 'sage.rings.qqbar.ANRational'>
    40894908            sage: loads(dumps(t)) == t
    40904909            True
     
    40924911        return (ANRational, (self._value, ))
    40934912
    40944913    def _repr_(self):
     4914        r"""
     4915        String representation of self.
     4916
     4917        EXAMPLES::
     4918
     4919            sage: QQbar(2/3)._repr_()
     4920            '2/3'
     4921        """
    40954922        return repr(self._value)
    40964923
    40974924    def handle_sage_input(self, sib, coerce, is_qqbar):
     
    41244951        return (v, False)
    41254952
    41264953    def kind(self):
     4954        r"""
     4955        Return a string describing what kind of element this is. Since this is
     4956        a rational number, the result is either ``'zero'`` or ``'rational'``.
     4957
     4958        EXAMPLES::
     4959
     4960            sage: a = QQbar(3)._descr; type(a)
     4961            <class 'sage.rings.qqbar.ANRational'>
     4962            sage: a.kind()
     4963            'rational'
     4964            sage: a = QQbar(0)._descr; type(a)
     4965            <class 'sage.rings.qqbar.ANRational'>
     4966            sage: a.kind()
     4967            'zero'
     4968        """
    41274969        if self._value.is_zero():
    41284970            return 'zero'
    41294971        else:
    41304972            return 'rational'
    41314973
    41324974    def _interval_fast(self, prec):
     4975        r"""
     4976        Return an approximation to self in a real interval field of precision prec.
     4977
     4978        EXAMPLE::
     4979
     4980            sage: QQbar(355/113)._descr._interval_fast(30)
     4981            3.14159292?
     4982        """
    41334983        return RealIntervalField(prec)(self._value)
    41344984
    41354985    def generator(self):
     4986        r"""
     4987        Return an :class:`AlgebraicGenerator` object associated to this
     4988        element. Returns the trivial generator, since self is rational.
     4989
     4990        EXAMPLE::
     4991
     4992            sage: QQbar(0)._descr.generator()
     4993            Trivial generator
     4994        """
    41364995        return qq_generator
    41374996
    41384997    def is_complex(self):
     4998        r"""
     4999        Return False, since rational numbers are real
     5000
     5001        EXAMPLE::
     5002
     5003            sage: QQbar(1/7)._descr.is_complex()
     5004            False
     5005        """
    41395006        return False
    41405007
    41415008    def is_rational(self):
     5009        r"""
     5010        Return True, since this is a rational number.
     5011
     5012        EXAMPLE::
     5013
     5014            sage: QQbar(34/9)._descr.is_rational()
     5015            True
     5016            sage: QQbar(0)._descr.is_rational()
     5017            True
     5018        """
    41425019        return True
    41435020
    41445021    def rational_value(self):
     5022        r"""
     5023        Return self as a rational number.
     5024
     5025        EXAMPLE::
     5026
     5027            sage: a = QQbar(789/19)
     5028            sage: b = a._descr.rational_value(); b
     5029            789/19
     5030            sage: type(b)
     5031            <type 'sage.rings.rational.Rational'>
     5032        """
    41455033        return self._value
    41465034
    41475035    def exactify(self):
     5036        r"""
     5037        Calculate self exactly. Since self is a rational number, return self.
     5038
     5039        EXAMPLE::
     5040
     5041            sage: a = QQbar(1/3)._descr
     5042            sage: a.exactify() is a
     5043            True
     5044        """
    41485045        return self
    41495046
    41505047    def is_exact(self):
     5048        r"""
     5049        Return True, since rationals are exact.
     5050
     5051        EXAMPLE::
     5052
     5053            sage: QQbar(1/3)._descr.is_exact()
     5054            True
     5055        """
    41515056        return True
    41525057
    41535058    def is_simple(self):
     
    41655070        return True
    41665071
    41675072    def minpoly(self):
     5073        r"""
     5074        Return the min poly of self over `\QQ`.
     5075
     5076        EXAMPLE::
     5077
     5078            sage: QQbar(7)._descr.minpoly()
     5079            x - 7
     5080        """
    41685081        return QQx_x - self._value
    41695082
    41705083    def neg(self, n):
     5084        r"""
     5085        Negation of self.
     5086
     5087        EXAMPLE::
     5088
     5089            sage: a = QQbar(3)
     5090            sage: b = a._descr
     5091            sage: type(b)
     5092            <class 'sage.rings.qqbar.ANRational'>
     5093            sage: b.neg(a)
     5094            -3
     5095        """
    41715096        return ANRational(-self._value)
    41725097
    41735098    def invert(self, n):
     5099        r"""
     5100        1/self.
     5101
     5102        EXAMPLE::
     5103
     5104            sage: a = QQbar(3)
     5105            sage: b = a._descr
     5106            sage: b.invert(a)
     5107            1/3
     5108        """
    41745109        return ANRational(~self._value)
    41755110
    41765111    def abs(self, n):
     5112        r"""
     5113        Absolute value of self.
     5114
     5115        EXAMPLE::
     5116
     5117            sage: a = QQbar(3)
     5118            sage: b = a._descr
     5119            sage: b.abs(a)
     5120            3
     5121        """
    41775122        return ANRational(abs(self._value))
    41785123
    41795124    def rational_argument(self, n):
     5125        r"""
     5126        Return the argument of self divided by `2 \pi`, or ``None`` if this
     5127        element is 0.
     5128
     5129        EXAMPLE::
     5130
     5131            sage: QQbar(3)._descr.rational_argument(None)
     5132            0
     5133            sage: QQbar(-3)._descr.rational_argument(None)
     5134            1/2
     5135            sage: QQbar(0)._descr.rational_argument(None) is None
     5136            True
     5137        """
    41805138        if self._value > 0:
    41815139            return QQ(0)
    41825140        if self._value < 0:
     
    41845142        return None
    41855143
    41865144    def gaussian_value(self):
     5145        r"""
     5146        Return self as an element of `\QQ(i)`.
     5147
     5148        EXAMPLE::
     5149
     5150            sage: a = QQbar(3)
     5151            sage: b = a._descr
     5152            sage: x = b.gaussian_value(); x
     5153            3
     5154            sage: x.parent()
     5155            Number Field in I with defining polynomial x^2 + 1
     5156        """
    41875157        return QQbar_I_nf(self._value)
    41885158
    41895159    def angle(self):
     5160        r"""
     5161        Return a rational number `q \in (-1/2, 1/2]` such that ``self`` is a rational multiple of
     5162        `e^{2\pi i q}`. Always returns 0, since this element is rational.
     5163
     5164        EXAMPLE::
     5165
     5166            sage: QQbar(3)._descr.angle()
     5167            0
     5168            sage: QQbar(-3)._descr.angle()
     5169            0
     5170            sage: QQbar(0)._descr.angle()
     5171            0
     5172        """
    41905173        return QQ_0
    41915174
    41925175    def scale(self):
     5176        r"""
     5177        Return a rational number `r` such that ``self`` is equal to `r e^{2 \pi
     5178        i q}` for some `q \in (-1/2, 1/2]`.  In other words, just return self
     5179        as a rational number.
     5180
     5181        EXAMPLE::
     5182
     5183            sage: QQbar(-3)._descr.scale()
     5184            -3
     5185        """
    41935186        return self._value
    41945187
    41955188class ANRootOfUnity(ANDescr):
    41965189    r"""
    41975190    The subclass of ``ANDescr`` that represents a rational multiplied
    4198     by a root of unity.  This class is private, and should not be
     5191    by a root of unity. This class is private, and should not be
    41995192    used directly.
    42005193
    42015194    Such numbers are represented by a "rational angle" and a rational
    4202     scale.  The "rational angle" is the argument of the number, divided by
     5195    scale. The "rational angle" is the argument of the number, divided by
    42035196    `2\pi`; so given angle `\alpha` and scale `s`, the number is:
    42045197    `s(\cos(2\pi\alpha) + \sin(2\pi\alpha)i)`; or equivalently
    42055198    `s(e^{2\pi\alpha i})`.
    42065199
    42075200    We normalize so that `0<\alpha<\frac{1}{2}`; this requires
    4208     allowing both positive and negative scales.  (Attempts to create
     5201    allowing both positive and negative scales. (Attempts to create
    42095202    an ``ANRootOfUnity`` with an angle which is a multiple of
    42105203    `\frac{1}{2}` end up creating an ``ANRational`` instead.)
    42115204    """
     
    42135206    def __new__(self, angle, scale):
    42145207        r"""
    42155208        Construct an ``ANRootOfUnity`` from a rational angle and a rational
    4216         scale.  If the number is actually a real rational, returns an
     5209        scale. If the number is actually a real rational, returns an
    42175210        ``ANRational`` instead.
    42185211        """
    42195212        if scale.is_zero():
     
    42295222        else:
    42305223            # int_angle is even
    42315224            return ANRational(scale)
    4232        
     5225
    42335226    def __init__(self, angle, scale):
    42345227        """
    42355228        Construct an ``ANRootOfUnity`` from a rational angle and a rational
    42365229        scale.
    4237         """
    4238 
     5230
     5231        EXAMPLE::
     5232
     5233            sage: type((2/3 * QQbar.zeta(7))._descr) # indirect doctest
     5234            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5235        """
    42395236        angle2 = angle * 2
    42405237        fl2 = angle2.floor()
    42415238        angle2 = angle2 - fl2
     
    42515248
    42525249        EXAMPLES::
    42535250
    4254             sage: t = QQbar.zeta(3) * 5; type(t._descr)           
     5251            sage: t = QQbar.zeta(3) * 5; type(t._descr)
    42555252            <class 'sage.rings.qqbar.ANRootOfUnity'>
    42565253            sage: loads(dumps(t)) == t
    42575254            True
     
    42595256        return (ANRootOfUnity, (self._angle, self._scale))
    42605257
    42615258    def _repr_(self):
     5259        r"""
     5260        String representation of this ``ANRootOfUnity`` element.
     5261
     5262        EXAMPLE::
     5263
     5264            sage: t = QQbar.zeta(3) * 5; type(t._descr)
     5265            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5266            sage: t._descr._repr_()
     5267            '5*e^(2*pi*I*1/3)'
     5268        """
    42625269        return "%s*e^(2*pi*I*%s)"%(self._scale, self._angle)
    42635270
    42645271    def handle_sage_input(self, sib, coerce, is_qqbar):
     
    43125319            return (v, True)
    43135320
    43145321    def kind(self):
     5322        r"""
     5323        Return a string describing what kind of element this is.
     5324
     5325        EXAMPLE::
     5326
     5327            sage: QQbar.zeta(4)._descr.kind()
     5328            'imaginary'
     5329            sage: QQbar.zeta(5)._descr.kind()
     5330            'rootunity'
     5331        """
    43155332        if self._angle == QQ_1_4:
    43165333            return 'imaginary'
    43175334        else:
    43185335            return 'rootunity'
    43195336
    43205337    def _interval_fast(self, prec):
     5338        r"""
     5339        Calculate an approximation to self in an interval field of precision prec.
     5340
     5341        EXAMPLE::
     5342
     5343            sage: QQbar.zeta(5)._descr._interval_fast(100)
     5344            0.30901699437494742410229341719? + 0.95105651629515357211643933338?*I
     5345        """
    43215346        argument = self._angle * RealIntervalField(prec).pi() * 2
    43225347        if self._angle == QQ_1_4:
    43235348            return ComplexIntervalField(prec)(0, self._scale)
     
    43255350            return ComplexIntervalField(prec)(argument.cos(), argument.sin()) * self._scale
    43265351
    43275352    def generator(self):
     5353        r"""
     5354        Return an :class:`AlgebraicGenerator` object corresponding to this element.
     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.generator()
     5362            1*e^(2*pi*I*1/34)
     5363        """
    43285364        return cyclotomic_generator(self._angle.denominator())
    43295365
    43305366    def field_element_value(self):
     5367        r"""
     5368        Return self as an element of a cyclotomic field.
     5369
     5370        EXAMPLE::
     5371
     5372            sage: t = (QQbar.zeta(17)^13)._descr
     5373            sage: type(t)
     5374            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5375            sage: s = t.field_element_value(); s
     5376            -zeta34^9
     5377            sage: s.parent()
     5378            Cyclotomic Field of order 34 and degree 16
     5379        """
    43315380        gen = self.generator()
    43325381        f = gen._field
    43335382        a = f.gen()
    43345383        return self._scale * a ** self._angle.numerator()
    43355384
    43365385    def is_complex(self):
     5386        r"""
     5387        Return True, since this class is only used for complex algebraic numbers.
     5388
     5389        EXAMPLE::
     5390
     5391            sage: t = (QQbar.zeta(17)^13)._descr
     5392            sage: type(t)
     5393            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5394            sage: t.is_complex()
     5395            True
     5396        """
    43375397        return True
    43385398
    43395399    def exactify(self):
     5400        r"""
     5401        Return self, since ``ANRootOfUnity`` elements are exact.
     5402
     5403        EXAMPLE::
     5404
     5405            sage: t = (QQbar.zeta(17)^13)._descr
     5406            sage: type(t)
     5407            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5408            sage: t.exactify() is t
     5409            True
     5410        """
    43405411        return self
    43415412
    43425413    def is_exact(self):
     5414        r"""
     5415        Return True, since ``ANRootOfUnity`` elements are exact.
     5416
     5417        EXAMPLE::
     5418
     5419            sage: t = (QQbar.zeta(17)^13)._descr
     5420            sage: type(t)
     5421            <class 'sage.rings.qqbar.ANRootOfUnity'>
     5422            sage: t.is_exact()
     5423            True
     5424        """
    43435425        return True
    43445426
    43455427    def is_simple(self):
     
    43775459        p = p / p.leading_coefficient()
    43785460        return p
    43795461
     5462    # These all ignore "n".
     5463
    43805464    def neg(self, n):
     5465        r"""
     5466        Negation of self.
     5467
     5468        EXAMPLE::
     5469
     5470            sage: a = QQbar.zeta(17)^5 * 4/3; a._descr
     5471            4/3*e^(2*pi*I*5/17)
     5472            sage: a._descr.neg(None)
     5473            -4/3*e^(2*pi*I*5/17)
     5474        """
    43815475        return ANRootOfUnity(self._angle, -self._scale)
    43825476
    43835477    def invert(self, n):
     5478        r"""
     5479        1/self.
     5480
     5481        EXAMPLE::
     5482
     5483            sage: a = QQbar.zeta(17)^5 * 4/3; a._descr
     5484            4/3*e^(2*pi*I*5/17)
     5485            sage: a._descr.invert(None)
     5486            -3/4*e^(2*pi*I*7/34)
     5487        """
    43845488        # We want ANRootOfUnity(-self._angle, ~self._scale);
    43855489        # but that's not normalized, so we pre-normalize it to:
    43865490        return ANRootOfUnity(QQ_1_2 - self._angle, -~self._scale)
    43875491
    43885492    def conjugate(self, n):
     5493        r"""
     5494        Complex conjugate of self.
     5495
     5496        EXAMPLE::
     5497
     5498            sage: a = QQbar.zeta(17)^5 * 4/3; a._descr
     5499            4/3*e^(2*pi*I*5/17)
     5500            sage: a._descr.conjugate(None)
     5501            -4/3*e^(2*pi*I*7/34)
     5502        """
    43895503        # We want ANRootOfUnity(-self._angle, self._scale);
    43905504        # but that's not normalized, so we pre-normalize it to:
    43915505        return ANRootOfUnity(QQ_1_2 - self._angle, -self._scale)
    43925506
    43935507    def abs(self, n):
     5508        r"""
     5509        Absolute value of self.
     5510
     5511        EXAMPLE::
     5512
     5513            sage: a = -QQbar.zeta(17)^5 * 4/3; a._descr
     5514            -4/3*e^(2*pi*I*5/17)
     5515            sage: a._descr.abs(None)
     5516            4/3
     5517        """
    43945518        return ANRational(abs(self._scale))
    43955519
    43965520    def norm(self, n):
     5521        r"""
     5522        Norm (square of absolute value) of self.
     5523
     5524        EXAMPLE::
     5525
     5526            sage: a = -QQbar.zeta(17)^5 * 4/3; a._descr
     5527            -4/3*e^(2*pi*I*5/17)
     5528            sage: a._descr.norm(None)
     5529            16/9
     5530        """
    43975531        return ANRational(self._scale * self._scale)
    43985532
    43995533    def rational_argument(self, n):
     5534        r"""
     5535        Return the rational `\theta \in (-1/2, 1/2)` such that self represents
     5536        a positive rational multiple of `e^{2 \pi i \theta}`.
     5537
     5538        EXAMPLE::
     5539
     5540            sage: (-QQbar.zeta(3))._descr.angle()
     5541            1/3
     5542            sage: (-QQbar.zeta(3))._descr.rational_argument(None)
     5543            -1/6
     5544        """
    44005545        if self._scale > 0:
    44015546            return self._angle
    44025547        else:
    44035548            return self._angle - QQ_1_2
    4404    
     5549
    44055550    def gaussian_value(self):
     5551        r"""
     5552        Return self as an element of `\QQ(i)`` (assuming this is possible).
     5553
     5554        EXAMPLE::
     5555
     5556            sage: (-17*QQbar.zeta(4))._descr.gaussian_value()
     5557            -17*I
     5558            sage: (-17*QQbar.zeta(5))._descr.gaussian_value()
     5559            Traceback (most recent call last):
     5560            ...
     5561            AssertionError
     5562        """
    44065563        assert(self._angle == QQ_1_4)
    44075564        return QQbar_I_nf(self._scale * QQbar_I_nf.gen())
    44085565
    44095566    def angle(self):
     5567        r"""
     5568        Return the rational `\theta \in [0, 1/2)` such that self represents a
     5569        rational multiple of `e^{2 \pi i \theta}`.
     5570
     5571        EXAMPLE::
     5572
     5573            sage: (-QQbar.zeta(3))._descr.angle()
     5574            1/3
     5575            sage: (-QQbar.zeta(3))._descr.rational_argument(None)
     5576            -1/6
     5577        """
    44105578        return self._angle
    44115579
    44125580    def scale(self):
     5581        r"""
     5582        Return the scale of self, the unique rational `r` such that self is
     5583        equal to `re^{2\pi i \theta}` for some `theta \in (-1/2, 1/2]`. This is
     5584        `\pm 1` times ``self.abs()``.
     5585
     5586        EXAMPLE::
     5587
     5588            sage: (QQbar.zeta(5)^3)._descr.scale()
     5589            -1
     5590        """
    44135591        return self._scale
    44145592
    44155593def is_AlgebraicReal(x):
     5594    r"""
     5595    Test if ``x`` is an instance of :class:`~AlgebraicReal`. For internal use.
     5596
     5597    EXAMPLE::
     5598
     5599        sage: from sage.rings.qqbar import is_AlgebraicReal
     5600        sage: is_AlgebraicReal(AA(sqrt(2)))
     5601        True
     5602        sage: is_AlgebraicReal(QQbar(sqrt(2)))
     5603        False
     5604        sage: is_AlgebraicReal("spam")
     5605        False
     5606    """
    44165607    return isinstance(x, AlgebraicReal)
    44175608
    44185609def is_AlgebraicNumber(x):
     5610    r"""
     5611    Test if ``x`` is an instance of :class:`~AlgebraicNumber`. For internal use.
     5612
     5613    EXAMPLE::
     5614
     5615        sage: from sage.rings.qqbar import is_AlgebraicNumber
     5616        sage: is_AlgebraicNumber(AA(sqrt(2)))
     5617        False
     5618        sage: is_AlgebraicNumber(QQbar(sqrt(2)))
     5619        True
     5620        sage: is_AlgebraicNumber("spam")
     5621        False
     5622    """
    44195623    return isinstance(x, AlgebraicNumber)
    44205624
    44215625QQbarPoly = PolynomialRing(QQbar, 'x')
     
    44275631
    44285632    If multiple algebraic numbers are created as roots of a single
    44295633    polynomial, this allows the polynomial and information about
    4430     the polynomial to be shared.  This reduces work if the polynomial
     5634    the polynomial to be shared. This reduces work if the polynomial
    44315635    must be recomputed at higher precision, or if it must be factored.
    44325636
    44335637    This class is private, and should only be constructed by
    44345638    ``AA.common_polynomial()`` or ``QQbar.common_polynomial()``, and should
    44355639    only be used as an argument to ``AA.polynomial_root()`` or
    4436     ``QQbar.polynomial_root()``.  (It doesn't matter whether you create
     5640    ``QQbar.polynomial_root()``. (It doesn't matter whether you create
    44375641    the common polynomial with ``AA.common_polynomial()`` or
    44385642    ``QQbar.common_polynomial()``.)
    44395643
     
    44485652    """
    44495653
    44505654    def __init__(self, poly):
     5655        r"""
     5656        Initialize this AlgebraicPolynomialTracker object.
     5657
     5658        EXAMPLE::
     5659
     5660            sage: x = polygen(QQbar)
     5661            sage: P = QQbar.common_polynomial(x^2 - x - 1)
     5662            sage: type(P) # indirect doctest
     5663            <class 'sage.rings.qqbar.AlgebraicPolynomialTracker'>
     5664        """
    44515665        if not is_Polynomial(poly):
    4452             raise ValueError, "Trying to create AlgebraicPolynomialTracker on non-Polynomial"
     5666            raise ValueError("Trying to create AlgebraicPolynomialTracker on non-Polynomial")
    44535667        if isinstance(poly.base_ring(), AlgebraicField_common):
    44545668            complex = is_AlgebraicField(poly.base_ring())
    44555669        else:
     
    45025716            {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})})}})}
    45035717        """
    45045718        # XXX It would be nicer to skip the "AA.common_polynomial()"
    4505         # wrapper if the polynomial is not actually shared.  But
     5719        # wrapper if the polynomial is not actually shared. But
    45065720        # sage_input.py isn't quite that generic.
    45075721        v = sib.name('AA').common_polynomial(self._poly)
    45085722        sib.id_cache(self, v, 'cp')
    45095723        return v
    45105724
    45115725    def _repr_(self):
     5726        r"""
     5727        String representation of self.
     5728
     5729        EXAMPLE::
     5730
     5731            sage: x = polygen(QQ)
     5732            sage: AA.common_polynomial(x^3 - 7)._repr_()
     5733            'x^3 - 7'
     5734        """
    45125735        return repr(self._poly)
    45135736
    45145737    def poly(self):
     5738        r"""
     5739        Return the underlying polynomial of self.
     5740
     5741        EXAMPLE::
     5742
     5743            sage: x = polygen(QQ); f = x^3 - 7
     5744            sage: g = AA.common_polynomial(f)
     5745            sage: g.poly() == f
     5746            True
     5747        """
    45155748        return self._poly
    45165749
    45175750    def is_complex(self):
     5751        r"""
     5752        Return True if the coefficients of this polynomial are non-real.
     5753
     5754        EXAMPLE::
     5755
     5756            sage: x = polygen(QQ); f = x^3 - 7
     5757            sage: g = AA.common_polynomial(f)
     5758            sage: g.is_complex()
     5759            False
     5760            sage: QQbar.common_polynomial(x^3 - QQbar(I)).is_complex()
     5761            True
     5762        """
    45185763        return self._complex
    45195764
    45205765    def complex_roots(self, prec, multiplicity):
    45215766        """
     5767        Find the roots of self in the complex field to precision prec.
     5768
    45225769        EXAMPLES::
    45235770
    45245771            sage: x = polygen(ZZ)
     
    45545801        Compute a common field that holds all of the algebraic coefficients
    45555802        of this polynomial, then factor the polynomial over that field.
    45565803        Store the factors for later use (ignoring multiplicity).
     5804
     5805        EXAMPLE::
     5806
     5807            sage: x = polygen(AA)
     5808            sage: p = sqrt(AA(2)) * x^2 - sqrt(AA(3))
     5809            sage: cp = AA.common_polynomial(p)
     5810            sage: cp._exact
     5811            False
     5812            sage: cp.exactify()
     5813            sage: cp._exact
     5814            True
    45575815        """
    45585816        if self._exact:
    45595817            return
     
    45825840            self._factors = [fac_exp[0] for fac_exp in fp.factor()]
    45835841
    45845842    def factors(self):
     5843        r"""
     5844        EXAMPLE::
     5845
     5846            sage: x=polygen(QQ); f=QQbar.common_polynomial(x^4 + 4)
     5847            sage: f.factors()
     5848            [y^2 - 2*y + 2, y^2 + 2*y + 2]
     5849        """
    45855850        self.exactify()
    45865851        return self._factors
    45875852
    45885853    def generator(self):
     5854        r"""
     5855        Return an :class:`AlgebraicGenerator` for a number field containing all
     5856        the coefficients of self.
     5857
     5858        EXAMPLE::
     5859
     5860            sage: x = polygen(AA)
     5861            sage: p = sqrt(AA(2)) * x^2 - sqrt(AA(3))
     5862            sage: cp = AA.common_polynomial(p)
     5863            sage: cp.generator()
     5864            Number Field in a with defining polynomial y^4 - 4*y^2 + 1 with a in 1.931851652578137?
     5865        """
    45895866        self.exactify()
    45905867        return self._gen
    45915868
     
    45965873    This class is private, and should not be used directly.
    45975874    """
    45985875    def __init__(self, poly, interval, multiplicity=1, is_pow=None):
     5876        r"""
     5877        Initialize this ``ANRoot`` object.
     5878
     5879        EXAMPLE::
     5880
     5881            sage: x = polygen(QQ); f = (x^3 + x + 1).roots(AA,multiplicities=False)[0]._descr
     5882            sage: type(f) # indirect doctest
     5883            <class 'sage.rings.qqbar.ANRoot'>
     5884        """
    45995885        if not isinstance(poly, AlgebraicPolynomialTracker):
    46005886            poly = AlgebraicPolynomialTracker(poly)
    46015887        self._poly = poly
     
    46045890        self._complex_poly = poly.is_complex()
    46055891        self._interval = self.refine_interval(interval, 64)
    46065892        self._is_pow = is_pow
    4607        
     5893
    46085894    def __reduce__(self):
    46095895        """
    46105896        Add customized pickling support.
     
    46215907        return (ANRoot, (self._poly, self._interval, self._multiplicity))
    46225908
    46235909    def _repr_(self):
     5910        r"""
     5911        String representation of self.
     5912
     5913        EXAMPLE::
     5914
     5915            sage: x=polygen(QQ); v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]
     5916            sage: v._descr._repr_()
     5917            'Root 1.618033988749894849? of x^2 - x - 1'
     5918        """
    46245919        return 'Root %s of %s'%(self._interval, self._poly)
    46255920
    46265921    def handle_sage_input(self, sib, coerce, is_qqbar):
     
    46355930            # Verified
    46365931            sqrt(AA(3)).nth_root(3)
    46375932
    4638         These two examples are too big to verify quickly.  (Verification
     5933        These two examples are too big to verify quickly. (Verification
    46395934        would create a field of degree 28.)::
    46405935
    46415936            sage: sage_input((sqrt(AA(3))^(5/7))^(9/4))
     
    46505945            sage: sage_input(QQbar.polynomial_root(x^3-5, CIF(RIF(-3, 0), RIF(0, 3))), verify=True)
    46515946            # Verified
    46525947            R.<x> = AA[]
    4653             QQbar.polynomial_root(AA.common_polynomial(x^3 - 5), CIF(RIF(-RR(0.85498797333834853), -RR(0.85498797333834842)), RIF(RR(1.4808826096823642), RR(1.4808826096823644))))           
     5948            QQbar.polynomial_root(AA.common_polynomial(x^3 - 5), CIF(RIF(-RR(0.85498797333834853), -RR(0.85498797333834842)), RIF(RR(1.4808826096823642), RR(1.4808826096823644))))
    46545949            sage: from sage.rings.qqbar import *
    46555950            sage: from sage.misc.sage_input import SageInputBuilder
    46565951            sage: sib = SageInputBuilder()
     
    46925987        return (parent.polynomial_root(poly, sib(good_intv)), True)
    46935988
    46945989    def kind(self):
     5990        r"""
     5991        Return a string indicating what kind of element this is.
     5992
     5993        EXAMPLE::
     5994
     5995            sage: (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.kind()
     5996            'other'
     5997        """
    46955998        return 'other'
    46965999
    46976000    def is_complex(self):
     6001        r"""
     6002        Whether this is a root in `\overline{\QQ}` (rather than `\mathbf{A}`).
     6003        Note that this may return True even if the root is actually real, as
     6004        the second example shows; it does *not* trigger exact computation to
     6005        see if the root is real.
     6006
     6007        EXAMPLE::
     6008
     6009            sage: x = polygen(QQ)
     6010            sage: (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.is_complex()
     6011            False
     6012            sage: (x^2 - x - 1).roots(ring=QQbar, multiplicities=False)[1]._descr.is_complex()
     6013            True
     6014        """
    46986015        return self._complex
    46996016
    47006017    def conjugate(self, n):
     6018        r"""
     6019        Complex conjugate of this ANRoot object.
     6020
     6021        EXAMPLE::
     6022
     6023            sage: a = (x^2 + 23).roots(ring=QQbar, multiplicities=False)[0]
     6024            sage: b = a._descr
     6025            sage: type(b)
     6026            <class 'sage.rings.qqbar.ANRoot'>
     6027            sage: c = b.conjugate(a); c
     6028            <class 'sage.rings.qqbar.ANUnaryExpr'>
     6029            sage: c.exactify()
     6030            -2*a + 1 where a^2 - a + 6 = 0 and a in 0.50000000000000000? - 2.397915761656360?*I
     6031        """
    47016032        if not self._complex:
    47026033            return self
    47036034        if not self._complex_poly:
     
    47066037        return ANUnaryExpr(n, 'conjugate')
    47076038
    47086039    def refine_interval(self, interval, prec):
     6040        r"""
     6041        Takes an interval which is assumed to enclose exactly one root
     6042        of the polynomial (or, with multiplicity=`k`, exactly one root
     6043        of the `k-1`-st derivative); and a precision, in bits.
     6044
     6045        Tries to find a narrow interval enclosing the root using
     6046        interval arithmetic of the given precision. (No particular
     6047        number of resulting bits of precision is guaranteed.)
     6048
     6049        Uses a combination of Newton's method (adapted for interval
     6050        arithmetic) and bisection. The algorithm will converge very
     6051        quickly if started with a sufficiently narrow interval.
     6052
     6053        EXAMPLES::
     6054
     6055            sage: from sage.rings.qqbar import ANRoot
     6056            sage: x = polygen(AA)
     6057            sage: rt2 = ANRoot(x^2 - 2, RIF(0, 2))
     6058            sage: rt2.refine_interval(RIF(0, 2), 75)
     6059            1.4142135623730950488017?
     6060        """
    47096061        if self._complex or self._complex_poly:
    47106062            v = self._complex_refine_interval(interval, prec)
    47116063            if self._complex:
     
    47176069
    47186070    def _real_refine_interval(self, interval, prec):
    47196071        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.
     6072        Does the calculation for ``refine_interval``.
    47316073
    47326074        EXAMPLES::
    47336075
    47346076            sage: from sage.rings.qqbar import ANRoot
    47356077            sage: x = polygen(AA)
    47366078            sage: rt2 = ANRoot(x^2 - 2, RIF(0, 2))
    4737             sage: rt2.refine_interval(RIF(0, 2), 75)
     6079            sage: rt2.refine_interval(RIF(0, 2), 75) # indirect doctest
    47386080            1.4142135623730950488017?
    47396081        """
    47406082        # Don't throw away bits in the original interval; doing so might
     
    47626104        # This special case is important: this is the only way we could
    47636105        # refine "infinitely deep" (we could get an interval of diameter
    47646106        # about 2^{-2^31}, and then hit floating-point underflow); avoiding
    4765         # this case here means we do not have to worry about iterating too 
     6107        # this case here means we do not have to worry about iterating too
    47666108        # many times later
    47676109        if coeffs[0].is_zero() and interval.contains_zero():
    47686110            return zero
     
    47706112        # interval_dp = poly_ring(dp)
    47716113        dcoeffs = [c.interval_fast(field) for c in dp.list()]
    47726114        interval_dp = poly_ring(dcoeffs)
    4773        
     6115
    47746116        linfo = {}
    47756117        uinfo = {}
    47766118
     
    48066148                # print interval_p
    48076149                # print linfo['endpoint'], linfo['value'], linfo['sign']
    48086150                # print uinfo['endpoint'], uinfo['value'], uinfo['sign']
    4809                 raise ValueError, "Refining interval that does not bound unique root!"
     6151                raise ValueError("Refining interval that does not bound unique root!")
    48106152
    48116153            # Use a simple algorithm:
    4812             # Try an interval Newton-Raphson step.  If this does not add at
     6154            # Try an interval Newton-Raphson step. If this does not add at
    48136155            # least one bit of information, or if it fails (because the
    48146156            # slope is not bounded away from zero), then try bisection.
    48156157            # If this fails because the value at the midpoint is not
     
    48916233                    # but the interval is no more than twice as wide as the
    48926234                    # narrowest possible.)
    48936235                    return interval
    4894        
     6236
    48956237    def _complex_refine_interval(self, interval, prec):
    48966238        r"""
    48976239        Takes an interval which is assumed to enclose exactly one root
     
    48996241        of the `k-1`-st derivative); and a precision, in bits.
    49006242
    49016243        Tries to find a narrow interval enclosing the root using
    4902         interval arithmetic of the given precision.  (No particular
     6244        interval arithmetic of the given precision. (No particular
    49036245        number of resulting bits of precision is guaranteed.)
    49046246
    4905         Uses Newton's method (adapted for interval arithmetic).  The
     6247        Uses Newton's method (adapted for interval arithmetic). The
    49066248        algorithm will converge very quickly if started with a
    4907         sufficiently narrow interval.  If Newton's method fails, then
     6249        sufficiently narrow interval. If Newton's method fails, then
    49086250        we falls back on computing all the roots of the polynomial
    49096251        numerically, and select the appropriate root.
    49106252
     
    49146256            sage: x = polygen(QQbar)
    49156257            sage: intv = CIF(RIF(0, 1), RIF(0.1, 1))
    49166258            sage: rt = ANRoot(x^5 - 1, intv)
    4917             sage: new_intv = rt.refine_interval(intv, 53); new_intv
     6259            sage: new_intv = rt.refine_interval(intv, 53); new_intv # indirect doctest
    49186260            0.3090169943749474241? + 0.951056516295153573?*I
    49196261            sage: rt.refine_interval(new_intv, 70)
    49206262            0.30901699437494742411? + 0.95105651629515357212?*I
     
    49446286        # This special case is important: this is the only way we could
    49456287        # refine "infinitely deep" (we could get an interval of diameter
    49466288        # about 2^{-2^31}, and then hit floating-point underflow); avoiding
    4947         # this case here means we do not have to worry about iterating too 
     6289        # this case here means we do not have to worry about iterating too
    49486290        # many times later
    49496291        if coeffs[0].is_zero() and zero in interval:
    49506292            return zero
     
    49526294        # interval_dp = poly_ring(dp)
    49536295        dcoeffs = [c.interval_fast(field) for c in dp.list()]
    49546296        interval_dp = poly_ring(dcoeffs)
    4955        
     6297
    49566298        while True:
    49576299            center = field(interval.center())
    49586300            val = interval_p(center)
     
    49726314                new_diam = interval.diameter()
    49736315
    49746316                if new_diam == 0:
    4975                     # Wow; we nailed it exactly.  (This may happen
     6317                    # Wow; we nailed it exactly. (This may happen
    49766318                    # whenever the root is exactly equal to some
    49776319                    # floating-point number, and cannot happen
    49786320                    # if the root is not equal to a floating-point
     
    49806322                    return interval
    49816323
    49826324                if new_diam == diam:
    4983                     # We're not getting any better.  There are two
    4984                     # possible reasons for this.  Either we have
     6325                    # We're not getting any better. There are two
     6326                    # possible reasons for this. Either we have
    49856327                    # refined as much as possible given the imprecision
    49866328                    # of our interval polynomial, and we have the best
    49876329                    # answer we're going to get at this precision;
     
    49926334
    49936335                    # I do not have a formal proof, but I believe the
    49946336                    # following test differentiates between these two
    4995                     # behaviors.  (If I'm wrong, we might get bad behavior
     6337                    # behaviors. (If I'm wrong, we might get bad behavior
    49966338                    # like infinite loops, but we still won't actually
    49976339                    # return a wrong answer.)
    49986340
     
    50056347                        return interval
    50066348
    50076349                    # The center of the current interval is known
    5008                     # not to be a root.  This should let us divide
     6350                    # not to be a root. This should let us divide
    50096351                    # the interval in half, and improve on our previous
    5010                     # estimates.  I can only think of two reasons why
     6352                    # estimates. I can only think of two reasons why
    50116353                    # it might not:
    50126354                    # 1) the "center" of the interval is actually
    50136355                    # on one of the edges of the interval (because the
     
    50326374                    # whether the diameter is less than pi/2; in that
    50336375                    # case, no matter the value of "val" (as long as
    50346376                    # "val" is fairly precise), "val / slope" should
    5035                     # be bounded away from zero.  But we compare
     6377                    # be bounded away from zero. But we compare
    50366378                    # against 1 instead, in the hopes that this might
    50376379                    # be slightly faster.
    50386380
     
    50466388        """
    50476389        Find a precise approximation to the unique root in interval,
    50486390        by finding a precise approximation to all roots of the
    5049         polynomial, and checking which one is in interval.  Slow but sure.
     6391        polynomial, and checking which one is in interval. Slow but sure.
    50506392
    50516393        EXAMPLES::
    50526394
     
    50666408            return our_root[0]
    50676409
    50686410        if len(our_root) == 0:
    5069             raise ValueError, "Complex root interval does not include any roots"
     6411            raise ValueError("Complex root interval does not include any roots")
    50706412
    50716413        # We have more than one root that overlap the current interval.
    50726414        # Technically, this might not be an error; perhaps the actual
     
    50766418        # But it seems far more likely that the provided interval is
    50776419        # just too big.
    50786420
    5079         raise ValueError, "Complex root interval probably includes multiple roots"
     6421        raise ValueError("Complex root interval probably includes multiple roots")
    50806422
    50816423    def exactify(self):
    50826424        """
     
    51156457            red_elt, red_back, red_pol = do_polred(my_factor)
    51166458
    51176459            field = NumberField(red_pol, 'a', check=False)
    5118            
     6460
    51196461            def intv_fn(rif):
    51206462                return conjugate_expand(red_elt(self._interval_fast(rif) * den))
    51216463            new_intv = conjugate_shrink(isolating_interval(intv_fn, red_pol))
    51226464            root = ANRoot(QQx(red_pol), new_intv)
    51236465            new_gen = AlgebraicGenerator(field, root)
    5124            
     6466
    51256467            return ANExtensionElement(new_gen, red_back(field.gen())/den)
    51266468        else:
    51276469            fld = gen.field()
     
    51516493
    51526494
    51536495            pari_nf = gen.pari_field()
    5154            
     6496
    51556497            # print pari_nf[0]
    51566498            x, y = QQxy.gens()
    51576499            my_factor = QQxy['z']([c.polynomial()(y) for c in my_factor])(x)
     
    51726514            red_elt, red_back, red_pol = do_polred(newpol_sage_y)
    51736515
    51746516            new_nf = NumberField(red_pol, name='a', check=False)
    5175            
     6517
    51766518            self_pol_sage = QQx(self_pol.lift())
    51776519
    51786520            new_nf_a = new_nf.gen()
    5179            
     6521
    51806522            def intv_fn(prec):
    51816523                return conjugate_expand(red_elt(gen._interval_fast(prec) * k + self._interval_fast(prec) * den))
    51826524            new_intv = conjugate_shrink(isolating_interval(intv_fn, red_pol))
     
    51866528            red_back_a = red_back(new_nf.gen())
    51876529            new_poly = ((QQx_x - k * self_pol_sage)(red_back_a)/den)
    51886530            return ANExtensionElement(new_gen, new_poly)
    5189        
     6531
    51906532    def _more_precision(self):
    51916533        """
    5192         Recompute the interval enclosing this root at higher
     6534        Recompute the interval enclosing this ``ANRoot`` object at higher
    51936535        precision.
     6536
     6537        EXAMPLE::
     6538
     6539            sage: x = polygen(QQ); y = (x^3 + x + 1).roots(AA,multiplicities=False)[0]
     6540            sage: z = y._descr
     6541            sage: z._interval.prec()
     6542            64
     6543            sage: z._more_precision()
     6544            sage: z._interval.prec()
     6545            128
    51946546        """
    51956547        prec = self._interval.prec()
    51966548        self._interval = self.refine_interval(self._interval, prec*2)
     
    51996551        """
    52006552        Given a RealIntervalField, compute the value of this number
    52016553        using interval arithmetic of at least the precision of the field,
    5202         and return the value in that field.  (More precision may be used
     6554        and return the value in that field. (More precision may be used
    52036555        in the computation.)
     6556
     6557        EXAMPLE::
     6558
     6559            sage: x = polygen(QQ); y = (x^3 + x + 1).roots(AA,multiplicities=False)[0]._descr
     6560            sage: y._interval_fast(128)
     6561            -0.68232780382801932736948373971104825689?
    52046562        """
    52056563        if prec == self._interval.prec():
    52066564            return self._interval
     
    52136571
    52146572_cyclotomic_gen_cache = {}
    52156573def cyclotomic_generator(n):
     6574    r"""
     6575    Return an :class:`AlgebraicGenerator` object corresponding to the generator
     6576    `e^{2 \pi I / n}` of the `n`-th cyclotomic field.
     6577
     6578    EXAMPLE::
     6579
     6580        sage: from sage.rings.qqbar import cyclotomic_generator
     6581        sage: g=cyclotomic_generator(7); g
     6582        1*e^(2*pi*I*1/7)
     6583        sage: type(g)
     6584        <class 'sage.rings.qqbar.AlgebraicGenerator'>
     6585    """
    52166586    try:
    52176587        return _cyclotomic_gen_cache[n]
    52186588    except KeyError:
     
    52286598class ANExtensionElement(ANDescr):
    52296599    r"""
    52306600    The subclass of ``ANDescr`` that represents a number field
    5231     element in terms of a specific generator.  Consists of a polynomial
     6601    element in terms of a specific generator. Consists of a polynomial
    52326602    with rational coefficients in terms of the generator, and the
    52336603    generator itself, an ``AlgebraicGenerator``.
    52346604    """
     
    52396609        except TypeError:
    52406610            if generator is QQbar_I_generator and value[0].is_zero():
    52416611                return ANRootOfUnity(QQ_1_4, value[1])
    5242             return ANDescr.__new__(self)           
     6612            return ANDescr.__new__(self)
    52436613
    52446614    def __init__(self, generator, value):
    52456615        self._generator = generator
     
    52616631            True
    52626632        """
    52636633        return (ANExtensionElement, (self._generator, self._value))
    5264    
     6634
    52656635    def _repr_(self):
    52666636        return '%s where %s = 0 and a in %s'%(self._value,
    52676637                                              self._generator.field().polynomial()._repr(name='a'),
     
    53176687        rt = sib(self._generator.root_as_algebraic())
    53186688        # For the best fidelity, we really ought to somehow ensure
    53196689        # that rt is exactified, but sage_input doesn't support that
    5320         # nicely.  Skip it for now.
     6690        # nicely. Skip it for now.
    53216691        # The following is copied with slight mods from polynomial_element.pyx
    53226692        coeffs = [sib(c, True) for c in self._value.list()]
    53236693        terms = []
     
    53346704        if result_is_qqbar != is_qqbar:
    53356705            v = sib.name('QQbar' if is_qqbar else 'AA')(v)
    53366706        return (v, True)
    5337        
     6707
    53386708    def kind(self):
     6709        r"""
     6710        Return a string describing what kind of element this is.
     6711
     6712        EXAMPLE::
     6713
     6714            sage: x = QQbar(sqrt(2) + sqrt(3))
     6715            sage: x.exactify()
     6716            sage: x._descr.kind()
     6717            'element'
     6718            sage: x = QQbar(I) + 1
     6719            sage: x.exactify()
     6720            sage: x._descr.kind()
     6721            'gaussian'
     6722        """
    53396723        if self._generator is QQbar_I_generator:
    53406724            return 'gaussian'
    53416725        else:
    53426726            return 'element'
    53436727
    53446728    def is_complex(self):
     6729        r"""
     6730        Return True if the number field that defines this element is not real.
     6731        This does not imply that the element itself is definitely non-real, as
     6732        in the example below.
     6733
     6734        EXAMPLE::
     6735
     6736            sage: rt2 = QQbar(sqrt(2))
     6737            sage: rtm3 = QQbar(sqrt(-3))
     6738            sage: x = rtm3 + rt2 - rtm3
     6739            sage: x.exactify()
     6740            sage: y = x._descr
     6741            sage: type(y)
     6742            <class 'sage.rings.qqbar.ANExtensionElement'>
     6743            sage: y.is_complex()
     6744            True
     6745            sage: x.imag() == 0
     6746            True
     6747        """
    53456748        return not self._exactly_real
    53466749
    53476750    def is_exact(self):
     6751        r"""
     6752        Return True, since ANExtensionElements are exact.
     6753
     6754        EXAMPLE::
     6755
     6756            sage: rt2 = QQbar(sqrt(2))
     6757            sage: rtm3 = QQbar(sqrt(-3))
     6758            sage: x = rtm3 + rt2 - rtm3
     6759            sage: x.exactify()
     6760            sage: y = x._descr
     6761            sage: type(y)
     6762            <class 'sage.rings.qqbar.ANExtensionElement'>
     6763            sage: y.is_exact()
     6764            True
     6765        """
    53486766        return True
    53496767
    53506768    def is_simple(self):
     
    53806798            return self._is_simple
    53816799
    53826800    def is_field_element(self):
     6801        r"""
     6802        Return True if self is an element of a number field (always true for ANExtensionElements)
     6803
     6804        EXAMPLE::
     6805
     6806            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6807            sage: v.is_field_element()
     6808            True
     6809        """
    53836810        return True
    53846811
    53856812    def generator(self):
     6813        r"""
     6814        Return the :class:`~AlgebraicGenerator` object corresponding to self.
     6815
     6816        EXAMPLE::
     6817
     6818            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6819            sage: v.generator()
     6820            Number Field in a with defining polynomial y^2 - y - 1 with a in 1.618033988749895?
     6821        """
    53866822        return self._generator
    53876823
    53886824    def exactify(self):
     6825        r"""
     6826        Return an exact representation of self. Since self is already exact,
     6827        just return self.
     6828
     6829        EXAMPLE::
     6830
     6831            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6832            sage: type(v)
     6833            <class 'sage.rings.qqbar.ANExtensionElement'>
     6834            sage: v.exactify() is v
     6835            True
     6836        """
    53896837        return self
    53906838
    53916839    def field_element_value(self):
     6840        r"""
     6841        Return the underlying number field element.
     6842
     6843        EXAMPLE::
     6844
     6845            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6846            sage: v.field_element_value()
     6847            a
     6848        """
    53926849        return self._value
    53936850
    53946851    def minpoly(self):
     
    53976854
    53986855        EXAMPLES::
    53996856
    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
     6857            sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify()
     6858            sage: type(v)
     6859            <class 'sage.rings.qqbar.ANExtensionElement'>
     6860            sage: v.minpoly()
     6861            x^2 - x - 1
    54066862        """
    54076863        try:
    54086864            return self._minpoly
     
    54356891        if self.is_simple():
    54366892            return self
    54376893
    5438         # This is very inefficient... 
     6894        # This is very inefficient...
    54396895        # for instance, the .exactify() call will try to factor poly,
    54406896        # even though we know that poly is irreducible
    54416897        poly = self.minpoly()
     
    54516907            return v.real()
    54526908        return v
    54536909
     6910    # for these three functions the argument n is not used (but it is there
     6911    # anyway for compatibility)
     6912
    54546913    def neg(self, n):
     6914        r"""
     6915        Negation of self.
     6916
     6917        EXAMPLE::
     6918
     6919            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     6920            sage: a.exactify()
     6921            sage: b = a._descr
     6922            sage: type(b)
     6923            <class 'sage.rings.qqbar.ANExtensionElement'>
     6924            sage: b.neg(a)
     6925            1/2*a^3 - a^2 + 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? - 0.7071067811865475?*I
     6926            sage: b.neg("ham spam and eggs")
     6927            1/2*a^3 - a^2 + 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? - 0.7071067811865475?*I
     6928        """
    54556929        return ANExtensionElement(self._generator, -self._value)
    54566930
    54576931    def invert(self, n):
     6932        r"""
     6933        1/self.
     6934
     6935        EXAMPLE::
     6936
     6937            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     6938            sage: a.exactify()
     6939            sage: b = a._descr
     6940            sage: type(b)
     6941            <class 'sage.rings.qqbar.ANExtensionElement'>
     6942            sage: b.invert(a)
     6943            -1/2*a^3 - a^2 + 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? - 0.7071067811865475?*I
     6944            sage: b.invert("ham spam and eggs")
     6945            -1/2*a^3 - a^2 + 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? - 0.7071067811865475?*I
     6946        """
    54586947        return ANExtensionElement(self._generator, ~self._value)
    54596948
    54606949    def conjugate(self, n):
     6950        r"""
     6951        Negation of self.
     6952
     6953        EXAMPLE::
     6954
     6955            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     6956            sage: a.exactify()
     6957            sage: b = a._descr
     6958            sage: type(b)
     6959            <class 'sage.rings.qqbar.ANExtensionElement'>
     6960            sage: b.conjugate(a)
     6961            -1/2*a^3 + a^2 - 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? + 0.7071067811865475?*I
     6962            sage: b.conjugate("ham spam and eggs")
     6963            -1/2*a^3 + a^2 - 1 where a^4 - 2*a^2 + 4 = 0 and a in -1.224744871391589? + 0.7071067811865475?*I
     6964        """
    54616965        if self._exactly_real:
    54626966            return self
    54636967        else:
    54646968            return ANExtensionElement(self._generator.conjugate(), self._value)
    54656969
     6970    # The rest of these unary operations do actually use n, which is an
     6971    # AlgebraicNumber pointing to self.
     6972
    54666973    def norm(self, n):
     6974        r"""
     6975        Norm of self (square of complex absolute value)
     6976
     6977        EXAMPLE::
     6978
     6979            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     6980            sage: a.exactify()
     6981            sage: b = a._descr
     6982            sage: type(b)
     6983            <class 'sage.rings.qqbar.ANExtensionElement'>
     6984            sage: b.norm(a)
     6985            <class 'sage.rings.qqbar.ANUnaryExpr'>
     6986        """
    54676987        if self._exactly_real:
    54686988            return (n*n)._descr
    54696989        elif self._generator is QQbar_I_generator:
     
    54726992            return ANUnaryExpr(n, 'norm')
    54736993
    54746994    def abs(self, n):
     6995        r"""
     6996        Return the absolute value of self (square root of the norm).
     6997
     6998        EXAMPLE::
     6999
     7000            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     7001            sage: a.exactify()
     7002            sage: b = a._descr
     7003            sage: type(b)
     7004            <class 'sage.rings.qqbar.ANExtensionElement'>
     7005            sage: b.abs(a)
     7006            Root 3.146264369941972342? of x^2 - 9.89897948556636?
     7007        """
    54757008        return AlgebraicReal(self.norm(n)).sqrt()._descr
    54767009
    54777010    def rational_argument(self, n):
    54787011        r"""
    5479         If the argument of self is `2\pi` times some rational number,
    5480         return that rational; otherwise, return None.
    5481         """
    5482 
     7012        If the argument of self is `2\pi` times some rational number in `[1/2,
     7013        -1/2)`, return that rational; otherwise, return ``None``.
     7014
     7015        EXAMPLE::
     7016
     7017            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(3))
     7018            sage: a.exactify()
     7019            sage: b = a._descr
     7020            sage: type(b)
     7021            <class 'sage.rings.qqbar.ANExtensionElement'>
     7022            sage: b.rational_argument(a) is None
     7023            True
     7024            sage: x = polygen(QQ)
     7025            sage: a = (x^4 + 1).roots(QQbar, multiplicities=False)[0]
     7026            sage: a.exactify()
     7027            sage: b = a._descr
     7028            sage: b.rational_argument(a)
     7029            -3/8
     7030        """
    54837031        # If the argument of self is 2*pi times some rational number a/b,
    54847032        # then self/abs(self) is a root of the b'th cyclotomic polynomial.
    54857033        # This implies that the algebraic degree of self is at least
    5486         # phi(b).  Working backward, we know that the algebraic degree
     7034        # phi(b). Working backward, we know that the algebraic degree
    54877035        # of self is at most the degree of the generator, so that gives
    5488         # an upper bound on phi(b).  According to
     7036        # an upper bound on phi(b). According to
    54897037        # http://mathworld.wolfram.com/TotientFunction.html,
    54907038        # phi(b) >= sqrt(b) for b > 6; this gives us an upper bound on b.
    54917039        # We then check to see if this is possible; if so, we test
     
    55157063        raise NotImplementedError
    55167064
    55177065    def gaussian_value(self):
     7066        r"""
     7067        Return self as an element of `\QQ(i)`.
     7068
     7069        EXAMPLE::
     7070
     7071            sage: a = QQbar(I) + 3/7
     7072            sage: a.exactify()
     7073            sage: b = a._descr
     7074            sage: type(b)
     7075            <class 'sage.rings.qqbar.ANExtensionElement'>
     7076            sage: b.gaussian_value()
     7077            I + 3/7
     7078
     7079        A non-example::
     7080
     7081            sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3))
     7082            sage: a.exactify()
     7083            sage: b = a._descr
     7084            sage: type(b)
     7085            <class 'sage.rings.qqbar.ANExtensionElement'>
     7086            sage: b.gaussian_value()
     7087            Traceback (most recent call last):
     7088            ...
     7089            AssertionError
     7090        """
    55187091        assert(self._generator is QQbar_I_generator)
    55197092        return self._value
    55207093
    55217094class ANUnaryExpr(ANDescr):
    55227095    def __init__(self, arg, op):
     7096        r"""
     7097        Initialize this ANUnaryExpr.
     7098
     7099        EXAMPLE::
     7100
     7101            sage: t = ~QQbar(sqrt(2)); type(t._descr) # indirect doctest
     7102            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7103        """
    55237104        self._arg = arg
    55247105        self._op = op
    55257106        self._complex = True
     
    56147195        return (v, True)
    56157196
    56167197    def kind(self):
     7198        r"""
     7199        Return a string describing what kind of element this is.
     7200
     7201        EXAMPLE::
     7202
     7203            sage: x = -QQbar(sqrt(2))
     7204            sage: y = x._descr
     7205            sage: type(y)
     7206            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7207            sage: y.kind()
     7208            'other'
     7209        """
    56177210        return 'other'
    56187211
    56197212    def is_complex(self):
     7213        r"""
     7214        Return whether or not this element is complex. Note that this is a data
     7215        type check, and triggers no computations -- if it returns False, the
     7216        element might still be real, it just doesn't know it yet.
     7217
     7218        EXAMPLE::
     7219
     7220            sage: t = AA(sqrt(2))
     7221            sage: s = (-t)._descr
     7222            sage: s
     7223            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7224            sage: s.is_complex()
     7225            False
     7226            sage: QQbar(-sqrt(2))._descr.is_complex()
     7227            True
     7228        """
    56207229        return self._complex
    56217230
    56227231    def _interval_fast(self, prec):
     7232        r"""
     7233        Calculate an approximation to this ``ANUnaryExpr`` object in an interval field of precision ``prec``.
     7234
     7235        EXAMPLE::
     7236
     7237            sage: t = AA(sqrt(2))
     7238            sage: s = (-t)._descr
     7239            sage: s
     7240            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7241            sage: s._interval_fast(150)
     7242            -1.414213562373095048801688724209698078569671876?
     7243        """
    56237244        op = self._op
    56247245
    56257246        v = self._arg._interval_fast(prec)
     
    56657286        raise NotImplementedError
    56667287
    56677288    def exactify(self):
     7289        r"""
     7290        Trigger exact computation of self.
     7291
     7292        EXAMPLE::
     7293
     7294            sage: v = (-QQbar(sqrt(2)))._descr
     7295            sage: type(v)
     7296            <class 'sage.rings.qqbar.ANUnaryExpr'>
     7297            sage: v.exactify()
     7298            -a where a^2 - 2 = 0 and a in 1.414213562373095?
     7299        """
    56687300        op = self._op
    56697301        arg = self._arg
    56707302
     
    57057337            vd = v._descr
    57067338            vd._exactly_real = True
    57077339            return vd
    5708            
     7340
    57097341        if op == 'norm':
    57107342            arg.exactify()
    57117343            v = arg * arg.conjugate()
     
    57207352
    57217353class ANBinaryExpr(ANDescr):
    57227354    def __init__(self, left, right, op):
     7355        r"""
     7356        Initialize this ANBinaryExpr.
     7357
     7358        EXAMPLE::
     7359
     7360            sage: t = QQbar(sqrt(2)) + QQbar(sqrt(3)); type(t._descr) # indirect doctest
     7361            <class 'sage.rings.qqbar.ANBinaryExpr'>
     7362        """
    57237363        self._left = left
    57247364        self._right = right
    57257365        self._op = op
     
    57957435        op = self._op
    57967436
    57977437        # 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
     7438        # QQbar(2)+QQbar.zeta(3). So we want to pass coerced=True to
    57997439        # an argument if it is rational (but if both arguments are
    58007440        # rational, we only want to set it for one of them).
    58017441
     
    58097449
    58107450        arg1_is_qqbar = arg1.parent() is QQbar
    58117451        arg2_is_qqbar = arg2.parent() is QQbar
    5812        
     7452
    58137453        result_is_qqbar = \
    58147454            (arg1_is_qqbar and not arg1_coerced) or \
    58157455            (arg2_is_qqbar and not arg2_coerced)
     
    58397479        return (v, True)
    58407480
    58417481    def kind(self):
     7482        r"""
     7483        Return a string describing what kind of element this is. Returns ``'other'``.
     7484
     7485        EXAMPLE::
     7486
     7487            sage: x = (QQbar(sqrt(2)) + QQbar(sqrt(5)))._descr
     7488            sage: type(x)
     7489            <class 'sage.rings.qqbar.ANBinaryExpr'>
     7490            sage: x.kind()
     7491            'other'
     7492        """
    58427493        return 'other'
    58437494
    58447495    def is_complex(self):
     7496        r"""
     7497        Whether this element is complex. Does not trigger exact computation, so
     7498        may return True even if the element is real.
     7499
     7500        EXAMPLE::
     7501
     7502            sage: x = (QQbar(sqrt(-2)) / QQbar(sqrt(-5)))._descr
     7503            sage: x.is_complex()
     7504            True
     7505        """
    58457506        return self._complex
    58467507
    58477508    def _interval_fast(self, prec):
     7509        r"""
     7510        Calculate an approximation to self in an interval field of precision prec.
     7511
     7512        EXAMPLE::
     7513
     7514            sage: x = (QQbar(sqrt(-2)) / QQbar(sqrt(-5)))._descr
     7515            sage: y= x._interval_fast(64); y
     7516            0.632455532033675867?
     7517            sage: y.parent()
     7518            Complex Interval Field with 64 bits of precision
     7519        """
    58487520        op = self._op
    58497521
    58507522        lv = self._left._interval_fast(prec)
     
    58737545
    58747546            sage: rt2c = QQbar.zeta(3) + AA(sqrt(2)) - QQbar.zeta(3)
    58757547            sage: rt2c.exactify()
    5876        
    5877         We check to make sure that this method still works even.  We
     7548
     7549        We check to make sure that this method still works even. We
    58787550        do this by increasing the recursion level at each step and
    58797551        decrease it before we return::
    58807552
     
    59247596#     # (Take every other coordinate to get the vertices of a
    59257597#     # heptadecagon.)
    59267598#     # Formulas from:
    5927 #     # Weisstein, Eric W. "Trigonometry Angles--Pi/17." From 
    5928 #     # MathWorld--A Wolfram Web Resource. 
    5929 #     # http://mathworld.wolfram.com/TrigonometryAnglesPi17.html 
     7599#     # Weisstein, Eric W. "Trigonometry Angles--Pi/17." From
     7600#     # MathWorld--A Wolfram Web Resource.
     7601#     # http://mathworld.wolfram.com/TrigonometryAnglesPi17.html
    59307602
    59317603#     rt17 = AA(17).sqrt()
    59327604#     rt2 = AA(2).sqrt()
     
    59537625#     # (Take every other coordinate to get the vertices of a
    59547626#     # heptadecagon.)
    59557627#     # Formulas from:
    5956 #     # Weisstein, Eric W. "Heptadecagon." From MathWorld--A Wolfram 
    5957 #     # Web Resource. http://mathworld.wolfram.com/Heptadecagon.html 
     7628#     # Weisstein, Eric W. "Heptadecagon." From MathWorld--A Wolfram
     7629#     # Web Resource. http://mathworld.wolfram.com/Heptadecagon.html
    59587630
    59597631#     x = AA.polynomial_root(256*ax**8 - 128*ax**7 - 448*ax**6 + 192*ax**5 + 240*ax**4 - 80*ax**3 - 40*ax**2 + 8*ax + 1, RIF(0.9829, 0.983))
    59607632#     y = (1-x**2).sqrt()
     
    59667638#     print cx.sign(), cy.sign()
    59677639#     print (cx-1).sign()
    59687640#     return x, y
    5969 # # heptadecagon2()   
     7641# # heptadecagon2()
    59707642
    59717643def _init_qqbar():
    59727644    """
    5973     This code indirectly uses a huge amount of sage, despite the fact
    5974     that qqbar is imported rather early on in the sage loading. This function
    5975     is called at the end of sage.all.
     7645    This code indirectly uses a huge amount of sage, despite the fact
     7646    that qqbar is imported rather early on in the sage loading. This function
     7647    is called at the end of sage.all.
     7648
     7649    EXAMPLE::
     7650
     7651        sage: sage.rings.qqbar.QQbar_I_generator # indirect doctest
     7652        Number Field in I with defining polynomial x^2 + 1 with a in 1*I
    59767653    """
    59777654    global ZZX_x, AA_0, QQbar_I, AA_hash_offset, QQbar_hash_offset, QQbar_I_generator, QQbar_I_nf
    59787655    global QQ_0, QQ_1, QQ_1_2, QQ_1_4, RR_1_10
    5979    
     7656
    59807657    RR_1_10 = RR(1)/10
    59817658    QQ_0 = QQ(0)
    59827659    QQ_1 = QQ(1)
     
    60037680AA_golden_ratio = None
    60047681
    60057682def get_AA_golden_ratio():
     7683    r"""
     7684    Return the golden ratio as an element of the algebraic real field. Used by
     7685    :meth:`sage.symbolic.constants.golden_ratio._algebraic_`.
     7686
     7687    EXAMPLE::
     7688
     7689        sage: AA(golden_ratio) # indirect doctest
     7690        1.618033988749895?
     7691    """
    60067692    global AA_golden_ratio
    60077693    if AA_golden_ratio is None:
    60087694        AA_golden_ratio_nf = NumberField(ZZX_x**2 - ZZX_x - 1, 'phi')