Ticket #12662: trac_12662qqbardoctestv2.patch
File trac_12662qqbardoctestv2.patch, 142.4 KB (added by , 9 years ago) 


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 9 9 This is an implementation of the algebraic numbers (the complex 10 10 numbers which are the zero of a polynomial in `\ZZ[x]`; in other 11 11 words, the algebraic closure of `\QQ`, with an embedding into `\CC`). 12 All computations are exact. 12 All computations are exact. We also include an implementation of the 13 13 algebraic reals (the intersection of the algebraic numbers with 14 `\RR`). 14 `\RR`). The field of algebraic numbers `\QQbar` is available with 15 15 abbreviation ``QQbar``; the field of algebraic reals has abbreviation 16 16 ``AA``. 17 17 … … 30 30 31 31  the sum, difference, product, or quotient of algebraic numbers 32 32 33  the negation, inverse, absolute value, norm, real part, 33  the negation, inverse, absolute value, norm, real part, 34 34 imaginary part, or complex conjugate of an algebraic number 35 35 36 36  a particular root of a polynomial, given as a polynomial with … … 46 46 The multiplicative subgroup of the algebraic numbers generated 47 47 by the rational numbers and the roots of unity is handled particularly 48 48 efficiently, as long as these roots of unity come from the ``QQbar.zeta()`` 49 method. 49 method. Cyclotomic fields in general are fairly efficient, again 50 50 as long as they are derived from ``QQbar.zeta()``. 51 51 52 52 An algebraic number can be coerced into ``ComplexIntervalField`` (or 53 53 ``RealIntervalField``, for algebraic reals); every algebraic number has a 54 54 cached interval of the highest precision yet calculated. 55 55 56 Everything is done with intervals except for comparisons. 56 Everything is done with intervals except for comparisons. By default, 57 57 comparisons compute the two algebraic numbers with 128bit precision 58 58 intervals; if this does not suffice to prove that the numbers are different, 59 59 then we fall back on exact computation. … … 81 81 For a monic cubic polynomial `x^3 + bx^2 + cx + d` with roots `s1`, 82 82 `s2`, `s3`, the discriminant is defined as 83 83 `(s1s2)^2(s1s3)^2(s2s3)^2` and can be computed as `b^2c^2  4b^3d  84 4c^3 + 18bcd  27d^2`. 84 4c^3 + 18bcd  27d^2`. We can test that these definitions do give the 85 85 same result:: 86 86 87 87 sage: def disc1(b, c, d): … … 153 153 sage: QQbar(1)^(1/3) 154 154 0.500000000000000? + 0.866025403784439?*I 155 155 156 We can explicitly coerce from `\QQ[I]`. 156 We can explicitly coerce from `\QQ[I]`. (Technically, this is not quite 157 157 kosher, 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`. 158 whether the field generator is supposed to map to `+I` or `I`. We assume 159 159 that for any quadratic field with polynomial `x^2+1`, the generator maps 160 160 to `+I`.):: 161 161 … … 207 207 sage: a 208 208 1.000000000000000? 209 209 sage: a == 1 210 True 210 True 211 211 212 212 Algebraic numbers which are known to be rational print as rationals; 213 213 otherwise they print as intervals (with 53bit precision):: … … 252 252 sage: r.abs() == 2 253 253 True 254 254 sage: r.norm() == 4 255 True 255 True 256 256 sage: (r+I).norm().minpoly() 257 257 x^2  10*x + 13 258 258 sage: r = AA.polynomial_root(x^2  x  1, RIF(1, 0)); r … … 286 286 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 287 287 288 288 The paper "ARPREC: An Arbitrary Precision Computation Package" by 289 Bailey, Yozo, Li and Thompson discusses this result. 289 Bailey, Yozo, Li and Thompson discusses this result. Evidently it is 290 290 difficult to find, but we can easily verify it. :: 291 291 292 292 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)) … … 308 308 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? 309 309 310 310 Given an algebraic number, we can produce a string that will reproduce 311 that algebraic number if you type the string into Sage. 311 that algebraic number if you type the string into Sage. We can see 312 312 that until exact computation is triggered, an algebraic number keeps 313 313 track of the computation steps used to produce that number:: 314 314 … … 341 341 sage: sage_input(z3_3 * z4_4 * z5_5) 342 342 60*QQbar.zeta(60)^17 343 343 344 Note that the ``verify=True`` argument to ``sage_input`` will always trigger 344 Note that the ``verify=True`` argument to ``sage_input`` will always trigger 345 345 exact computation, so running ``sage_input`` twice in a row on the same number 346 will actually give different answers. 347 on ``n`` will also trigger exact computation on ``rt2``, as you can see by the 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 348 348 fact that the third output is different than the first:: 349 349 350 350 sage: rt2 = AA(sqrt(2)) … … 416 416 True 417 417 418 418 sage: t.exactify(); type(t._descr) 419 <class 'sage.rings.qqbar.ANExtensionElement'> 419 <class 'sage.rings.qqbar.ANExtensionElement'> 420 420 sage: loads(dumps(t)) == QQbar(sqrt(2)) 421 421 True 422 422 … … 424 424 <class 'sage.rings.qqbar.ANUnaryExpr'> 425 425 sage: loads(dumps(t)) == 1/QQbar(sqrt(2)) 426 426 True 427 427 428 428 sage: t = QQbar(sqrt(2)) + QQbar(sqrt(3)); type(t._descr) 429 429 <class 'sage.rings.qqbar.ANBinaryExpr'> 430 430 sage: loads(dumps(t)) == QQbar(sqrt(2)) + QQbar(sqrt(3)) … … 432 432 433 433 We can convert elements of ``QQbar`` and ``AA`` into the following 434 434 types: ``float``, ``complex``, ``RDF``, ``CDF``, ``RR``, ``CC``, 435 ``RIF``, ``CIF``, ``ZZ``, and ``QQ``, with a few exceptions. 435 ``RIF``, ``CIF``, ``ZZ``, and ``QQ``, with a few exceptions. (For the 436 436 arbitraryprecision types, ``RR``, ``CC``, ``RIF``, and ``CIF``, it 437 437 can convert into a field of arbitrary precision.) 438 438 439 439 Converting from ``QQbar`` to a real type (``float``, ``RDF``, ``RR``, 440 440 ``RIF``, ``ZZ``, or ``QQ``) succeeds only if the ``QQbar`` is actually 441 real (has an imaginary component of exactly zero). 441 real (has an imaginary component of exactly zero). Converting from 442 442 either ``AA`` or ``QQbar`` to ``ZZ`` or ``QQ`` succeeds only if the 443 number actually is an integer or rational. 443 number actually is an integer or rational. If conversion fails, a 444 444 ValueError will be raised. 445 445 446 446 Here are examples of all of these conversions:: … … 476 476 477 477 TESTS: 478 478 479 Verify that trac 10981is fixed::479 Verify that :trac:`10981` is fixed:: 480 480 481 481 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() 484 484 (0, [(0.3535533905932738?*x + 1/2)/(x^2  1.414213562373095?*x + 1), (0.3535533905932738?*x + 1/2)/(x^2 + 1.414213562373095?*x + 1)]) 485 485 """ 486 486 … … 525 525 526 526 is_SymbolicExpressionRing = None 527 527 528 def late_import(): 528 def _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 """ 529 539 global is_SymbolicExpressionRing 530 540 if is_SymbolicExpressionRing is None: 531 541 import sage.symbolic.ring 532 542 is_SymbolicExpressionRing = sage.symbolic.ring.is_SymbolicExpressionRing 533 543 534 544 class AlgebraicField_common(sage.rings.ring.Field): 545 r""" 546 Common base class for the classes :class:`~AlgebraicRealField` and 547 :class:`~AlgebraicField`. 548 """ 549 535 550 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 536 560 return 64 537 561 538 562 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 """ 539 572 return False 540 573 541 574 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 """ 542 584 return sage.rings.integer.Integer(0) 543 585 544 586 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 """ 545 596 return infinity.infinity 546 597 547 598 def common_polynomial(self, poly): 548 599 """ 549 600 Given a polynomial with algebraic coefficients, returns a 550 601 wrapper that caches highprecision calculations and 551 factorizations. 602 factorizations. This wrapper can be passed to polynomial_root 552 603 in place of the polynomial. 553 604 554 605 Using ``common_polynomial`` makes no semantic difference, but will … … 574 625 0.?e18 + 2.236067977499790?*I 575 626 sage: b = QQbar.polynomial_root(p, RIF(1, 2)); b 576 627 1.732050807568878? 577 628 578 629 These "common polynomials" can be shared between real and 579 630 complex roots:: 580 631 … … 589 640 class AlgebraicRealField(_uniq_alg_r, AlgebraicField_common): 590 641 r""" 591 642 The field of algebraic reals. 643 644 TESTS:: 645 646 sage: AA == loads(dumps(AA)) 647 True 592 648 """ 593 649 594 650 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 """ 595 661 AlgebraicField_common.__init__(self, self, ('x',), normalize=False) 596 662 597 663 def _element_constructor_(self, x): 598 664 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 """ 603 683 if isinstance(x, AlgebraicReal): 604 684 return x 605 685 elif isinstance(x, AlgebraicNumber): 606 686 if x.imag().is_zero(): 607 687 return x.real() 608 688 else: 609 raise ValueError , "Cannot coerce algebraic number with nonzero imaginary part to algebraic real"689 raise ValueError("Cannot coerce algebraic number with nonzero imaginary part to algebraic real") 610 690 elif hasattr(x, '_algebraic_'): 611 691 return x._algebraic_(AA) 612 692 return AlgebraicReal(x) 613 693 614 694 def _repr_(self): 695 r""" 696 String representation of self. 697 698 EXAMPLE:: 699 700 sage: AA._repr_() 701 'Algebraic Real Field' 702 """ 615 703 return "Algebraic Real Field" 616 704 617 705 # Is there a standard representation for this? 618 706 def _latex_(self): 707 r""" 708 Latex representation of self. 709 710 EXAMPLE:: 711 712 sage: AA._latex_() 713 '\\mathbf{A}' 714 """ 619 715 return "\\mathbf{A}" 620 716 621 717 def _sage_input_(self, sib, coerce): … … 639 735 640 736 TESTS:: 641 737 642 sage: AA.has_coerce_map_from(ZZ) 738 sage: AA.has_coerce_map_from(ZZ) # indirect doctest 643 739 True 644 740 sage: K.<a> = QuadraticField(7, embedding=AA(7).sqrt()); AA.has_coerce_map_from(K) 645 741 True … … 655 751 return False 656 752 657 753 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 659 765 EXAMPLES:: 660 766 661 767 sage: AA.completion(infinity, 500) … … 674 780 return create_RealField(prec, **extras) 675 781 else: 676 782 raise NotImplementedError 677 783 678 784 def algebraic_closure(self): 679 785 """ 786 Return the algebraic closure of this field, which is the field 787 `\overline{\QQ}` of algebraic numbers. 788 680 789 EXAMPLES:: 681 790 682 791 sage: AA.algebraic_closure() … … 685 794 return QQbar 686 795 687 796 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 """ 688 810 try: 689 811 return im_gens[0] == codomain._coerce_(self.gen(0)) 690 812 except TypeError: 691 813 return False 692 814 693 815 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 """ 694 825 return (self(1), ) 695 826 696 827 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 """ 697 840 if n == 0: 698 841 return self(1) 699 842 else: 700 843 raise IndexError, "n must be 0" 701 844 702 845 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 """ 703 854 return 1 704 855 705 856 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 """ 706 866 return True 707 867 708 868 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 nth 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 nth root of unity in algebraic reals 898 """ 709 899 if n == 1: 710 900 return self(1) 711 901 elif n == 2: 712 902 return self(1) 713 903 else: 714 raise ValueError , "no nth root of unity in algebraic reals"904 raise ValueError("no nth root of unity in algebraic reals") 715 905 716 906 def polynomial_root(self, poly, interval, multiplicity=1): 717 907 r""" … … 721 911 722 912 The polynomial need not be irreducible, or even squarefree; but 723 913 if the given root is a multiple root, its multiplicity must be 724 specified. 914 specified. (IMPORTANT NOTE: Currently, multiplicity`k` roots 725 915 are handled by taking the `(k1)`st derivative of the polynomial. 726 916 This means that the interval must enclose exactly one root 727 917 of this derivative.) … … 764 954 2.000000000000000? 765 955 """ 766 956 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") 768 958 769 959 return AlgebraicReal(ANRoot(poly, interval, multiplicity)) 770 960 771 961 def 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 """ 772 971 return isinstance(F, AlgebraicRealField) 773 972 973 # Create the globally unique AlgebraicRealField object. 774 974 AA = AlgebraicRealField() 775 975 776 976 class AlgebraicField(_uniq_alg, AlgebraicField_common): 777 977 """ 778 The field of al gebraicnumbers.978 The field of all algebraic complex numbers. 779 979 """ 780 980 781 981 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 """ 782 992 AlgebraicField_common.__init__(self, AA, ('I',), normalize=False) 783 993 784 994 def _element_constructor_(self, x): 785 995 """ 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 """ 790 1007 if isinstance(x, AlgebraicNumber): 791 1008 return x 792 1009 elif isinstance(x, AlgebraicReal): … … 796 1013 return AlgebraicNumber(x) 797 1014 798 1015 def _repr_(self): 1016 r""" 1017 String representation of self. 1018 1019 EXAMPLE:: 1020 1021 sage: QQbar._repr_() 1022 'Algebraic Field' 1023 """ 799 1024 return "Algebraic Field" 800 1025 801 1026 def _latex_(self): 1027 r""" 1028 Latex representation of self. 1029 1030 EXAMPLE:: 1031 1032 sage: QQbar._latex_() 1033 '\\overline{\\QQ}' 1034 """ 802 1035 return "\\overline{\\QQ}" 803 1036 804 1037 def _sage_input_(self, sib, coerce): … … 817 1050 return sib.name('QQbar') 818 1051 819 1052 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 """ 820 1065 if from_par == ZZ or from_par == QQ or from_par == int or from_par == long: 821 1066 return True 822 1067 if from_par == AA or from_par == QQbar: 823 1068 return True 824 late_import()1069 _late_import() 825 1070 if is_SymbolicExpressionRing(from_par): 826 1071 return True 827 1072 return False 828 1073 829 1074 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 831 1086 EXAMPLES:: 832 1087 833 1088 sage: QQbar.completion(infinity, 500) … … 846 1101 return create_RealField(prec, **extras).complex_field() 847 1102 else: 848 1103 raise NotImplementedError 849 1104 850 1105 def algebraic_closure(self): 851 1106 """ 1107 Return the algebraic closure of this field. As this field is already 1108 algebraically closed, just returns self. 1109 852 1110 EXAMPLES:: 853 1111 854 1112 sage: QQbar.algebraic_closure() 855 1113 Algebraic Field 856 1114 """ 857 1115 return self 858 1116 859 1117 def construction(self): 860 1118 """ 1119 Return a functor that constructs self (used by the coercion machinery). 1120 861 1121 EXAMPLE:: 862 1122 863 1123 sage: QQbar.construction() … … 868 1128 return (AlgebraicClosureFunctor(), QQ) 869 1129 870 1130 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 """ 871 1140 return(QQbar_I, ) 872 1141 873 1142 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 """ 874 1155 if n == 0: 875 1156 return QQbar_I 876 1157 else: 877 raise IndexError , "n must be 0"1158 raise IndexError("n must be 0") 878 1159 879 1160 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 """ 880 1169 return 1 881 1170 882 1171 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 """ 883 1180 return False 884 1181 885 1182 def zeta(self, n=4): 886 1183 r""" 887 1184 Returns a primitive `n`'th root of unity, specifically `\exp(2*\pi*i/n)`. 888 1185 1186 INPUT: 1187 1188  ``n`` (integer)  default 4 1189 889 1190 EXAMPLES:: 890 1191 891 1192 sage: QQbar.zeta(1) … … 913 1214 914 1215 The polynomial need not be irreducible, or even squarefree; but 915 1216 if the given root is a multiple root, its multiplicity must be 916 specified. 1217 specified. (IMPORTANT NOTE: Currently, multiplicity`k` roots 917 1218 are handled by taking the `(k1)`st derivative of the polynomial. 918 1219 This means that the interval must enclose exactly one root 919 1220 of this derivative.) … … 949 1250 def random_element(self, poly_degree=2, *args, **kwds): 950 1251 r""" 951 1252 Returns a random algebraic number. 952 1253 953 1254 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 971 1269 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 976 1274 ALGORITHM: 977 1275 978 1276 A polynomial with degree between 1 and ``poly_degree``, 979 with random integer coefficients is created. 980 polynomial is chosen at random. 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 984 1282 EXAMPLES:: 985 1283 986 1284 sage: a = QQbar.random_element() 987 1285 sage: a # random 988 1286 0.2626138748742799? + 0.8769062830975992?*I 989 1287 sage: a in QQbar 990 1288 True 991 1289 992 1290 sage: b = QQbar.random_element(poly_degree=20) 993 1291 sage: b # random 994 1292 0.8642649077479498?  0.5995098147478391?*I 995 1293 sage: b in QQbar 996 1294 True 997 1295 998 1296 Parameters for the distribution of the integer coefficients 999 1297 of the polynomials can be passed on to the random element method 1000 for integers. 1298 for integers. For example, current default behavior of this method 1001 1299 returns zero about 15% of the time; if we do not include zero as a 1002 1300 possible coefficient, there will never be a zero constant term, and 1003 1301 thus never a zero root. :: 1004 1302 1005 1303 sage: z = [QQbar.random_element(x=1, y=10) for _ in range(20)] 1006 1304 sage: QQbar(0) in z 1007 1305 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. 1010 1308 Using an odd degree for the polynomials will insure some degree of 1011 success. 1012 1309 success. :: 1310 1013 1311 sage: r = [] 1014 1312 sage: while len(r) < 3: 1015 1313 ... x = QQbar.random_element(poly_degree=3) … … 1017 1315 ... r.append(x) 1018 1316 sage: (len(r) == 3) and all([z in AA for z in r]) 1019 1317 True 1020 1318 1021 1319 TESTS: 1022 1320 1023 1321 sage: QQbar.random_element('junk') 1024 1322 Traceback (most recent call last): 1025 1323 ... … … 1028 1326 Traceback (most recent call last): 1029 1327 ... 1030 1328 ValueError: polynomial degree must be greater than zero, not 0 1031 1329 1032 1330 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 1035 1333 sage: v = random_vector(QQbar, degree=2, poly_degree=3) 1036 1334 sage: v # random 1037 1335 (0.4694381338921299?, 0.500000000000000? + 0.866025403784439?*I) … … 1051 1349 # degree zero polynomials have no roots 1052 1350 # totally zero poly has degree 1 1053 1351 # add a random leading term 1054 if p.degree() < 1: 1352 if p.degree() < 1: 1055 1353 g = R.gen(0) 1056 1354 m = sage.misc.prandom.randint(1, poly_degree) 1057 1355 p = p + g**m 1058 1356 roots = p.roots(ring=QQbar, multiplicities=False) 1059 1357 1060 1358 # p will have at least one root; pick one at random 1061 1359 # could we instead just compute one root "randomly"? 1062 1360 m = sage.misc.prandom.randint(0, len(roots)1) 1063 1361 return roots[m] 1064 1362 1065 1363 def 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 """ 1066 1373 return isinstance(F, AlgebraicField) 1067 1374 1375 # Create the globally unique AlgebraicField object. 1068 1376 QQbar = AlgebraicField() 1069 1377 1070 1378 def 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 """ 1071 1388 return isinstance(F, AlgebraicField_common) 1072 1389 1073 1390 def 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 """ 1074 1403 # XXX Should do some testing to see where the efficiency breaks are 1075 # in MPFR. 1404 # in MPFR. We could also test variants like "bits = bits + bits // 2" 1076 1405 # (I think this is what MPFR uses internally). 1077 1406 bits = 64 1078 1407 while True: … … 1080 1409 bits = bits * 2 1081 1410 1082 1411 _short_prec_seq = (64, 128, None) 1083 def short_prec_seq(): return _short_prec_seq 1412 def short_prec_seq(): 1413 r""" 1414 Return a sequence of precisions to try in cases when an infiniteprecision 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 1084 1425 1085 1426 def 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 """ 1086 1437 bits = 256 1087 1438 while True: 1088 1439 yield bits … … 1090 1441 1091 1442 def rational_exact_root(r, d): 1092 1443 r""" 1093 Checks whether the rational `r` is an exact `d`'th power. 1444 Checks whether the rational `r` is an exact `d`'th power. If so, returns 1094 1445 the `d`'th root of `r`; otherwise, returns None. 1095 1446 1096 1447 EXAMPLES:: … … 1113 1464 def clear_denominators(poly): 1114 1465 """ 1115 1466 Takes a monic polynomial and rescales the variable to get a monic 1116 polynomial with "integral" coefficients. 1467 polynomial with "integral" coefficients. Works on any univariate 1117 1468 polynomial whose base ring has a ``denominator()`` method that returns 1118 1469 integers; for example, the base ring might be `\QQ` or a number 1119 1470 field. … … 1164 1515 return change, poly 1165 1516 1166 1517 def 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. 1175 1530 1176 1531 EXAMPLES:: 1177 1532 … … 1192 1547 1193 1548 best = None 1194 1549 best_discr = None 1195 1550 1196 1551 for i in range(red_table.nrows()): 1197 1552 red_poly = red_table[i,1] 1198 1553 if red_poly.poldegree() < degree: … … 1245 1600 ifld = intv.parent() 1246 1601 1247 1602 # We need to verify that pol has exactly one root in the 1248 # interval intv. 1603 # interval intv. We know (because it is a precondition of 1249 1604 # calling this function) that it has at least one root in the 1250 1605 # interval, so we only need to verify that it has at most one 1251 1606 # root (that the interval is sufficiently narrow). 1252 1607 1253 1608 # We do this by computing the derivative of the polynomial 1254 # over the interval. 1609 # over the interval. If the derivative is bounded away from zero, 1255 1610 # then we know there can be at most one root. 1256 1611 1257 1612 if not dpol(intv).contains_zero(): … … 1259 1614 1260 1615 def find_zero_result(fn, l): 1261 1616 """ 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``. 1267 1621 1268 1622 EXAMPLES:: 1269 1623 … … 1296 1650 r""" 1297 1651 If the interval ``v`` (which may be real or complex) includes some 1298 1652 purely real numbers, return ``v'`` containing ``v`` such that 1299 ``v' == v'.conjugate()``. Otherwise return ``v`` unchanged.(Note that if1653 ``v' == v'.conjugate()``. Otherwise return ``v`` unchanged. (Note that if 1300 1654 ``v' == v'.conjugate()``, and ``v'`` includes one nonreal root of a real 1301 1655 polynomial, then ``v'`` also includes the conjugate of that root. 1302 1656 Also note that the diameter of the return value is at most twice … … 1326 1680 def conjugate_shrink(v): 1327 1681 r""" 1328 1682 If the interval ``v`` includes some purely real numbers, return 1329 a real interval containing only those real numbers. 1683 a real interval containing only those real numbers. Otherwise 1330 1684 return ``v`` unchanged. 1331 1685 1332 1686 If ``v`` includes exactly one root of a real polynomial, and ``v`` was … … 1354 1708 return v 1355 1709 1356 1710 def number_field_elements_from_algebraics(numbers, minimal=False): 1357 r""" 1711 r""" 1358 1712 Given a sequence of elements of either ``AA`` or ``QQbar`` 1359 1713 (or a mixture), computes a number field containing all of these 1360 1714 elements, these elements as members of that number field, and a … … 1383 1737 sage: rts = p.roots(ring=QQbar, multiplicities=False) 1384 1738 sage: splitting = number_field_elements_from_algebraics(rts)[0]; splitting 1385 1739 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) 1387 1741 [(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)] 1388 1742 1389 1743 sage: rt2 = AA(sqrt(2)); rt2 … … 1436 1790 To: Algebraic Real Field 1437 1791 Defn: 1 > 1) 1438 1792 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 1440 1794 coerced into ``QQbar``:: 1441 1795 1442 1796 sage: number_field_elements_from_algebraics((sqrt(7), sqrt(9), sqrt(11))) … … 1487 1841 To: Algebraic Field 1488 1842 Defn: a > 0.7071067811865475? + 0.7071067811865475?*I) 1489 1843 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 1491 1845 the number is real, we get a homomorphism to ``QQbar``; but with 1492 ``minimal=True``, we get a homomorphism to ``AA``. 1846 ``minimal=True``, we get a homomorphism to ``AA``. Also note 1493 1847 that the exact answer depends on a Pari function that gives 1494 1848 different answers for 32bit and 64bit machines:: 1495 1849 … … 1535 1889 nums = nums[0] 1536 1890 1537 1891 hom = fld.hom([gen.root_as_algebraic()]) 1538 1892 1539 1893 return (fld, nums, hom) 1540 1894 1541 1895 # Cache some commonlyused polynomial rings … … 1549 1903 1550 1904 class AlgebraicGeneratorRelation(SageObject): 1551 1905 """ 1552 A simple class for maintaining relations in the lattice of algebraic 1906 A simple class for maintaining relations in the lattice of algebraic 1553 1907 extensions. 1554 1908 """ 1555 1909 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 """ 1556 1918 self.child1 = child1 1557 1919 self.child1_poly = child1_poly 1558 1920 self.child2 = child2 … … 1564 1926 class AlgebraicGenerator(SageObject): 1565 1927 r""" 1566 1928 An ``AlgebraicGenerator`` represents both an algebraic number `\alpha` and 1567 the number field `\QQ[\alpha]`. 1929 the number field `\QQ[\alpha]`. There is a single ``AlgebraicGenerator`` 1568 1930 representing `\QQ` (with `\alpha=0`). 1569 1931 1570 1932 The ``AlgebraicGenerator`` class is private, and should not be used … … 1595 1957 True 1596 1958 sage: nf = NumberField(y^2 + 1, name='a', check=False) 1597 1959 sage: root = ANRoot(x^2 + 1, CIF(0, 1)) 1598 sage: x = AlgebraicGenerator(nf, root); x 1960 sage: x = AlgebraicGenerator(nf, root); x 1599 1961 Number Field in a with defining polynomial y^2 + 1 with a in 1*I 1600 1962 """ 1601 1963 self._field = field … … 1625 1987 return (AlgebraicGenerator, (self._field, self._root)) 1626 1988 1627 1989 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 """ 1628 2005 return self._index 1629 2006 1630 2007 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 """ 1631 2022 return cmp(self._index, other._index) 1632 2023 1633 2024 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 """ 1634 2034 self._cyclotomic = True 1635 2035 self._cyclotomic_order = ZZ(n) 1636 2036 1637 2037 def is_complex(self): 2038 r""" 2039 Return True if this is a generator for a nonreal 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 """ 1638 2048 return self._root.is_complex() 1639 2049 1640 2050 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 """ 1641 2072 if self._trivial: 1642 2073 return 'Trivial generator' 1643 2074 else: … … 1647 2078 return '%s with a in %s'%(self._field, self._root._interval_fast(53)) 1648 2079 1649 2080 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 """ 1650 2091 return self._root_as_algebraic 1651 2092 1652 2093 def is_trivial(self): … … 1663 2104 return self._trivial 1664 2105 1665 2106 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 """ 1666 2118 return self._field 1667 2119 1668 2120 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") 1669 2143 if self._pari_field is None: 1670 2144 pari_pol = self._field.pari_polynomial("y") 1671 2145 self._pari_field = pari_pol.nfinit(1) … … 1675 2149 r""" 1676 2150 If this generator is for the algebraic number `\alpha`, return a 1677 2151 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 1678 2163 """ 1679 2164 try: 1680 2165 return self._conjugate … … 1696 2181 """ 1697 2182 Returns an interval containing this generator, to the specified 1698 2183 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 1699 2190 """ 1700 2191 return self._root._interval_fast(prec) 1701 2192 … … 1793 2284 red_back_x = QQx(red_back) 1794 2285 1795 2286 new_nf = NumberField(red_pol, name='a', check=False) 1796 2287 1797 2288 self_pol_sage = QQx(self_pol.lift()) 1798 2289 1799 2290 new_nf_a = new_nf.gen() … … 1809 2300 self._unions[other] = rel 1810 2301 other._unions[self] = rel 1811 2302 return new_gen 1812 2303 1813 2304 def super_poly(self, super, checked=None): 1814 2305 r""" 1815 2306 Given a generator ``gen`` and another generator ``super``, where ``super`` … … 1843 2334 a^3 + 3*a 1844 2335 sage: gen3.super_poly(gen2_3) 1845 2336 a^2 + 2 1846 2337 1847 2338 """ 1848 2339 if checked is None: 1849 2340 checked = {} … … 1869 2360 """ 1870 2361 Takes an algebraic number which is represented as either a 1871 2362 rational or a number field element, and which is in a subfield 1872 of the field generated by this generator. 2363 of the field generated by this generator. Lifts the number 1873 2364 into the field of this generator, and returns either a 1874 2365 ``Rational`` or a ``NumberFieldElement`` depending on whether 1875 2366 this is the trivial generator. … … 1899 2390 sage: gen2_3(ANRational(1/7)) 1900 2391 1/7 1901 2392 sage: gen2_3(sqrt3) 1902 a^2 + 2 2393 a^2 + 2 1903 2394 """ 1904 2395 if self._trivial: 1905 2396 return elt.rational_value() … … 1917 2408 return self._field(elt.field_element_value().polynomial()(sp)) 1918 2409 1919 2410 # These are the functions used to add, subtract, multiply, and divide 1920 # algebraic numbers. 2411 # algebraic numbers. Basically, we try to compute exactly if the 1921 2412 # result would be a Gaussian rational, or a rational times a root 1922 2413 # of unity; or if both arguments are already known to be in the same 1923 # number field. 2414 # number field. Otherwise we fall back to floatingpoint computation, 1924 2415 # to be backed up by exact symbolic computation only as required. 1925 2416 1926 2417 # These choices are motivated partly by efficiency considerations … … 1930 2421 # than as intervals, as often as possible. 1931 2422 1932 2423 def 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 """ 1933 2435 va = a._descr._value 1934 2436 vb = b._descr._value 1935 2437 if sub: … … 1939 2441 return ANRational(v) 1940 2442 1941 2443 def 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 1942 2456 va = a._descr._value 1943 2457 vb = b._descr._value 1944 2458 if div: … … 1948 2462 return ANRational(v) 1949 2463 1950 2464 def 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 """ 1951 2478 if b._descr.is_rational() and b._descr.rational_value().is_zero(): 1952 2479 return a._descr 1953 2480 # we know a is 0 … … 1957 2484 return b._descr 1958 2485 1959 2486 def 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 """ 1960 2502 if b._descr.is_rational() and b._descr.rational_value().is_zero(): 1961 2503 if div: 1962 raise ValueError , "algebraic number division by zero"2504 raise ValueError("algebraic number division by zero") 1963 2505 else: 1964 2506 return ANRational(0) 1965 2507 # we know a is 0 1966 2508 return ANRational(0) 1967 2509 1968 2510 def 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 """ 1969 2523 va = a._descr.gaussian_value() 1970 2524 vb = b._descr.gaussian_value() 1971 2525 if sub: … … 1975 2529 return ANExtensionElement(QQbar_I_generator, v) 1976 2530 1977 2531 def 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 """ 1978 2544 va = a._descr.gaussian_value() 1979 2545 vb = b._descr.gaussian_value() 1980 2546 if div: … … 1984 2550 return ANExtensionElement(QQbar_I_generator, v) 1985 2551 1986 2552 def an_addsub_expr(a, b, sub): 2553 r""" 2554 Add or subtract algebraic numbers represented as multipart 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 """ 1987 2569 return ANBinaryExpr(a, b, ('' if sub else '+')) 1988 2570 1989 2571 def an_muldiv_expr(a, b, div): 2572 r""" 2573 Multiply or divide algebraic numbers represented as multipart 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 """ 1990 2587 return ANBinaryExpr(a, b, ('/' if div else '*')) 1991 2588 1992 2589 def 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 """ 1993 2604 ad = a._descr 1994 2605 bd = b._descr 1995 2606 if div: … … 1998 2609 return ANRootOfUnity(ad.angle() + bd.angle(), ad.scale() * bd.scale()) 1999 2610 2000 2611 def 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 """ 2001 2628 ad = a._descr 2002 2629 bd = b._descr 2003 2630 if ad._angle == bd._angle: … … 2009 2636 return an_addsub_expr(a, b, sub) 2010 2637 2011 2638 def 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 """ 2012 2652 ad = a._descr 2013 2653 bd = b._descr 2014 2654 adg = ad.generator() … … 2026 2666 return ANBinaryExpr(a, b, ('/' if div else '*')) 2027 2667 2028 2668 def 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 """ 2029 2680 ad = a._descr 2030 2681 bd = b._descr 2031 2682 adg = ad.generator() … … 2105 2756 _add_algo[key] = an_addsub_expr 2106 2757 2107 2758 class ANDescr(SageObject): 2108 r""" An ``AlgebraicNumber`` or ``AlgebraicReal`` is a wrapper2109 around an ``ANDescr`` object. ``ANDescr`` is an abstract base2110 class, which should never be directly instantiated; its concrete2111 subclasses are ``ANRational``, ``ANBinaryExpr``, ``ANUnaryExpr``,2112 ``AN RootOfUnity``, ``ANRoot``, and ``ANExtensionElement``.2113 ``AN Descr`` and all of its subclasses are private, and should not2114 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. 2115 2766 """ 2116 2767 def is_exact(self): 2117 2768 """ … … 2160 2811 2161 2812 def is_rational(self): 2162 2813 r""" 2163 Returns ``True`` if self is an ``ANRational`` object. 2814 Returns ``True`` if self is an ``ANRational`` object. (Note that 2164 2815 the constructors for ``ANExtensionElement`` and ``ANRootOfUnity`` 2165 2816 will actually return ``ANRational`` objects for rational numbers.) 2166 2817 … … 2190 2841 """ 2191 2842 return False 2192 2843 2844 # Unitary operators: the second argument "n" is an AlgebraicNumber_base 2845 # wrapper around self. 2846 2193 2847 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 """ 2194 2858 return ANUnaryExpr(n, '') 2195 2859 2196 2860 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 """ 2197 2871 return ANUnaryExpr(n, '~') 2198 2872 2199 2873 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 """ 2200 2884 return ANUnaryExpr(n, 'abs') 2201 2885 2202 2886 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 """ 2203 2897 if self.is_complex(): 2204 2898 return ANUnaryExpr(n, 'real') 2205 2899 else: 2206 2900 return self 2207 2901 2208 2902 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 """ 2209 2913 if self.is_complex(): 2210 2914 return ANUnaryExpr(n, 'imag') 2211 2915 else: 2212 2916 return ANRational(0) 2213 2917 2214 2918 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 """ 2215 2929 if self.is_complex(): 2216 2930 return ANUnaryExpr(n, 'conjugate') 2217 2931 else: 2218 2932 return self 2219 2933 2220 2934 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 """ 2221 2946 if self.is_complex(): 2222 2947 return ANUnaryExpr(n, 'norm') 2223 2948 else: … … 2231 2956 2232 2957 ``AlgebraicNumber`` objects can be created using ``QQbar`` (== 2233 2958 ``AlgebraicNumberField()``), and ``AlgebraicReal`` objects can be created 2234 using ``AA`` (== ``AlgebraicRealField()``). 2959 using ``AA`` (== ``AlgebraicRealField()``). They can be created either by 2235 2960 coercing a rational or a symbolic expression, or by using the 2236 2961 ``QQbar.polynomial_root()`` or ``AA.polynomial_root()`` method to 2237 2962 construct a particular root of a polynomial with algebraic 2238 coefficients. 2963 coefficients. Also, ``AlgebraicNumber`` and ``AlgebraicReal`` are closed 2239 2964 under addition, subtraction, multiplication, division (except by 2240 2965 0), and rational powers (including roots), except that for a 2241 2966 negative ``AlgebraicReal``, taking a power with an even denominator returns 2242 2967 an ``AlgebraicNumber`` instead of an ``AlgebraicReal``. 2243 2968 2244 2969 ``AlgebraicNumber`` and ``AlgebraicReal`` objects can be 2245 approximated to any desired precision. 2970 approximated to any desired precision. They can be compared 2246 2971 exactly; if the two numbers are very close, or are equal, this may 2247 2972 require exact computation, which can be extremely slow. 2248 2973 2249 2974 As long as exact computation is not triggered, computation with 2250 2975 algebraic numbers should not be too much slower than computation with 2251 intervals. 2976 intervals. As mentioned above, exact computation is triggered 2252 2977 when comparing two algebraic numbers which are very close together. 2253 2978 This can be an explicit comparison in user code, but the following 2254 2979 list of actions (not necessarily complete) can also trigger exact … … 2285 3010 2286 3011 def __init__(self, parent, x): 2287 3012 r""" 2288 Initialize an algebraic number. 3013 Initialize an algebraic number. The argument must be either 2289 3014 a rational number, a Gaussian rational, or a subclass of ``ANDescr``. 2290 3015 2291 3016 EXAMPLES:: 2292 3017 2293 3018 sage: from sage.rings.qqbar import ANRootOfUnity … … 2307 3032 list(x.parent().polynomial()) == [1, 0, 1]: 2308 3033 self._descr = ANExtensionElement(QQbar_I_generator, QQbar_I_nf(x.list())) 2309 3034 else: 2310 raise TypeError , "Illegal initializer for algebraic number"3035 raise TypeError("Illegal initializer for algebraic number") 2311 3036 2312 3037 self._value = self._descr._interval_fast(64) 2313 3038 2314 3039 def _repr_(self): 2315 3040 """ 2316 3041 Returns the print representation of this number. 2317 3042 2318 3043 EXAMPLES:: 2319 3044 2320 sage: AA(22/7) 3045 sage: AA(22/7) # indirect doctest 2321 3046 22/7 2322 3047 sage: QQbar(1/3 + 2/7*I) 2323 3048 2/7*I + 1/3 … … 2393 3118 """ 2394 3119 TESTS:: 2395 3120 2396 sage: AA(sqrt(2)) * AA(sqrt(8)) 3121 sage: AA(sqrt(2)) * AA(sqrt(8)) # indirect doctest 2397 3122 4.000000000000000? 2398 3123 """ 2399 3124 sd = self._descr … … 2406 3131 """ 2407 3132 TESTS:: 2408 3133 2409 sage: AA(sqrt(2)) / AA(sqrt(8)) 3134 sage: AA(sqrt(2)) / AA(sqrt(8)) # indirect doctest 2410 3135 0.500000000000000? 2411 3136 """ 2412 3137 sd = self._descr … … 2431 3156 2432 3157 sage: x = polygen(ZZ) 2433 3158 sage: rt1, rt2 = (x^2  x  1).roots(ring=AA, multiplicities=False) 2434 sage: rt1 + rt2 3159 sage: rt1 + rt2 # indirect doctest 2435 3160 1.000000000000000? 2436 3161 """ 2437 3162 sd = self._descr … … 2444 3169 """ 2445 3170 TESTS:: 2446 3171 2447 sage: AA(golden_ratio) * 2  AA(5).sqrt() 3172 sage: AA(golden_ratio) * 2  AA(5).sqrt() # indirect doctest 2448 3173 1.000000000000000? 2449 3174 """ 2450 3175 sd = self._descr … … 2457 3182 """ 2458 3183 TESTS:: 2459 3184 2460 sage: QQbar(I) 3185 sage: QQbar(I) # indirect doctest 2461 3186 1*I 2462 3187 """ 2463 3188 return type(self)(self._descr.neg(self)) … … 2503 3228 2504 3229 sage: h1 = hash(QQbar.zeta(6)) 2505 3230 sage: h2 = hash(QQbar(1/2 + I*sqrt(3)/2)) 2506 sage: h1 == h2 3231 sage: h1 == h2 2507 3232 True 2508 3233 2509 3234 Unfortunately, the hash code for algebraic numbers which are close 2510 enough to each other are the same. 3235 enough to each other are the same. (This is inevitable, if 2511 3236 equal algebraic reals give the same hash code and hashing does 2512 3237 not always trigger exact computation.):: 2513 3238 … … 2526 3251 # 1, or 2 are presumably not uncommon). 2527 3252 2528 3253 # So I modify the algebraic real by adding 1/123456789 to it before 2529 # calling interval_exact(). 3254 # calling interval_exact(). Then, exact computation will be triggered 2530 3255 # by algebraic reals which are sufficiently close to 2531 # (some floating point number minus 1/123456789). 3256 # (some floating point number minus 1/123456789). Hopefully, 2532 3257 # 1/123456789 comes up in algebraic real computations far less 2533 # often than 0 does. 3258 # often than 0 does. Algebraic numbers have a similar offset added, 2534 3259 # with an additional complex component of 1/987654321*I. 2535 3260 2536 3261 # All of this effort to avoid exact computation is probably wasted, 2537 3262 # anyway... in almost all uses of hash codes, if the hash codes 2538 3263 # match, the next step is to compare for equality; and comparing 2539 # for equality often requires exact computation. 3264 # for equality often requires exact computation. (If a==b, 2540 3265 # then checking a==b requires exact computation unless (a is b).) 2541 3266 2542 3267 if self.parent() is AA: … … 2580 3305 return a square root of self in QQbar, otherwise raise a ValueError. 2581 3306 2582 3307  ``all``  bool (default: False); if True, return a list of all square 2583 roots. 3308 roots. If False, return just one square root, or raise an ValueError 2584 3309 if self is a negative element of AA and extend=False. 2585 3310 2586 3311 OUTPUT: 2587 3312 2588 3313 Either the principal square root of self, or a list of its … … 2597 3322 0.7071067811865475? + 0.7071067811865475?*I 2598 3323 sage: QQbar(I).sqrt(all=True) 2599 3324 [0.7071067811865475? + 0.7071067811865475?*I, 0.7071067811865475?  0.7071067811865475?*I] 2600 3325 2601 3326 sage: a = QQbar(0) 2602 3327 sage: a.sqrt() 2603 3328 0 2604 3329 sage: a.sqrt(all=True) 2605 3330 [0] 2606 3331 2607 3332 sage: a = AA(0) 2608 3333 sage: a.sqrt() 2609 3334 0 2610 3335 sage: a.sqrt(all=True) 2611 3336 [0] 2612 3337 2613 3338 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 2615 3340 ways can you squareroot zero? 2616 3341 2617 3342 :: 2618 3343 2619 3344 sage: AA(2).sqrt() 2620 3345 1.414213562373095?*I 2621 3346 2622 3347 sage: AA(2).sqrt(all=True) 2623 3348 [1.414213562373095?*I, 1.414213562373095?*I] 2624 3349 2625 3350 sage: AA(2).sqrt(extend=False) 2626 3351 Traceback (most recent call last): 2627 3352 ... … … 2630 3355 2631 3356 """ 2632 3357 # deal with 0 first: 2633 3358 2634 3359 if self.is_zero(): 2635 3360 if all: 2636 3361 return [self] … … 2641 3366 2642 3367 if self.parent() is AA and self<0 and not extend: 2643 3368 if not all: 2644 raise ValueError , "%s is not a square in AA, being negative. Use extend = True for a square root in QQbar."%self2645 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: 2646 3371 return [] 2647 3372 2648 3373 root = self.__pow__(~ZZ(2)) 2649 3374 2650 3375 if all: … … 2896 3621 r""" 2897 3622 Given a ``RealIntervalField``, compute the value of this number 2898 3623 using interval arithmetic of at least the precision of the field, 2899 and return the value in that field. 3624 and return the value in that field. (More precision may be used 2900 3625 in the computation.) The returned interval may be arbitrarily 2901 3626 imprecise, if this number is the result of a sufficiently long 2902 3627 computation chain. … … 2927 3652 def interval_diameter(self, diam): 2928 3653 """ 2929 3654 Compute an interval representation of self with ``diameter()`` at 2930 most ``diam``. 3655 most ``diam``. The precision of the returned value is unpredictable. 2931 3656 2932 3657 EXAMPLES:: 2933 3658 … … 2953 3678 Given an interval field (real or complex, as appropriate) of 2954 3679 precision `p`, compute an interval representation of self with 2955 3680 ``diameter()`` at most `2^{p}`; then round that representation into 2956 the given field. 3681 the given field. Here ``diameter()`` is relative diameter for 2957 3682 intervals not containing 0, and absolute diameter for 2958 3683 intervals that do contain 0; thus, if the returned interval 2959 3684 does not contain 0, it has at least `p1` good bits. … … 2982 3707 class AlgebraicNumber(AlgebraicNumber_base): 2983 3708 r""" 2984 3709 The class for algebraic numbers (complex numbers which are the roots 2985 of a polynomial with integer coefficients). 3710 of a polynomial with integer coefficients). Much of its functionality 2986 3711 is inherited from ``AlgebraicNumber_base``. 2987 3712 """ 2988 3713 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 """ 2989 3723 AlgebraicNumber_base.__init__(self, QQbar, x) 2990 3724 2991 3725 def __reduce__(self): … … 3002 3736 3003 3737 def __cmp__(self, other): 3004 3738 """ 3005 Compare two algebraic numbers, lexicographically. 3739 Compare two algebraic numbers, lexicographically. (That is, 3006 3740 first compare the real components; if the real components are 3007 3741 equal, compare the imaginary components.) 3008 3742 … … 3054 3788 return not self._sub_(other).__nonzero__() 3055 3789 3056 3790 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 """ 3057 3805 return not self.__eq__(other) 3058 3806 3059 3807 def __nonzero__(self): 3060 3808 """ 3061 Check whether self is equal is nonzero. 3809 Check whether self is equal is nonzero. This is fast if 3062 3810 interval arithmetic proves that self is nonzero, but may be 3063 3811 slow if the number actually is very close to zero. 3064 3812 … … 3088 3836 3089 3837 def __pow__(self, e): 3090 3838 r""" ``self**p`` returns the `p`'th power of self (where `p` can 3091 be an arbitrary rational). 3092 `b`'th root of self, then takes that to the `a`'th power. 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 3093 3841 that this differs from ``__pow__`` on algebraic reals, where real 3094 3842 roots are preferred over principal roots if they exist.) 3095 3843 … … 3123 3871 2 3124 3872 sage: a = QQbar.zeta(7)^(1/3); a 3125 3873 0.9555728057861407? + 0.2947551744109043?*I 3126 sage: a == QQbar.zeta(21) 3874 sage: a == QQbar.zeta(21) 3127 3875 True 3128 3876 sage: QQbar.zeta(7)^6 3129 3877 0.6234898018587335?  0.7818314824680299?*I … … 3181 3929 if val.imag().is_zero() and val.real() < 0: 3182 3930 argument_is_pi = True 3183 3931 break 3184 3932 3185 3933 target_abs = abs(val) ** e 3186 3934 target_arg = argument * e 3187 3935 … … 3213 3961 def _mpfr_(self, field): 3214 3962 r""" 3215 3963 Given a ``RealField``, compute a good approximation to self in 3216 that field. 3964 that field. Works only if the imaginary component of self is 3217 3965 exactly zero; otherwise it raises a ``ValueError``. 3218 3966 3219 3967 EXAMPLES:: … … 3231 3979 3232 3980 def __float__(self): 3233 3981 r""" 3234 Compute a good float approximation to self. 3982 Compute a good float approximation to self. Works only if the 3235 3983 imaginary component of self is exactly zero; otherwise it 3236 3984 raises a ``ValueError``. 3237 3985 … … 3247 3995 ValueError: Cannot coerce algebraic number with nonzero imaginary part to algebraic real 3248 3996 """ 3249 3997 return AA(self).__float__() 3250 3998 3251 3999 def __complex__(self): 3252 4000 r""" 3253 4001 Compute a good complex approximation to self. … … 3275 4023 return cdf(CC(self)) 3276 4024 3277 4025 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 """ 3278 4034 return self.interval_fast(ComplexIntervalField(prec)) 3279 4035 3280 4036 def _integer_(self, ZZ=None): … … 3332 4088 return AA(self)._rational_() 3333 4089 3334 4090 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 """ 3335 4099 return AlgebraicReal(self._descr.real(self)) 3336 4100 3337 4101 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 """ 3338 4110 return AlgebraicReal(self._descr.imag(self)) 3339 4111 3340 4112 def conjugate(self): … … 3354 4126 3355 4127 def norm(self): 3356 4128 r""" 3357 Returns ``self * self.conjugate()``. 4129 Returns ``self * self.conjugate()``. This is the algebraic 3358 4130 definition of norm, if we view ``QQbar`` as ``AA[I]``. 3359 4131 3360 4132 EXAMPLES:: … … 3371 4143 def interval_exact(self, field): 3372 4144 r""" 3373 4145 Given a ``ComplexIntervalField``, compute the best possible 3374 approximation of this number in that field. 4146 approximation of this number in that field. Note that if 3375 4147 either the real or imaginary parts of this number are 3376 4148 sufficiently close to some floatingpoint number (and, in 3377 4149 particular, if either is exactly representable in floatingpoint), … … 3390 4162 0 3391 4163 """ 3392 4164 if not is_ComplexIntervalField(field): 3393 raise ValueError , "AlgebraicNumber interval_exact requires a ComplexIntervalField"4165 raise ValueError("AlgebraicNumber interval_exact requires a ComplexIntervalField") 3394 4166 rfld = field._real_field() 3395 4167 re = self.real().interval_exact(rfld) 3396 4168 im = self.imag().interval_exact(rfld) 3397 4169 return field(re, im) 3398 4170 3399 4171 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 """ 3400 4190 if is_ComplexIntervalField(field): 3401 4191 return self.interval(field) 3402 4192 else: 3403 4193 return self.complex_number(field) 3404 4194 3405 3406 4195 def complex_number(self, field): 3407 4196 r""" Given a ``ComplexField``, compute a good approximation to 3408 self in that field. 4197 self in that field. The approximation will be off by at most 3409 4198 two ulp's in each component, except for components which are 3410 4199 very close to zero, which will have an absolute error at most 3411 4200 ``2**((field.prec()1))``. … … 3424 4213 def complex_exact(self, field): 3425 4214 r""" 3426 4215 Given a ``ComplexField``, return the best possible approximation of 3427 this number in that field. 4216 this number in that field. Note that if either component is 3428 4217 sufficiently close to the halfway point between two floatingpoint 3429 4218 numbers in the corresponding ``RealField``, then this will trigger 3430 4219 exact computation, which may be very slow. … … 3439 4228 rfld = field._real_field() 3440 4229 re = self.real().real_exact(rfld) 3441 4230 im = self.imag().real_exact(rfld) 3442 return field(re, im) 4231 return field(re, im) 3443 4232 3444 4233 def multiplicative_order(self): 3445 4234 r""" 3446 4235 Compute the multiplicative order of this algebraic real 3447 number. 3448 that `x^n = 1`. 3449 3450 We first check that ``abs(x)`` is very close to 1. 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 3451 4240 `x` exactly and examine its argument. 3452 4241 3453 4242 EXAMPLES:: … … 3475 4264 def rational_argument(self): 3476 4265 r""" 3477 4266 Returns the argument of self, divided by `2\pi`, as long as this 3478 result is rational. Otherwise returns None.Always triggers4267 result is rational. Otherwise returns None. Always triggers 3479 4268 exact computation. 3480 4269 3481 4270 EXAMPLES:: … … 3493 4282 sage: (QQbar.zeta(3)^65536).rational_argument() 3494 4283 1/3 3495 4284 """ 3496 # This always triggers exact computation. 4285 # This always triggers exact computation. An alternate method 3497 4286 # could almost always avoid exact computation when the result 3498 4287 # is None: if we can compute an upper bound on the degree of 3499 4288 # this algebraic number without exact computation, we can use … … 3510 4299 def __init__(self, x): 3511 4300 """ 3512 4301 Create an algebraic real from x, possibly taking the real part of x. 3513 4302 3514 4303 TESTS: 3515 4304 3516 Both of the following examples, from trac 11728, trigger3517 taking the real part below. 4305 Both of the following examples, from :trac:`11728`, trigger 4306 taking the real part below. This is necessary because 3518 4307 sometimes a very small (e.g., 1e17) complex part appears in a 3519 4308 complex interval used to create an AlgebraicReal.:: 3520 4309 … … 3532 4321 part. 3533 4322 3534 4323 EXAMPLES:: 3535 4324 3536 4325 sage: a = QQbar((1)^(1/4)); b = AA(a^3a); b._value 3537 4326 1.4142135623730950488? 3538 4327 sage: b._value = a._value; b._value … … 3551 4340 Recompute the interval bounding this number with higherprecision 3552 4341 interval arithmetic. 3553 4342 4343 EXAMPLE:: 4344 4345 sage: a = QQbar(sqrt(2)) 4346 sage: a._more_precision() 4347 3554 4348 TESTS: 3555 4349 3556 4350 We have to ensure after doing this that self._value is still 3557 4351 real which isn't the case without calling _ensure_real (see 3558 trac 11728)::3559 4352 :trac:`11728`):: 4353 3560 4354 sage: P = AA[x](1+x^4); a1,a2 = P.factor()[0][0],P.factor()[1][0]; a1*a2 3561 4355 x^4 + 1.000000000000000? 3562 4356 sage: a1,a2 … … 3603 4397 def __pow__(self, e): 3604 4398 """ 3605 4399 ``self**p`` returns the `p`'th power of self (where `p` can be an 3606 arbitrary rational). 3607 self, then takes that to the `a`'th power. 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 3608 4402 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. 4403 `b` is even, this takes a complex root. Note that the behavior 3610 4404 when self is negative and `b` is odd differs from the complex 3611 4405 case; algebraic numbers select the principal complex `b`'th 3612 4406 root, but algebraic reals select the real root. … … 3712 4506 """ 3713 4507 if self._value.lower().ceiling() > self._value.upper().floor(): 3714 4508 # The value is known to be nonintegral. 3715 raise ValueError , "Cannot coerce nonintegral Algebraic Real %s to Integer" % self4509 raise ValueError("Cannot coerce nonintegral Algebraic Real %s to Integer" % self) 3716 4510 3717 4511 self.exactify() 3718 4512 if not self._descr.is_rational(): 3719 raise ValueError , "Cannot coerce irrational Algebraic Real %s to Integer" % self4513 raise ValueError("Cannot coerce irrational Algebraic Real %s to Integer" % self) 3720 4514 3721 4515 return ZZ(self._descr.rational_value()) 3722 4516 … … 3741 4535 """ 3742 4536 self.exactify() 3743 4537 if not self._descr.is_rational(): 3744 raise ValueError , "Cannot coerce irrational Algebraic Real %s to Rational" % self4538 raise ValueError("Cannot coerce irrational Algebraic Real %s to Rational" % self) 3745 4539 3746 4540 return QQ(self._descr.rational_value()) 3747 4541 … … 3821 4615 return self.sign() 3822 4616 3823 4617 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 """ 3824 4627 return self.interval_fast(RealIntervalField(prec)) 3825 4628 3826 4629 def interval_exact(self, field): 3827 4630 """ 3828 4631 Given a ``RealIntervalField``, compute the best possible 3829 approximation of this number in that field. 4632 approximation of this number in that field. Note that if this 3830 4633 number is sufficiently close to some floatingpoint number 3831 4634 (and, in particular, if this number is exactly representable in 3832 4635 floatingpoint), then this will trigger exact computation, which … … 3887 4690 def real_number(self, field): 3888 4691 """ 3889 4692 Given a ``RealField``, compute a good approximation to self in 3890 that field. 4693 that field. The approximation will be off by at most two 3891 4694 ulp's, except for numbers which are very close to 0, which 3892 4695 will have an absolute error at most 3893 ``2**((field.prec()1))``. 4696 ``2**((field.prec()1))``. Also, the rounding mode of the 3894 4697 field is respected. 3895 4698 3896 4699 EXAMPLES:: … … 3963 4766 return float(RR(self)) 3964 4767 3965 4768 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 """ 3966 4785 if is_ComplexIntervalField(field): 3967 4786 return field(self.interval(field._real_field())) 3968 4787 else: … … 3971 4790 def real_exact(self, field): 3972 4791 r""" 3973 4792 Given a ``RealField``, compute the best possible approximation of 3974 this number in that field. 4793 this number in that field. Note that if this number is 3975 4794 sufficiently close to the halfway point between two 3976 4795 floatingpoint numbers in the field (for the default 3977 4796 roundtonearest mode) or if the number is sufficiently close … … 4037 4856 4038 4857 val = self.interval_exact(rifp1) 4039 4858 4040 # Call the largest floatingpoint number <= self 'x'. 4859 # Call the largest floatingpoint number <= self 'x'. Then 4041 4860 # val may be [x .. x], [x .. x + 1/2 ulp], 4042 4861 # [x + 1/2 ulp .. x + 1/2 ulp], or [x + 1/2 ulp .. x + 1 ulp]; 4043 4862 # in the second and fourth cases, the true value is not equal … … 4058 4877 class ANRational(ANDescr): 4059 4878 r""" 4060 4879 The subclass of ``ANDescr`` that represents an arbitrary 4061 rational. 4880 rational. This class is private, and should not be used directly. 4062 4881 """ 4063 4882 4064 4883 def __init__(self, x): … … 4076 4895 elif isinstance(x, (int, long)): 4077 4896 self._value = ZZ(x) 4078 4897 else: 4079 raise TypeError , "Illegal initializer for algebraic number rational"4898 raise TypeError("Illegal initializer for algebraic number rational") 4080 4899 4081 4900 def __reduce__(self): 4082 4901 """ … … 4084 4903 4085 4904 EXAMPLES:: 4086 4905 4087 sage: t = AA(5/2); type(t._descr) 4906 sage: t = AA(5/2); type(t._descr) 4088 4907 <class 'sage.rings.qqbar.ANRational'> 4089 4908 sage: loads(dumps(t)) == t 4090 4909 True … … 4092 4911 return (ANRational, (self._value, )) 4093 4912 4094 4913 def _repr_(self): 4914 r""" 4915 String representation of self. 4916 4917 EXAMPLES:: 4918 4919 sage: QQbar(2/3)._repr_() 4920 '2/3' 4921 """ 4095 4922 return repr(self._value) 4096 4923 4097 4924 def handle_sage_input(self, sib, coerce, is_qqbar): … … 4124 4951 return (v, False) 4125 4952 4126 4953 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 """ 4127 4969 if self._value.is_zero(): 4128 4970 return 'zero' 4129 4971 else: 4130 4972 return 'rational' 4131 4973 4132 4974 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 """ 4133 4983 return RealIntervalField(prec)(self._value) 4134 4984 4135 4985 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 """ 4136 4995 return qq_generator 4137 4996 4138 4997 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 """ 4139 5006 return False 4140 5007 4141 5008 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 """ 4142 5019 return True 4143 5020 4144 5021 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 """ 4145 5033 return self._value 4146 5034 4147 5035 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 """ 4148 5045 return self 4149 5046 4150 5047 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 """ 4151 5056 return True 4152 5057 4153 5058 def is_simple(self): … … 4165 5070 return True 4166 5071 4167 5072 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 """ 4168 5081 return QQx_x  self._value 4169 5082 4170 5083 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 """ 4171 5096 return ANRational(self._value) 4172 5097 4173 5098 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 """ 4174 5109 return ANRational(~self._value) 4175 5110 4176 5111 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 """ 4177 5122 return ANRational(abs(self._value)) 4178 5123 4179 5124 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 """ 4180 5138 if self._value > 0: 4181 5139 return QQ(0) 4182 5140 if self._value < 0: … … 4184 5142 return None 4185 5143 4186 5144 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 """ 4187 5157 return QQbar_I_nf(self._value) 4188 5158 4189 5159 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 """ 4190 5173 return QQ_0 4191 5174 4192 5175 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 """ 4193 5186 return self._value 4194 5187 4195 5188 class ANRootOfUnity(ANDescr): 4196 5189 r""" 4197 5190 The subclass of ``ANDescr`` that represents a rational multiplied 4198 by a root of unity. 5191 by a root of unity. This class is private, and should not be 4199 5192 used directly. 4200 5193 4201 5194 Such numbers are represented by a "rational angle" and a rational 4202 scale. 5195 scale. The "rational angle" is the argument of the number, divided by 4203 5196 `2\pi`; so given angle `\alpha` and scale `s`, the number is: 4204 5197 `s(\cos(2\pi\alpha) + \sin(2\pi\alpha)i)`; or equivalently 4205 5198 `s(e^{2\pi\alpha i})`. 4206 5199 4207 5200 We normalize so that `0<\alpha<\frac{1}{2}`; this requires 4208 allowing both positive and negative scales. 5201 allowing both positive and negative scales. (Attempts to create 4209 5202 an ``ANRootOfUnity`` with an angle which is a multiple of 4210 5203 `\frac{1}{2}` end up creating an ``ANRational`` instead.) 4211 5204 """ … … 4213 5206 def __new__(self, angle, scale): 4214 5207 r""" 4215 5208 Construct an ``ANRootOfUnity`` from a rational angle and a rational 4216 scale. 5209 scale. If the number is actually a real rational, returns an 4217 5210 ``ANRational`` instead. 4218 5211 """ 4219 5212 if scale.is_zero(): … … 4229 5222 else: 4230 5223 # int_angle is even 4231 5224 return ANRational(scale) 4232 5225 4233 5226 def __init__(self, angle, scale): 4234 5227 """ 4235 5228 Construct an ``ANRootOfUnity`` from a rational angle and a rational 4236 5229 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 """ 4239 5236 angle2 = angle * 2 4240 5237 fl2 = angle2.floor() 4241 5238 angle2 = angle2  fl2 … … 4251 5248 4252 5249 EXAMPLES:: 4253 5250 4254 sage: t = QQbar.zeta(3) * 5; type(t._descr) 5251 sage: t = QQbar.zeta(3) * 5; type(t._descr) 4255 5252 <class 'sage.rings.qqbar.ANRootOfUnity'> 4256 5253 sage: loads(dumps(t)) == t 4257 5254 True … … 4259 5256 return (ANRootOfUnity, (self._angle, self._scale)) 4260 5257 4261 5258 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 """ 4262 5269 return "%s*e^(2*pi*I*%s)"%(self._scale, self._angle) 4263 5270 4264 5271 def handle_sage_input(self, sib, coerce, is_qqbar): … … 4312 5319 return (v, True) 4313 5320 4314 5321 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 """ 4315 5332 if self._angle == QQ_1_4: 4316 5333 return 'imaginary' 4317 5334 else: 4318 5335 return 'rootunity' 4319 5336 4320 5337 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 """ 4321 5346 argument = self._angle * RealIntervalField(prec).pi() * 2 4322 5347 if self._angle == QQ_1_4: 4323 5348 return ComplexIntervalField(prec)(0, self._scale) … … 4325 5350 return ComplexIntervalField(prec)(argument.cos(), argument.sin()) * self._scale 4326 5351 4327 5352 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 """ 4328 5364 return cyclotomic_generator(self._angle.denominator()) 4329 5365 4330 5366 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 """ 4331 5380 gen = self.generator() 4332 5381 f = gen._field 4333 5382 a = f.gen() 4334 5383 return self._scale * a ** self._angle.numerator() 4335 5384 4336 5385 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 """ 4337 5397 return True 4338 5398 4339 5399 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 """ 4340 5411 return self 4341 5412 4342 5413 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 """ 4343 5425 return True 4344 5426 4345 5427 def is_simple(self): … … 4377 5459 p = p / p.leading_coefficient() 4378 5460 return p 4379 5461 5462 # These all ignore "n". 5463 4380 5464 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 """ 4381 5475 return ANRootOfUnity(self._angle, self._scale) 4382 5476 4383 5477 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 """ 4384 5488 # We want ANRootOfUnity(self._angle, ~self._scale); 4385 5489 # but that's not normalized, so we prenormalize it to: 4386 5490 return ANRootOfUnity(QQ_1_2  self._angle, ~self._scale) 4387 5491 4388 5492 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 """ 4389 5503 # We want ANRootOfUnity(self._angle, self._scale); 4390 5504 # but that's not normalized, so we prenormalize it to: 4391 5505 return ANRootOfUnity(QQ_1_2  self._angle, self._scale) 4392 5506 4393 5507 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 """ 4394 5518 return ANRational(abs(self._scale)) 4395 5519 4396 5520 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 """ 4397 5531 return ANRational(self._scale * self._scale) 4398 5532 4399 5533 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 """ 4400 5545 if self._scale > 0: 4401 5546 return self._angle 4402 5547 else: 4403 5548 return self._angle  QQ_1_2 4404 5549 4405 5550 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 """ 4406 5563 assert(self._angle == QQ_1_4) 4407 5564 return QQbar_I_nf(self._scale * QQbar_I_nf.gen()) 4408 5565 4409 5566 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 """ 4410 5578 return self._angle 4411 5579 4412 5580 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 """ 4413 5591 return self._scale 4414 5592 4415 5593 def 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 """ 4416 5607 return isinstance(x, AlgebraicReal) 4417 5608 4418 5609 def 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 """ 4419 5623 return isinstance(x, AlgebraicNumber) 4420 5624 4421 5625 QQbarPoly = PolynomialRing(QQbar, 'x') … … 4427 5631 4428 5632 If multiple algebraic numbers are created as roots of a single 4429 5633 polynomial, this allows the polynomial and information about 4430 the polynomial to be shared. 5634 the polynomial to be shared. This reduces work if the polynomial 4431 5635 must be recomputed at higher precision, or if it must be factored. 4432 5636 4433 5637 This class is private, and should only be constructed by 4434 5638 ``AA.common_polynomial()`` or ``QQbar.common_polynomial()``, and should 4435 5639 only be used as an argument to ``AA.polynomial_root()`` or 4436 ``QQbar.polynomial_root()``. 5640 ``QQbar.polynomial_root()``. (It doesn't matter whether you create 4437 5641 the common polynomial with ``AA.common_polynomial()`` or 4438 5642 ``QQbar.common_polynomial()``.) 4439 5643 … … 4448 5652 """ 4449 5653 4450 5654 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 """ 4451 5665 if not is_Polynomial(poly): 4452 raise ValueError , "Trying to create AlgebraicPolynomialTracker on nonPolynomial"5666 raise ValueError("Trying to create AlgebraicPolynomialTracker on nonPolynomial") 4453 5667 if isinstance(poly.base_ring(), AlgebraicField_common): 4454 5668 complex = is_AlgebraicField(poly.base_ring()) 4455 5669 else: … … 4502 5716 {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})})}})} 4503 5717 """ 4504 5718 # XXX It would be nicer to skip the "AA.common_polynomial()" 4505 # wrapper if the polynomial is not actually shared. 5719 # wrapper if the polynomial is not actually shared. But 4506 5720 # sage_input.py isn't quite that generic. 4507 5721 v = sib.name('AA').common_polynomial(self._poly) 4508 5722 sib.id_cache(self, v, 'cp') 4509 5723 return v 4510 5724 4511 5725 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 """ 4512 5735 return repr(self._poly) 4513 5736 4514 5737 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 """ 4515 5748 return self._poly 4516 5749 4517 5750 def is_complex(self): 5751 r""" 5752 Return True if the coefficients of this polynomial are nonreal. 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 """ 4518 5763 return self._complex 4519 5764 4520 5765 def complex_roots(self, prec, multiplicity): 4521 5766 """ 5767 Find the roots of self in the complex field to precision prec. 5768 4522 5769 EXAMPLES:: 4523 5770 4524 5771 sage: x = polygen(ZZ) … … 4554 5801 Compute a common field that holds all of the algebraic coefficients 4555 5802 of this polynomial, then factor the polynomial over that field. 4556 5803 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 4557 5815 """ 4558 5816 if self._exact: 4559 5817 return … … 4582 5840 self._factors = [fac_exp[0] for fac_exp in fp.factor()] 4583 5841 4584 5842 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 """ 4585 5850 self.exactify() 4586 5851 return self._factors 4587 5852 4588 5853 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 """ 4589 5866 self.exactify() 4590 5867 return self._gen 4591 5868 … … 4596 5873 This class is private, and should not be used directly. 4597 5874 """ 4598 5875 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 """ 4599 5885 if not isinstance(poly, AlgebraicPolynomialTracker): 4600 5886 poly = AlgebraicPolynomialTracker(poly) 4601 5887 self._poly = poly … … 4604 5890 self._complex_poly = poly.is_complex() 4605 5891 self._interval = self.refine_interval(interval, 64) 4606 5892 self._is_pow = is_pow 4607 5893 4608 5894 def __reduce__(self): 4609 5895 """ 4610 5896 Add customized pickling support. … … 4621 5907 return (ANRoot, (self._poly, self._interval, self._multiplicity)) 4622 5908 4623 5909 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 """ 4624 5919 return 'Root %s of %s'%(self._interval, self._poly) 4625 5920 4626 5921 def handle_sage_input(self, sib, coerce, is_qqbar): … … 4635 5930 # Verified 4636 5931 sqrt(AA(3)).nth_root(3) 4637 5932 4638 These two examples are too big to verify quickly. 5933 These two examples are too big to verify quickly. (Verification 4639 5934 would create a field of degree 28.):: 4640 5935 4641 5936 sage: sage_input((sqrt(AA(3))^(5/7))^(9/4)) … … 4650 5945 sage: sage_input(QQbar.polynomial_root(x^35, CIF(RIF(3, 0), RIF(0, 3))), verify=True) 4651 5946 # Verified 4652 5947 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)))) 4654 5949 sage: from sage.rings.qqbar import * 4655 5950 sage: from sage.misc.sage_input import SageInputBuilder 4656 5951 sage: sib = SageInputBuilder() … … 4692 5987 return (parent.polynomial_root(poly, sib(good_intv)), True) 4693 5988 4694 5989 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 """ 4695 5998 return 'other' 4696 5999 4697 6000 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 """ 4698 6015 return self._complex 4699 6016 4700 6017 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 """ 4701 6032 if not self._complex: 4702 6033 return self 4703 6034 if not self._complex_poly: … … 4706 6037 return ANUnaryExpr(n, 'conjugate') 4707 6038 4708 6039 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 `k1`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 """ 4709 6061 if self._complex or self._complex_poly: 4710 6062 v = self._complex_refine_interval(interval, prec) 4711 6063 if self._complex: … … 4717 6069 4718 6070 def _real_refine_interval(self, interval, prec): 4719 6071 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 `k1`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``. 4731 6073 4732 6074 EXAMPLES:: 4733 6075 4734 6076 sage: from sage.rings.qqbar import ANRoot 4735 6077 sage: x = polygen(AA) 4736 6078 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 4738 6080 1.4142135623730950488017? 4739 6081 """ 4740 6082 # Don't throw away bits in the original interval; doing so might … … 4762 6104 # This special case is important: this is the only way we could 4763 6105 # refine "infinitely deep" (we could get an interval of diameter 4764 6106 # about 2^{2^31}, and then hit floatingpoint 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 4766 6108 # many times later 4767 6109 if coeffs[0].is_zero() and interval.contains_zero(): 4768 6110 return zero … … 4770 6112 # interval_dp = poly_ring(dp) 4771 6113 dcoeffs = [c.interval_fast(field) for c in dp.list()] 4772 6114 interval_dp = poly_ring(dcoeffs) 4773 6115 4774 6116 linfo = {} 4775 6117 uinfo = {} 4776 6118 … … 4806 6148 # print interval_p 4807 6149 # print linfo['endpoint'], linfo['value'], linfo['sign'] 4808 6150 # 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!") 4810 6152 4811 6153 # Use a simple algorithm: 4812 # Try an interval NewtonRaphson step. 6154 # Try an interval NewtonRaphson step. If this does not add at 4813 6155 # least one bit of information, or if it fails (because the 4814 6156 # slope is not bounded away from zero), then try bisection. 4815 6157 # If this fails because the value at the midpoint is not … … 4891 6233 # but the interval is no more than twice as wide as the 4892 6234 # narrowest possible.) 4893 6235 return interval 4894 6236 4895 6237 def _complex_refine_interval(self, interval, prec): 4896 6238 r""" 4897 6239 Takes an interval which is assumed to enclose exactly one root … … 4899 6241 of the `k1`st derivative); and a precision, in bits. 4900 6242 4901 6243 Tries to find a narrow interval enclosing the root using 4902 interval arithmetic of the given precision. 6244 interval arithmetic of the given precision. (No particular 4903 6245 number of resulting bits of precision is guaranteed.) 4904 6246 4905 Uses Newton's method (adapted for interval arithmetic). 6247 Uses Newton's method (adapted for interval arithmetic). The 4906 6248 algorithm will converge very quickly if started with a 4907 sufficiently narrow interval. 6249 sufficiently narrow interval. If Newton's method fails, then 4908 6250 we falls back on computing all the roots of the polynomial 4909 6251 numerically, and select the appropriate root. 4910 6252 … … 4914 6256 sage: x = polygen(QQbar) 4915 6257 sage: intv = CIF(RIF(0, 1), RIF(0.1, 1)) 4916 6258 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 4918 6260 0.3090169943749474241? + 0.951056516295153573?*I 4919 6261 sage: rt.refine_interval(new_intv, 70) 4920 6262 0.30901699437494742411? + 0.95105651629515357212?*I … … 4944 6286 # This special case is important: this is the only way we could 4945 6287 # refine "infinitely deep" (we could get an interval of diameter 4946 6288 # about 2^{2^31}, and then hit floatingpoint 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 4948 6290 # many times later 4949 6291 if coeffs[0].is_zero() and zero in interval: 4950 6292 return zero … … 4952 6294 # interval_dp = poly_ring(dp) 4953 6295 dcoeffs = [c.interval_fast(field) for c in dp.list()] 4954 6296 interval_dp = poly_ring(dcoeffs) 4955 6297 4956 6298 while True: 4957 6299 center = field(interval.center()) 4958 6300 val = interval_p(center) … … 4972 6314 new_diam = interval.diameter() 4973 6315 4974 6316 if new_diam == 0: 4975 # Wow; we nailed it exactly. 6317 # Wow; we nailed it exactly. (This may happen 4976 6318 # whenever the root is exactly equal to some 4977 6319 # floatingpoint number, and cannot happen 4978 6320 # if the root is not equal to a floatingpoint … … 4980 6322 return interval 4981 6323 4982 6324 if new_diam == diam: 4983 # We're not getting any better. 4984 # possible reasons for this. 6325 # We're not getting any better. There are two 6326 # possible reasons for this. Either we have 4985 6327 # refined as much as possible given the imprecision 4986 6328 # of our interval polynomial, and we have the best 4987 6329 # answer we're going to get at this precision; … … 4992 6334 4993 6335 # I do not have a formal proof, but I believe the 4994 6336 # following test differentiates between these two 4995 # behaviors. 6337 # behaviors. (If I'm wrong, we might get bad behavior 4996 6338 # like infinite loops, but we still won't actually 4997 6339 # return a wrong answer.) 4998 6340 … … 5005 6347 return interval 5006 6348 5007 6349 # The center of the current interval is known 5008 # not to be a root. 6350 # not to be a root. This should let us divide 5009 6351 # the interval in half, and improve on our previous 5010 # estimates. 6352 # estimates. I can only think of two reasons why 5011 6353 # it might not: 5012 6354 # 1) the "center" of the interval is actually 5013 6355 # on one of the edges of the interval (because the … … 5032 6374 # whether the diameter is less than pi/2; in that 5033 6375 # case, no matter the value of "val" (as long as 5034 6376 # "val" is fairly precise), "val / slope" should 5035 # be bounded away from zero. 6377 # be bounded away from zero. But we compare 5036 6378 # against 1 instead, in the hopes that this might 5037 6379 # be slightly faster. 5038 6380 … … 5046 6388 """ 5047 6389 Find a precise approximation to the unique root in interval, 5048 6390 by finding a precise approximation to all roots of the 5049 polynomial, and checking which one is in interval. 6391 polynomial, and checking which one is in interval. Slow but sure. 5050 6392 5051 6393 EXAMPLES:: 5052 6394 … … 5066 6408 return our_root[0] 5067 6409 5068 6410 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") 5070 6412 5071 6413 # We have more than one root that overlap the current interval. 5072 6414 # Technically, this might not be an error; perhaps the actual … … 5076 6418 # But it seems far more likely that the provided interval is 5077 6419 # just too big. 5078 6420 5079 raise ValueError , "Complex root interval probably includes multiple roots"6421 raise ValueError("Complex root interval probably includes multiple roots") 5080 6422 5081 6423 def exactify(self): 5082 6424 """ … … 5115 6457 red_elt, red_back, red_pol = do_polred(my_factor) 5116 6458 5117 6459 field = NumberField(red_pol, 'a', check=False) 5118 6460 5119 6461 def intv_fn(rif): 5120 6462 return conjugate_expand(red_elt(self._interval_fast(rif) * den)) 5121 6463 new_intv = conjugate_shrink(isolating_interval(intv_fn, red_pol)) 5122 6464 root = ANRoot(QQx(red_pol), new_intv) 5123 6465 new_gen = AlgebraicGenerator(field, root) 5124 6466 5125 6467 return ANExtensionElement(new_gen, red_back(field.gen())/den) 5126 6468 else: 5127 6469 fld = gen.field() … … 5151 6493 5152 6494 5153 6495 pari_nf = gen.pari_field() 5154 6496 5155 6497 # print pari_nf[0] 5156 6498 x, y = QQxy.gens() 5157 6499 my_factor = QQxy['z']([c.polynomial()(y) for c in my_factor])(x) … … 5172 6514 red_elt, red_back, red_pol = do_polred(newpol_sage_y) 5173 6515 5174 6516 new_nf = NumberField(red_pol, name='a', check=False) 5175 6517 5176 6518 self_pol_sage = QQx(self_pol.lift()) 5177 6519 5178 6520 new_nf_a = new_nf.gen() 5179 6521 5180 6522 def intv_fn(prec): 5181 6523 return conjugate_expand(red_elt(gen._interval_fast(prec) * k + self._interval_fast(prec) * den)) 5182 6524 new_intv = conjugate_shrink(isolating_interval(intv_fn, red_pol)) … … 5186 6528 red_back_a = red_back(new_nf.gen()) 5187 6529 new_poly = ((QQx_x  k * self_pol_sage)(red_back_a)/den) 5188 6530 return ANExtensionElement(new_gen, new_poly) 5189 6531 5190 6532 def _more_precision(self): 5191 6533 """ 5192 Recompute the interval enclosing this root at higher6534 Recompute the interval enclosing this ``ANRoot`` object at higher 5193 6535 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 5194 6546 """ 5195 6547 prec = self._interval.prec() 5196 6548 self._interval = self.refine_interval(self._interval, prec*2) … … 5199 6551 """ 5200 6552 Given a RealIntervalField, compute the value of this number 5201 6553 using interval arithmetic of at least the precision of the field, 5202 and return the value in that field. 6554 and return the value in that field. (More precision may be used 5203 6555 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? 5204 6562 """ 5205 6563 if prec == self._interval.prec(): 5206 6564 return self._interval … … 5213 6571 5214 6572 _cyclotomic_gen_cache = {} 5215 6573 def 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 """ 5216 6586 try: 5217 6587 return _cyclotomic_gen_cache[n] 5218 6588 except KeyError: … … 5228 6598 class ANExtensionElement(ANDescr): 5229 6599 r""" 5230 6600 The subclass of ``ANDescr`` that represents a number field 5231 element in terms of a specific generator. 6601 element in terms of a specific generator. Consists of a polynomial 5232 6602 with rational coefficients in terms of the generator, and the 5233 6603 generator itself, an ``AlgebraicGenerator``. 5234 6604 """ … … 5239 6609 except TypeError: 5240 6610 if generator is QQbar_I_generator and value[0].is_zero(): 5241 6611 return ANRootOfUnity(QQ_1_4, value[1]) 5242 return ANDescr.__new__(self) 6612 return ANDescr.__new__(self) 5243 6613 5244 6614 def __init__(self, generator, value): 5245 6615 self._generator = generator … … 5261 6631 True 5262 6632 """ 5263 6633 return (ANExtensionElement, (self._generator, self._value)) 5264 6634 5265 6635 def _repr_(self): 5266 6636 return '%s where %s = 0 and a in %s'%(self._value, 5267 6637 self._generator.field().polynomial()._repr(name='a'), … … 5317 6687 rt = sib(self._generator.root_as_algebraic()) 5318 6688 # For the best fidelity, we really ought to somehow ensure 5319 6689 # that rt is exactified, but sage_input doesn't support that 5320 # nicely. 6690 # nicely. Skip it for now. 5321 6691 # The following is copied with slight mods from polynomial_element.pyx 5322 6692 coeffs = [sib(c, True) for c in self._value.list()] 5323 6693 terms = [] … … 5334 6704 if result_is_qqbar != is_qqbar: 5335 6705 v = sib.name('QQbar' if is_qqbar else 'AA')(v) 5336 6706 return (v, True) 5337 6707 5338 6708 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 """ 5339 6723 if self._generator is QQbar_I_generator: 5340 6724 return 'gaussian' 5341 6725 else: 5342 6726 return 'element' 5343 6727 5344 6728 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 nonreal, 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 """ 5345 6748 return not self._exactly_real 5346 6749 5347 6750 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 """ 5348 6766 return True 5349 6767 5350 6768 def is_simple(self): … … 5380 6798 return self._is_simple 5381 6799 5382 6800 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 """ 5383 6810 return True 5384 6811 5385 6812 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 """ 5386 6822 return self._generator 5387 6823 5388 6824 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 """ 5389 6837 return self 5390 6838 5391 6839 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 """ 5392 6849 return self._value 5393 6850 5394 6851 def minpoly(self): … … 5397 6854 5398 6855 EXAMPLES:: 5399 6856 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 5406 6862 """ 5407 6863 try: 5408 6864 return self._minpoly … … 5435 6891 if self.is_simple(): 5436 6892 return self 5437 6893 5438 # This is very inefficient... 6894 # This is very inefficient... 5439 6895 # for instance, the .exactify() call will try to factor poly, 5440 6896 # even though we know that poly is irreducible 5441 6897 poly = self.minpoly() … … 5451 6907 return v.real() 5452 6908 return v 5453 6909 6910 # for these three functions the argument n is not used (but it is there 6911 # anyway for compatibility) 6912 5454 6913 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 """ 5455 6929 return ANExtensionElement(self._generator, self._value) 5456 6930 5457 6931 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 """ 5458 6947 return ANExtensionElement(self._generator, ~self._value) 5459 6948 5460 6949 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 """ 5461 6965 if self._exactly_real: 5462 6966 return self 5463 6967 else: 5464 6968 return ANExtensionElement(self._generator.conjugate(), self._value) 5465 6969 6970 # The rest of these unary operations do actually use n, which is an 6971 # AlgebraicNumber pointing to self. 6972 5466 6973 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 """ 5467 6987 if self._exactly_real: 5468 6988 return (n*n)._descr 5469 6989 elif self._generator is QQbar_I_generator: … … 5472 6992 return ANUnaryExpr(n, 'norm') 5473 6993 5474 6994 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 """ 5475 7008 return AlgebraicReal(self.norm(n)).sqrt()._descr 5476 7009 5477 7010 def rational_argument(self, n): 5478 7011 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 """ 5483 7031 # If the argument of self is 2*pi times some rational number a/b, 5484 7032 # then self/abs(self) is a root of the b'th cyclotomic polynomial. 5485 7033 # This implies that the algebraic degree of self is at least 5486 # phi(b). 7034 # phi(b). Working backward, we know that the algebraic degree 5487 7035 # of self is at most the degree of the generator, so that gives 5488 # an upper bound on phi(b). 7036 # an upper bound on phi(b). According to 5489 7037 # http://mathworld.wolfram.com/TotientFunction.html, 5490 7038 # phi(b) >= sqrt(b) for b > 6; this gives us an upper bound on b. 5491 7039 # We then check to see if this is possible; if so, we test … … 5515 7063 raise NotImplementedError 5516 7064 5517 7065 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 nonexample:: 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 """ 5518 7091 assert(self._generator is QQbar_I_generator) 5519 7092 return self._value 5520 7093 5521 7094 class ANUnaryExpr(ANDescr): 5522 7095 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 """ 5523 7104 self._arg = arg 5524 7105 self._op = op 5525 7106 self._complex = True … … 5614 7195 return (v, True) 5615 7196 5616 7197 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 """ 5617 7210 return 'other' 5618 7211 5619 7212 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 """ 5620 7229 return self._complex 5621 7230 5622 7231 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 """ 5623 7244 op = self._op 5624 7245 5625 7246 v = self._arg._interval_fast(prec) … … 5665 7286 raise NotImplementedError 5666 7287 5667 7288 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 """ 5668 7300 op = self._op 5669 7301 arg = self._arg 5670 7302 … … 5705 7337 vd = v._descr 5706 7338 vd._exactly_real = True 5707 7339 return vd 5708 7340 5709 7341 if op == 'norm': 5710 7342 arg.exactify() 5711 7343 v = arg * arg.conjugate() … … 5720 7352 5721 7353 class ANBinaryExpr(ANDescr): 5722 7354 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 """ 5723 7363 self._left = left 5724 7364 self._right = right 5725 7365 self._op = op … … 5795 7435 op = self._op 5796 7436 5797 7437 # We want 2+QQbar.zeta(3) and QQbar.zeta(3)+2, not 5798 # QQbar(2)+QQbar.zeta(3). 7438 # QQbar(2)+QQbar.zeta(3). So we want to pass coerced=True to 5799 7439 # an argument if it is rational (but if both arguments are 5800 7440 # rational, we only want to set it for one of them). 5801 7441 … … 5809 7449 5810 7450 arg1_is_qqbar = arg1.parent() is QQbar 5811 7451 arg2_is_qqbar = arg2.parent() is QQbar 5812 7452 5813 7453 result_is_qqbar = \ 5814 7454 (arg1_is_qqbar and not arg1_coerced) or \ 5815 7455 (arg2_is_qqbar and not arg2_coerced) … … 5839 7479 return (v, True) 5840 7480 5841 7481 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 """ 5842 7493 return 'other' 5843 7494 5844 7495 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 """ 5845 7506 return self._complex 5846 7507 5847 7508 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 """ 5848 7520 op = self._op 5849 7521 5850 7522 lv = self._left._interval_fast(prec) … … 5873 7545 5874 7546 sage: rt2c = QQbar.zeta(3) + AA(sqrt(2))  QQbar.zeta(3) 5875 7547 sage: rt2c.exactify() 5876 5877 We check to make sure that this method still works even. 7548 7549 We check to make sure that this method still works even. We 5878 7550 do this by increasing the recursion level at each step and 5879 7551 decrease it before we return:: 5880 7552 … … 5924 7596 # # (Take every other coordinate to get the vertices of a 5925 7597 # # heptadecagon.) 5926 7598 # # Formulas from: 5927 # # Weisstein, Eric W. "Trigonometry AnglesPi/17." From 5928 # # MathWorldA Wolfram Web Resource. 5929 # # http://mathworld.wolfram.com/TrigonometryAnglesPi17.html 7599 # # Weisstein, Eric W. "Trigonometry AnglesPi/17." From 7600 # # MathWorldA Wolfram Web Resource. 7601 # # http://mathworld.wolfram.com/TrigonometryAnglesPi17.html 5930 7602 5931 7603 # rt17 = AA(17).sqrt() 5932 7604 # rt2 = AA(2).sqrt() … … 5953 7625 # # (Take every other coordinate to get the vertices of a 5954 7626 # # heptadecagon.) 5955 7627 # # Formulas from: 5956 # # Weisstein, Eric W. "Heptadecagon." From MathWorldA Wolfram 5957 # # Web Resource. http://mathworld.wolfram.com/Heptadecagon.html 7628 # # Weisstein, Eric W. "Heptadecagon." From MathWorldA Wolfram 7629 # # Web Resource. http://mathworld.wolfram.com/Heptadecagon.html 5958 7630 5959 7631 # 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)) 5960 7632 # y = (1x**2).sqrt() … … 5966 7638 # print cx.sign(), cy.sign() 5967 7639 # print (cx1).sign() 5968 7640 # return x, y 5969 # # heptadecagon2() 7641 # # heptadecagon2() 5970 7642 5971 7643 def _init_qqbar(): 5972 7644 """ 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 5976 7653 """ 5977 7654 global ZZX_x, AA_0, QQbar_I, AA_hash_offset, QQbar_hash_offset, QQbar_I_generator, QQbar_I_nf 5978 7655 global QQ_0, QQ_1, QQ_1_2, QQ_1_4, RR_1_10 5979 7656 5980 7657 RR_1_10 = RR(1)/10 5981 7658 QQ_0 = QQ(0) 5982 7659 QQ_1 = QQ(1) … … 6003 7680 AA_golden_ratio = None 6004 7681 6005 7682 def 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 """ 6006 7692 global AA_golden_ratio 6007 7693 if AA_golden_ratio is None: 6008 7694 AA_golden_ratio_nf = NumberField(ZZX_x**2  ZZX_x  1, 'phi')