rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self._build_code_from_tree(self._tree, d) self._index = dict([(i,e) for i,(e,w) in enumerate(index)]) self._character_to_code = dict([(e,d[i]) for i,(e,w) in enumerate(index)])
self._build_code_from_tree(self._tree, d, prefix="") self._index = dict((i, s) for i, (s, w) in enumerate(dic.items())) self._character_to_code = dict( (s, d[i]) for i, (s, w) in enumerate(dic.items()))
def _build_code(self, dic): r""" Returns a Huffman code for each one of the given elements. INPUT: - ``dic`` (dictionary) -- associates to each letter of the alphabet a frequency or a number of occurrences.
Returns an encoding of the given string based on the current encoding table INPUT: - ``string`` (string) EXAMPLE: This is how a string is encoded then decoded ::
Encode the given string based on the current encoding table. INPUT: - ``string`` -- a string of symbols over an alphabet. OUTPUT: - A Huffman encoding of ``string``. EXAMPLES: This is how a string is encoded and then decoded::
def encode(self, string): r""" Returns an encoding of the given string based on the current encoding table
return join(map(lambda x:self._character_to_code[x],string), '')
return "".join(map(lambda x: self._character_to_code[x], string))
def encode(self, string): r""" Returns an encoding of the given string based on the current encoding table
Returns a decoded version of the given string corresponding to the current encoding table. INPUT: - ``string`` (string) EXAMPLE: This is how a string is encoded then decoded ::
Decode the given string using the current encoding table. INPUT: - ``string`` -- a string of Huffman encodings. OUTPUT: - The Huffman decoding of ``string``. EXAMPLES: This is how a string is encoded and then decoded::
def decode(self, string): r""" Returns a decoded version of the given string corresponding to the current encoding table.
ValueError: The given string does not only contain 0 and 1 """
ValueError: Input must be a binary string. """
def decode(self, string): r""" Returns a decoded version of the given string corresponding to the current encoding table.
if i == '0':
if i == "0":
def decode(self, string): r""" Returns a decoded version of the given string corresponding to the current encoding table.
elif i == '1':
elif i == "1":
def decode(self, string): r""" Returns a decoded version of the given string corresponding to the current encoding table.
raise ValueError('The given string does not only contain 0 and 1') if not isinstance(tree,list):
raise ValueError("Input must be a binary string.") if not isinstance(tree, list):
def decode(self, string): r""" Returns a decoded version of the given string corresponding to the current encoding table.
return join(chars, '')
return "".join(chars)
def decode(self, string): r""" Returns a decoded version of the given string corresponding to the current encoding table.
Returns the current encoding table
Returns the current encoding table. INPUT: - None.
def encoding_table(self): r""" Returns the current encoding table
A dictionary associating its code to each trained letter of the alphabet EXAMPLE:: sage: from sage.coding.source_coding.huffman import Huffman sage: str = "Sage is my most favorite general purpose computer algebra system" sage: h = Huffman(str) sage: h.encoding_table() {'S': '00000', 'a': '1101', ' ': '101', 'c': '110000', 'b': '110001', 'e': '010', 'g': '0001', 'f': '110010', 'i': '10000', 'm': '0011', 'l': '10011', 'o': '0110', 'n': '110011', 'p': '0010', 's': '1110', 'r': '1111', 'u': '10001', 't': '0111', 'v': '00001', 'y': '10010'}
- A dictionary associating an alphabetic symbol to a Huffman encoding. EXAMPLES:: sage: from sage.coding.source_coding.huffman import Huffman sage: str = "Sage is my most favorite general purpose computer algebra system" sage: h = Huffman(str) sage: T = sorted(h.encoding_table().items()) sage: for symbol, code in T: ... print symbol, code ... 101 S 00000 a 1101 b 110001 c 110000 e 010 f 110010 g 0001 i 10000 l 10011 m 0011 n 110011 o 0110 p 0010 r 1111 s 1110 t 0111 u 10001 v 00001 y 10010
def encoding_table(self): r""" Returns the current encoding table
Returns the Huffman tree corresponding to the current encoding
Returns the Huffman tree corresponding to the current encoding. INPUT: - None.
def tree(self): r""" Returns the Huffman tree corresponding to the current encoding
A tree EXAMPLE::
- The binary tree representing a Huffman code. EXAMPLES::
def tree(self): r""" Returns the Huffman tree corresponding to the current encoding
"""
<BLANKLINE> """
def tree(self): r""" Returns the Huffman tree corresponding to the current encoding
def _generate_edges(self, tree, father='', id=''): if father=='': u = 'root'
def _generate_edges(self, tree, parent="", bit=""): """ Generate the edges of the given Huffman tree. INPUT: - ``tree`` -- a Huffman binary tree. - ``parent`` -- (default: empty string) a parent vertex with exactly two children. - ``bit`` -- (default: empty string) the bit signifying either the left or right branch. The bit "0" denotes the left branch and "1" denotes the right branch. OUTPUT: - An edge list of the Huffman binary tree. EXAMPLES:: sage: from sage.coding.source_coding.huffman import Huffman sage: H = Huffman("Sage") sage: T = H.tree() sage: T.edges(labels=None) [('0', 'S: 01'), ('0', 'a: 00'), ('1', 'e: 10'), ('1', 'g: 11'), ('root', '0'), ('root', '1')] """ if parent == "": u = "root"
def _generate_edges(self, tree, father='', id=''): if father=='': u = 'root' else: u = father try: return self._generate_edges(tree[0], father=father+id, id='0') + \ self._generate_edges(tree[1], father=father+id, id='1') + \ ([(u, father+id)] if (father+id) != '' else [])
u = father
u = parent s = "".join([parent, bit])
def _generate_edges(self, tree, father='', id=''): if father=='': u = 'root' else: u = father try: return self._generate_edges(tree[0], father=father+id, id='0') + \ self._generate_edges(tree[1], father=father+id, id='1') + \ ([(u, father+id)] if (father+id) != '' else [])
return self._generate_edges(tree[0], father=father+id, id='0') + \ self._generate_edges(tree[1], father=father+id, id='1') + \ ([(u, father+id)] if (father+id) != '' else [])
left = self._generate_edges(tree[0], parent=s, bit="0") right = self._generate_edges(tree[1], parent=s, bit="1") L = [(u, s)] if s != "" else [] return left + right + L
def _generate_edges(self, tree, father='', id=''): if father=='': u = 'root' else: u = father try: return self._generate_edges(tree[0], father=father+id, id='0') + \ self._generate_edges(tree[1], father=father+id, id='1') + \ ([(u, father+id)] if (father+id) != '' else [])
return [(u, self.decode(father+id)+' : '+(father+id))]
return [(u, "".join([self.decode(s), ": ", s]))]
def _generate_edges(self, tree, father='', id=''): if father=='': u = 'root' else: u = father try: return self._generate_edges(tree[0], father=father+id, id='0') + \ self._generate_edges(tree[1], father=father+id, id='1') + \ ([(u, father+id)] if (father+id) != '' else [])
- ``alphabet`` - (default: (1,2)) any container that is suitable to build an instance of OrderedAlphabet (list, tuple, str, ...)
- ``alphabet`` - (default: (1,2)) an iterable of two positive integers
def KolakoskiWord(self, alphabet=(1,2)): r""" Returns the Kolakoski word over the given alphabet and starting with the first letter of the alphabet.
[1] William Kolakoski, proposal 5304, American Mathematical Monthly 72 (1965), 674; for a partial solution, see "Self Generating Runs," by Necdet Üçoluk, Amer. Math. Mon. 73 (1966), 681-2. """ try: a = int(alphabet[0]) b = int(alphabet[1]) if a <=0 or b <= 0 or a == b: raise ValueError, 'The alphabet (=%s) must consist of two distinct positive integers'%alphabet else: return Words(alphabet)(self._KolakoskiWord_iterator(a, b), datatype = 'iter') except: raise ValueError, 'The elements of the alphabet (=%s) must be positive integers'%alphabet
- [1] William Kolakoski, proposal 5304, American Mathematical Monthly 72 (1965), 674; for a partial solution, see "Self Generating Runs," by Necdet Üçoluk, Amer. Math. Mon. 73 (1966), 681-2. """ a, b = alphabet if a not in ZZ or a <= 0 or b not in ZZ or b <= 0 or a == b: msg = 'The alphabet (=%s) must consist of two distinct positive integers'%(alphabet,) raise ValueError, msg return Words(alphabet)(self._KolakoskiWord_iterator(a, b), datatype = 'iter')
def KolakoskiWord(self, alphabet=(1,2)): r""" Returns the Kolakoski word over the given alphabet and starting with the first letter of the alphabet.
def is_prime(n, flag=0):
def is_prime(n):
def is_prime(n, flag=0): r""" Returns True if `x` is prime, and False otherwise. The result is proven correct - *this is NOT a pseudo-primality test!*. INPUT: - ``flag`` - int - ``0`` (default) - use a combination of algorithms. - ``1`` - certify primality using the Pocklington-Lehmer Test. - ``2`` - certify primality using the APRCL test. OUTPUT: - ``bool`` - True or False .. note:: We do not consider negatives of prime numbers as prime. EXAMPLES:: sage: is_prime(389) True sage: is_prime(2000) False sage: is_prime(2) True sage: is_prime(-1) False sage: factor(-6) -1 * 2 * 3 sage: is_prime(1) False sage: is_prime(-2) False IMPLEMENTATION: Calls the PARI isprime function. """ n = ZZ(n) return pari(n).isprime()
Returns True if `x` is prime, and False otherwise. The result is proven correct - *this is NOT a pseudo-primality test!*. INPUT: - ``flag`` - int - ``0`` (default) - use a combination of algorithms. - ``1`` - certify primality using the Pocklington-Lehmer Test. - ``2`` - certify primality using the APRCL test.
Returns ``True`` if `n` is prime, and ``False`` otherwise. AUTHORS: - Kevin Stueve [email protected] (2010-01-17): delegated calculation to ``n.is_prime()`` INPUT: - ``n`` - the object for which to determine primality
def is_prime(n, flag=0): r""" Returns True if `x` is prime, and False otherwise. The result is proven correct - *this is NOT a pseudo-primality test!*. INPUT: - ``flag`` - int - ``0`` (default) - use a combination of algorithms. - ``1`` - certify primality using the Pocklington-Lehmer Test. - ``2`` - certify primality using the APRCL test. OUTPUT: - ``bool`` - True or False .. note:: We do not consider negatives of prime numbers as prime. EXAMPLES:: sage: is_prime(389) True sage: is_prime(2000) False sage: is_prime(2) True sage: is_prime(-1) False sage: factor(-6) -1 * 2 * 3 sage: is_prime(1) False sage: is_prime(-2) False IMPLEMENTATION: Calls the PARI isprime function. """ n = ZZ(n) return pari(n).isprime()
- ``bool`` - True or False .. note:: We do not consider negatives of prime numbers as prime.
- ``bool`` - ``True`` or ``False``
def is_prime(n, flag=0): r""" Returns True if `x` is prime, and False otherwise. The result is proven correct - *this is NOT a pseudo-primality test!*. INPUT: - ``flag`` - int - ``0`` (default) - use a combination of algorithms. - ``1`` - certify primality using the Pocklington-Lehmer Test. - ``2`` - certify primality using the APRCL test. OUTPUT: - ``bool`` - True or False .. note:: We do not consider negatives of prime numbers as prime. EXAMPLES:: sage: is_prime(389) True sage: is_prime(2000) False sage: is_prime(2) True sage: is_prime(-1) False sage: factor(-6) -1 * 2 * 3 sage: is_prime(1) False sage: is_prime(-2) False IMPLEMENTATION: Calls the PARI isprime function. """ n = ZZ(n) return pari(n).isprime()
IMPLEMENTATION: Calls the PARI isprime function. """ n = ZZ(n) return pari(n).isprime()
ALGORITHM:: Calculation is delegated to the ``n.is_prime()`` method, or in special cases (e.g., Python ``int``s) to ``Integer(n).is_prime()``. If an ``n.is_prime()`` method is not available, it otherwise raises a ``TypeError``. """ if type(n) == int or type(n)==long: from sage.rings.integer import Integer return Integer(n).is_prime() else: try: return n.is_prime() except AttributeError: raise TypeError, "is_prime() is not written for this type"
def is_prime(n, flag=0): r""" Returns True if `x` is prime, and False otherwise. The result is proven correct - *this is NOT a pseudo-primality test!*. INPUT: - ``flag`` - int - ``0`` (default) - use a combination of algorithms. - ``1`` - certify primality using the Pocklington-Lehmer Test. - ``2`` - certify primality using the APRCL test. OUTPUT: - ``bool`` - True or False .. note:: We do not consider negatives of prime numbers as prime. EXAMPLES:: sage: is_prime(389) True sage: is_prime(2000) False sage: is_prime(2) True sage: is_prime(-1) False sage: factor(-6) -1 * 2 * 3 sage: is_prime(1) False sage: is_prime(-2) False IMPLEMENTATION: Calls the PARI isprime function. """ n = ZZ(n) return pari(n).isprime()
return u[0]
return u[0].vector()
def _discrete_log(self,x): # EVEN DUMBER IMPLEMENTATION! u = [y for y in self.list() if y.element() == x] if len(u) == 0: raise TypeError, "Not in group" if len(u) > 1: raise NotImplementedError return u[0]
K = self.base_ring()._magma_init_(magma)
K = magma(self.base_ring())
def _magma_init_(self, magma): r""" EXAMPLES: We first coerce a square matrix. :: sage: magma(MatrixSpace(QQ,3)) # optional - magma Full Matrix Algebra of degree 3 over Rational Field :: sage: magma(MatrixSpace(Integers(8),2,3)) # optional - magma Full RMatrixSpace of 2 by 3 matrices over IntegerRing(8) """ K = self.base_ring()._magma_init_(magma) if self.__nrows == self.__ncols: s = 'MatrixAlgebra(%s,%s)'%(K, self.__nrows) else: s = 'RMatrixSpace(%s,%s,%s)'%(K, self.__nrows, self.__ncols) return s
s = 'MatrixAlgebra(%s,%s)'%(K, self.__nrows)
s = 'MatrixAlgebra(%s,%s)'%(K.name(), self.__nrows)
def _magma_init_(self, magma): r""" EXAMPLES: We first coerce a square matrix. :: sage: magma(MatrixSpace(QQ,3)) # optional - magma Full Matrix Algebra of degree 3 over Rational Field :: sage: magma(MatrixSpace(Integers(8),2,3)) # optional - magma Full RMatrixSpace of 2 by 3 matrices over IntegerRing(8) """ K = self.base_ring()._magma_init_(magma) if self.__nrows == self.__ncols: s = 'MatrixAlgebra(%s,%s)'%(K, self.__nrows) else: s = 'RMatrixSpace(%s,%s,%s)'%(K, self.__nrows, self.__ncols) return s
s = 'RMatrixSpace(%s,%s,%s)'%(K, self.__nrows, self.__ncols)
s = 'RMatrixSpace(%s,%s,%s)'%(K.name(), self.__nrows, self.__ncols)
def _magma_init_(self, magma): r""" EXAMPLES: We first coerce a square matrix. :: sage: magma(MatrixSpace(QQ,3)) # optional - magma Full Matrix Algebra of degree 3 over Rational Field :: sage: magma(MatrixSpace(Integers(8),2,3)) # optional - magma Full RMatrixSpace of 2 by 3 matrices over IntegerRing(8) """ K = self.base_ring()._magma_init_(magma) if self.__nrows == self.__ncols: s = 'MatrixAlgebra(%s,%s)'%(K, self.__nrows) else: s = 'RMatrixSpace(%s,%s,%s)'%(K, self.__nrows, self.__ncols) return s
cones = tuple(tuple(new_fan_rays.index(cone_polytope.vertex(v)) for v in range(cone_polytope.nvertices() - 1))
cones = tuple(tuple(sorted(new_fan_rays.index(cone_polytope.vertex(v)) for v in range(cone_polytope.nvertices() - 1)))
def _subdivide_palp(self, new_rays, verbose): r""" Subdivide ``self`` adding ``new_rays`` one by one.
for cone, polytope in zip(fan.generating_cones(), cone_polytopes): cone._lattice_polytope = polytope
def _subdivide_palp(self, new_rays, verbose): r""" Subdivide ``self`` adding ``new_rays`` one by one.
key = (polynomial, polynomial.base_ring(), name, embedding, embedding.parent() if embedding is not None else None)
key = (polynomial, polynomial.base_ring(), name, latex_name, embedding, embedding.parent() if embedding is not None else None)
def NumberField(polynomial, name=None, check=True, names=None, cache=True, embedding=None, latex_name=None): r""" Return *the* number field defined by the given irreducible polynomial and with variable with the given name. If check is True (the default), also verify that the defining polynomial is irreducible and over `\QQ`. INPUT: - ``polynomial`` - a polynomial over `\QQ` or a number field, or a list of polynomials. - ``name`` - a string (default: 'a'), the name of the generator - ``check`` - bool (default: True); do type checking and irreducibility checking. - ``embedding`` - image of the generator in an ambient field (default: None) EXAMPLES:: sage: z = QQ['z'].0 sage: K = NumberField(z^2 - 2,'s'); K Number Field in s with defining polynomial z^2 - 2 sage: s = K.0; s s sage: s*s 2 sage: s^2 2 Constructing a relative number field:: sage: K.<a> = NumberField(x^2 - 2) sage: R.<t> = K[] sage: L.<b> = K.extension(t^3+t+a); L Number Field in b with defining polynomial t^3 + t + a over its base field sage: L.absolute_field('c') Number Field in c with defining polynomial x^6 + 2*x^4 + x^2 - 2 sage: a*b a*b sage: L(a) a sage: L.lift_to_base(b^3 + b) -a Constructing another number field:: sage: k.<i> = NumberField(x^2 + 1) sage: R.<z> = k[] sage: m.<j> = NumberField(z^3 + i*z + 3) sage: m Number Field in j with defining polynomial z^3 + i*z + 3 over its base field Number fields are globally unique:: sage: K.<a>= NumberField(x^3-5) sage: a^3 5 sage: L.<a>= NumberField(x^3-5) sage: K is L True Having different defining polynomials makes the fields different:: sage: x = polygen(QQ, 'x'); y = polygen(QQ, 'y') sage: k.<a> = NumberField(x^2 + 3) sage: m.<a> = NumberField(y^2 + 3) sage: k Number Field in a with defining polynomial x^2 + 3 sage: m Number Field in a with defining polynomial y^2 + 3 One can also define number fields with specified embeddings, may be used for arithmetic and deduce relations with other number fields which would not be valid for an abstract number field:: sage: K.<a> = NumberField(x^3-2, embedding=1.2) sage: RR.coerce_map_from(K) Composite map: From: Number Field in a with defining polynomial x^3 - 2 To: Real Field with 53 bits of precision Defn: Generic morphism: From: Number Field in a with defining polynomial x^3 - 2 To: Real Lazy Field Defn: a -> 1.259921049894873? then Conversion via _mpfr_ method map: From: Real Lazy Field To: Real Field with 53 bits of precision sage: RR(a) 1.25992104989487 sage: 1.1 + a 2.35992104989487 sage: b = 1/(a+1); b 1/3*a^2 - 1/3*a + 1/3 sage: RR(b) 0.442493334024442 sage: L.<b> = NumberField(x^6-2, embedding=1.1) sage: L(a) b^2 sage: a + b b^2 + b Note that the image only needs to be specified to enough precision to distinguish roots, and is exactly computed to any needed precision:: sage: RealField(200)(a) 1.2599210498948731647672106072782283505702514647015079800820 One can embed into any other field:: sage: K.<a> = NumberField(x^3-2, embedding=CC.gen()-0.6) sage: CC(a) -0.629960524947436 + 1.09112363597172*I sage: L = Qp(5) sage: f = polygen(L)^3 - 2 sage: K.<a> = NumberField(x^3-2, embedding=f.roots()[0][0]) sage: a + L(1) 4 + 2*5^2 + 2*5^3 + 3*5^4 + 5^5 + 4*5^6 + 2*5^8 + 3*5^9 + 4*5^12 + 4*5^14 + 4*5^15 + 3*5^16 + 5^17 + 5^18 + 2*5^19 + O(5^20) sage: L.<b> = NumberField(x^6-x^2+1/10, embedding=1) sage: K.<a> = NumberField(x^3-x+1/10, embedding=b^2) sage: a+b b^2 + b sage: CC(a) == CC(b)^2 True sage: K.coerce_embedding() Generic morphism: From: Number Field in a with defining polynomial x^3 - x + 1/10 To: Number Field in b with defining polynomial x^6 - x^2 + 1/10 Defn: a -> b^2 The ``QuadraticField`` and ``CyclotomicField`` constructors create an embedding by default unless otherwise specified. :: sage: K.<zeta> = CyclotomicField(15) sage: CC(zeta) 0.913545457642601 + 0.406736643075800*I sage: L.<sqrtn3> = QuadraticField(-3) sage: K(sqrtn3) 2*zeta^5 + 1 sage: sqrtn3 + zeta 2*zeta^5 + zeta + 1 An example involving a variable name that defines a function in PARI:: sage: theta = polygen(QQ, 'theta') sage: M.<z> = NumberField([theta^3 + 4, theta^2 + 3]); M Number Field in z0 with defining polynomial theta^3 + 4 over its base field TESTS:: sage: x = QQ['x'].gen() sage: y = ZZ['y'].gen() sage: K = NumberField(x^3 + x + 3, 'a'); K Number Field in a with defining polynomial x^3 + x + 3 sage: K.defining_polynomial().parent() Univariate Polynomial Ring in x over Rational Field :: sage: L = NumberField(y^3 + y + 3, 'a'); L Number Field in a with defining polynomial y^3 + y + 3 sage: L.defining_polynomial().parent() Univariate Polynomial Ring in y over Rational Field :: sage: sage.rings.number_field.number_field._nf_cache = {} sage: K.<x> = CyclotomicField(5)[] sage: W.<a> = NumberField(x^2 + 1); W Number Field in a with defining polynomial x^2 + 1 over its base field sage: sage.rings.number_field.number_field._nf_cache = {} sage: W1 = NumberField(x^2+1,'a') sage: K.<x> = CyclotomicField(5)[] sage: W.<a> = NumberField(x^2 + 1); W Number Field in a with defining polynomial x^2 + 1 over its base field """ if name is None and names is None: raise TypeError, "You must specify the name of the generator." if not names is None: name = names if isinstance(polynomial, (list, tuple)): return NumberFieldTower(polynomial, name) name = sage.structure.parent_gens.normalize_names(1, name) if not isinstance(polynomial, polynomial_element.Polynomial): try: polynomial = polynomial.polynomial(QQ) except (AttributeError, TypeError): raise TypeError, "polynomial (=%s) must be a polynomial."%repr(polynomial) # convert ZZ to QQ R = polynomial.base_ring() Q = polynomial.parent().base_extend(R.fraction_field()) polynomial = Q(polynomial) if cache: key = (polynomial, polynomial.base_ring(), name, embedding, embedding.parent() if embedding is not None else None) if _nf_cache.has_key(key): K = _nf_cache[key]() if not K is None: return K if isinstance(R, NumberField_generic): S = R.extension(polynomial, name, check=check) if cache: _nf_cache[key] = weakref.ref(S) return S if polynomial.degree() == 2: K = NumberField_quadratic(polynomial, name, latex_name, check, embedding) else: K = NumberField_absolute(polynomial, name, latex_name, check, embedding) if cache: _nf_cache[key] = weakref.ref(K) return K
def QuadraticField(D, names, check=True, embedding=True, latex_name=None):
def QuadraticField(D, names, check=True, embedding=True, latex_name='sqrt'):
def QuadraticField(D, names, check=True, embedding=True, latex_name=None): r""" Return a quadratic field obtained by adjoining a square root of `D` to the rational numbers, where `D` is not a perfect square. INPUT: - ``D`` - a rational number - ``names`` - variable name - ``check`` - bool (default: True) - ``embedding`` - bool or square root of D in an ambient field (default: True) OUTPUT: A number field defined by a quadratic polynomial. Unless otherwise specified, it has an embedding into `\RR` or `\CC` by sending the generator to the positive root. EXAMPLES:: sage: QuadraticField(3, 'a') Number Field in a with defining polynomial x^2 - 3 sage: K.<theta> = QuadraticField(3); K Number Field in theta with defining polynomial x^2 - 3 sage: RR(theta) 1.73205080756888 sage: QuadraticField(9, 'a') Traceback (most recent call last): ... ValueError: D must not be a perfect square. sage: QuadraticField(9, 'a', check=False) Number Field in a with defining polynomial x^2 - 9 Quadratic number fields derive from general number fields. :: sage: from sage.rings.number_field.number_field import is_NumberField sage: type(K) <class 'sage.rings.number_field.number_field.NumberField_quadratic_with_category'> sage: is_NumberField(K) True Quadratic number fields are cached:: sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a') True We can give the generator a special name for latex:: sage: K.<a> = QuadraticField(next_prime(10^10), latex_name=r'\sqrt{D}') sage: 1+a a + 1 sage: latex(1+a) \sqrt{D} + 1 """ D = QQ(D) if check: if D.is_square(): raise ValueError, "D must not be a perfect square." R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: if D > 0: embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() return NumberField(f, names, check=False, embedding=embedding, latex_name=latex_name)
root.
or upper half plane root.
def QuadraticField(D, names, check=True, embedding=True, latex_name=None): r""" Return a quadratic field obtained by adjoining a square root of `D` to the rational numbers, where `D` is not a perfect square. INPUT: - ``D`` - a rational number - ``names`` - variable name - ``check`` - bool (default: True) - ``embedding`` - bool or square root of D in an ambient field (default: True) OUTPUT: A number field defined by a quadratic polynomial. Unless otherwise specified, it has an embedding into `\RR` or `\CC` by sending the generator to the positive root. EXAMPLES:: sage: QuadraticField(3, 'a') Number Field in a with defining polynomial x^2 - 3 sage: K.<theta> = QuadraticField(3); K Number Field in theta with defining polynomial x^2 - 3 sage: RR(theta) 1.73205080756888 sage: QuadraticField(9, 'a') Traceback (most recent call last): ... ValueError: D must not be a perfect square. sage: QuadraticField(9, 'a', check=False) Number Field in a with defining polynomial x^2 - 9 Quadratic number fields derive from general number fields. :: sage: from sage.rings.number_field.number_field import is_NumberField sage: type(K) <class 'sage.rings.number_field.number_field.NumberField_quadratic_with_category'> sage: is_NumberField(K) True Quadratic number fields are cached:: sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a') True We can give the generator a special name for latex:: sage: K.<a> = QuadraticField(next_prime(10^10), latex_name=r'\sqrt{D}') sage: 1+a a + 1 sage: latex(1+a) \sqrt{D} + 1 """ D = QQ(D) if check: if D.is_square(): raise ValueError, "D must not be a perfect square." R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: if D > 0: embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() return NumberField(f, names, check=False, embedding=embedding, latex_name=latex_name)
We can give the generator a special name for latex::
By default, quadratic fields come with a nice latex representation:: sage: K.<a> = QuadraticField(-7) sage: latex(a) \sqrt{-7} sage: latex(1/(1+a)) -\frac{1}{8} \sqrt{-7} + \frac{1}{8} sage: K.latex_variable_name() '\\sqrt{-7}' We can provide our own name as well::
def QuadraticField(D, names, check=True, embedding=True, latex_name=None): r""" Return a quadratic field obtained by adjoining a square root of `D` to the rational numbers, where `D` is not a perfect square. INPUT: - ``D`` - a rational number - ``names`` - variable name - ``check`` - bool (default: True) - ``embedding`` - bool or square root of D in an ambient field (default: True) OUTPUT: A number field defined by a quadratic polynomial. Unless otherwise specified, it has an embedding into `\RR` or `\CC` by sending the generator to the positive root. EXAMPLES:: sage: QuadraticField(3, 'a') Number Field in a with defining polynomial x^2 - 3 sage: K.<theta> = QuadraticField(3); K Number Field in theta with defining polynomial x^2 - 3 sage: RR(theta) 1.73205080756888 sage: QuadraticField(9, 'a') Traceback (most recent call last): ... ValueError: D must not be a perfect square. sage: QuadraticField(9, 'a', check=False) Number Field in a with defining polynomial x^2 - 9 Quadratic number fields derive from general number fields. :: sage: from sage.rings.number_field.number_field import is_NumberField sage: type(K) <class 'sage.rings.number_field.number_field.NumberField_quadratic_with_category'> sage: is_NumberField(K) True Quadratic number fields are cached:: sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a') True We can give the generator a special name for latex:: sage: K.<a> = QuadraticField(next_prime(10^10), latex_name=r'\sqrt{D}') sage: 1+a a + 1 sage: latex(1+a) \sqrt{D} + 1 """ D = QQ(D) if check: if D.is_square(): raise ValueError, "D must not be a perfect square." R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: if D > 0: embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() return NumberField(f, names, check=False, embedding=embedding, latex_name=latex_name)
Returns the rim of ``self``
Returns the rim of ``self``.
def rim(self): r""" Returns the rim of ``self``
For example if `p=(5,5,2,1)`, the rim is composed from the dashed cells below::
The rim of the partition `[5,5,2,1]` consists of the cells marked with ``
def rim(self): r""" Returns the rim of ``self``
Returns the outer rim of ``self``
Returns the outer rim of ``self``.
def outer_rim(self): """ Returns the outer rim of ``self``
For example, the dashed cell below is the outer_rim of the partitions `(4,1)`::
The outer rim of the partition `[4,1]` consists of the cells marked with ``
def outer_rim(self): """ Returns the outer rim of ``self``
solution is not SymbolisEquation (as happens for example for
solution is not SymbolicEquation (as happens for example for
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): """ Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx`` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` initial conditions gives error if the solution is not SymbolisEquation (as happens for example for clairot equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairot, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) sage: f(x=10) 2 sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) dvar_str=dvar.operator()._maxima_().str() ivar_str=ivar._maxima_().str() de00 = de._maxima_().str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = maxima(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" maxima("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=maxima("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): raise NotImplementedError, "Maxima was unable to use initial condition for this equation (%s)"%(maxima_method.str()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+(ics[2])._maxima_().str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial contition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,(ivar==ics[0])._maxima_().str(),dvar_str,(ics[1])._maxima_().str(),(ivar==ics[2])._maxima_().str(),dvar_str,(ics[3])._maxima_().str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial contition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
"""
r"""
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2])
- ``de`` - a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") - ``vars`` - a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) - ``ics`` - a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2])
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES:
The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES::
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
AUTHORS: David Joyner (3-2006, 8-2007)
AUTHORS: - David Joyner (3-2006, 8-2007)
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
"""
r"""
def eulers_method(f,x0,y0,h,x1,method="table"): """ This implements Euler's method for finding numerically the solution of the 1st order ODE ``y' = f(x,y)``, ``y(a)=c``. The "x" column of the table increments from ``x0`` to ``x1`` by ``h`` (so ``(x1-x0)/h`` must be an integer). In the "y" column, the new y-value equals the old y-value plus the corresponding entry in the last column. *For pedagogical purposes only.* EXAMPLES:: sage: from sage.calculus.desolvers import eulers_method sage: x,y = PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1) x y h*f(x,y) 0 1 -2 1/2 -1 -7/4 1 -11/4 -11/8 :: sage: x,y = PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1,method="none") [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]] :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: x,y = PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1,method="None") [[0, 1], [1/2, -1.0], [1, -2.7], [3/2, -4.0]] :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: x,y=PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1) x y h*f(x,y) 0 1 -2.0 1/2 -1.0 -1.7 1 -2.7 -1.3 :: sage: x,y=PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,1,1,1/3,2) x y h*f(x,y) 1 1 1/3 4/3 4/3 1 5/3 7/3 17/9 2 38/9 83/27 :: sage: eulers_method(5*x+y-5,0,1,1/2,1,method="none") [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]] :: sage: pts = eulers_method(5*x+y-5,0,1,1/2,1,method="none") sage: P1 = list_plot(pts) sage: P2 = line(pts) sage: (P1+P2).show() AUTHORS: - David Joyner """ if method=="table": print "%10s %20s %25s"%("x","y","h*f(x,y)") n=int((1.0)*(x1-x0)/h) x00=x0; y00=y0 soln = [[x00,y00]] for i in range(n+1): if method=="table": print "%10r %20r %20r"%(x00,y00,h*f(x00,y00)) y00 = y00+h*f(x00,y00) x00=x00+h soln.append([x00,y00]) if method!="table": return soln
"""
r"""
def eulers_method_2x2(f,g, t0, x0, y0, h, t1,method="table"): """ This implements Euler's method for finding numerically the solution of the 1st order system of two ODEs ``x' = f(t, x, y), x(t0)=x0.`` ``y' = g(t, x, y), y(t0)=y0.`` The "t" column of the table increments from `t_0` to `t_1` by `h` (so `\\frac{t_1-t_0}{h}` must be an integer). In the "x" column, the new x-value equals the old x-value plus the corresponding entry in the next (third) column. In the "y" column, the new y-value equals the old y-value plus the corresponding entry in the next (last) column. *For pedagogical purposes only.* EXAMPLES:: sage: from sage.calculus.desolvers import eulers_method_2x2 sage: t, x, y = PolynomialRing(QQ,3,"txy").gens() sage: f = x+y+t; g = x-y sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1,method="none") [[0, 0, 0], [1/3, 0, 0], [2/3, 1/9, 0], [1, 10/27, 1/27], [4/3, 68/81, 4/27]] :: sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 0 0 0 0 1/3 0 1/9 0 0 2/3 1/9 7/27 0 1/27 1 10/27 38/81 1/27 1/9 :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: t,x,y=PolynomialRing(RR,3,"txy").gens() sage: f = x+y+t; g = x-y sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 0 0.00 0 0.00 1/3 0.00 0.13 0.00 0.00 2/3 0.13 0.29 0.00 0.043 1 0.41 0.57 0.043 0.15 To numerically approximate `y(1)`, where `(1+t^2)y''+y'-y=0`, `y(0)=1`, `y'(0)=-1`, using 4 steps of Euler's method, first convert to a system: `y_1' = y_2`, `y_1(0)=1`; `y_2' = \\frac{y_1-y_2}{1+t^2}`, `y_2(0)=-1`.:: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: t, x, y=PolynomialRing(RR,3,"txy").gens() sage: f = y; g = (x-y)/(1+t^2) sage: eulers_method_2x2(f,g, 0, 1, -1, 1/4, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 1 -0.25 -1 0.50 1/4 0.75 -0.12 -0.50 0.29 1/2 0.63 -0.054 -0.21 0.19 3/4 0.63 -0.0078 -0.031 0.11 1 0.63 0.020 0.079 0.071 To numerically approximate y(1), where `y''+ty'+y=0`, `y(0)=1`, `y'(0)=0`:: sage: t,x,y=PolynomialRing(RR,3,"txy").gens() sage: f = y; g = -x-y*t sage: eulers_method_2x2(f,g, 0, 1, 0, 1/4, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 1 0.00 0 -0.25 1/4 1.0 -0.062 -0.25 -0.23 1/2 0.94 -0.11 -0.46 -0.17 3/4 0.88 -0.15 -0.62 -0.10 1 0.75 -0.17 -0.68 -0.015 AUTHORS: - David Joyner """ if method=="table": print "%10s %20s %25s %20s %20s"%("t", "x","h*f(t,x,y)","y", "h*g(t,x,y)") n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): if method=="table": print "%10r %20r %25r %20r %20r"%(t00,x00,h*f(t00,x00,y00),y00,h*g(t00,x00,y00)) x01 = x00 + h*f(t00,x00,y00) y00 = y00 + h*g(t00,x00,y00) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) if method!="table": return soln
"""
r""" Plots solution of ODE
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
`\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) =
`\theta''+\sin(\theta)=0`, `\theta(0)=\frac 34`, `\theta'(0) =
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot
``(P[0]+P[1]).show()`` to plot `(t,\theta(t))` and `(t,\theta'(t))`::
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
if self._style == "coroots" and all(xv in ZZ for xv in x):
if self._style == "coroots" and isinstance(x, tuple) and all(xv in ZZ for xv in x):
def __call__(self, *args): """ Coerces the element into the ring. You may pass a vector in the ambient space, an element of the base_ring, or an argument list of integers (or half-integers for the spin types) which are the components of a vector in the ambient space. INPUT: - ``x`` - a ring element to be coerced; or - ``*args`` - the components of a vector EXAMPLES:: sage: A2 = WeylCharacterRing("A2") sage: [A2(x) for x in [-2,-1,0,1,2]] [-2*A2(0,0,0), -A2(0,0,0), 0, A2(0,0,0), 2*A2(0,0,0)] sage: [A2(2,1,0), A2([2,1,0]), A2(2,1,0)== A2([2,1,0])] [A2(2,1,0), A2(2,1,0), True] sage: A2([2,1,0]) == A2(2,1,0) True sage: l = -2*A2(0,0,0) - A2(1,0,0) + A2(2,0,0) + 2*A2(3,0,0) sage: [l in A2, A2(l) == l] [True, True] sage: P.<q> = QQ[] sage: A2 = WeylCharacterRing(['A',2], base_ring = P) sage: [A2(x) for x in [-2,-1,0,1,2,-2*q,-q,q,2*q,(1-q)]] [-2*A2(0,0,0), -A2(0,0,0), 0, A2(0,0,0), 2*A2(0,0,0), -2*q*A2(0,0,0), -q*A2(0,0,0), q*A2(0,0,0), 2*q*A2(0,0,0), (-q+1)*A2(0,0,0)] """ if len(args) == 1: x = args[0] else: x = args
A stochastic matrix is a matrix such that the sum of the elements of any row is equal to 1. A bistochastic matrix is a stochastic matrix whose transpose matrix is also stochastic ( there are conditions both on the rows and on the columns ).
A stochastic matrix is a matrix with nonnegative real entries such that the sum of the elements of any row is equal to 1. A bistochastic matrix is a stochastic matrix whose transpose matrix is also stochastic ( there are conditions both on the rows and on the columns ).
def bistochastic_as_sum_of_permutations(M, check = True): r""" Returns the positive sum of permutations corresponding to the bistochastic matrix. A stochastic matrix is a matrix such that the sum of the elements of any row is equal to 1. A bistochastic matrix is a stochastic matrix whose transpose matrix is also stochastic ( there are conditions both on the rows and on the columns ). According to the Birkhoff-von Neumann Theorem, any bistochastic matrix can be written as a positive sum of permutation matrices, which also means that the polytope of bistochastic matrices is integer. As a non-bistochastic matrix can obviously not be written as a sum of permutations, this theorem is an equivalence. This function, given a bistochastic matrix, returns the corresponding decomposition. INPUT: - ``M`` -- A bistochastic matrix - ``check`` (boolean) -- set to ``True`` (default) to checl that the matrix is indeed bistochastic OUTPUT: - An element of ``CombinatorialFreeModule``, which is a free `F`-module ( where `F` is the ground ring of the given matrix ) whose basis is indexed by the permutations. .. NOTE:: - In this function, we just assume 1 to be any constant : for us a matrix M is bistochastic if there exists `c>0` such that `M/c` is bistochastic. - You can obtain a sequence of pairs ``(permutation,coeff)``, where ``permutation` is a Sage ``Permutation`` instance, and ``coeff`` its corresponding coefficient from the result of this function by applying the ``list`` function. - If you are interested in the matrix corresponding to a ``Permutation`` you will be glad to learn about the ``Permutation.to_matrix()`` method. - The base ring of the matrix can be anything that can be coerced to ``RR``. .. SEEALSO: - :meth:`as_sum_of_permutations <sage.matrix.matrix2.as_sum_of_permutations>` -- to use this method through the ``Matrix`` class. EXAMPLE: We create a bistochastic matrix from a convex sum of permutations, then try to deduce the decomposition from the matrix :: sage: from sage.combinat.permutation import bistochastic_as_sum_of_permutations sage: L = [] sage: L.append((9,Permutation([4, 1, 3, 5, 2]))) sage: L.append((6,Permutation([5, 3, 4, 1, 2]))) sage: L.append((3,Permutation([3, 1, 4, 2, 5]))) sage: L.append((2,Permutation([1, 4, 2, 3, 5]))) sage: M = sum([c * p.to_matrix() for (c,p) in L]) sage: decomp = bistochastic_as_sum_of_permutations(M) sage: print decomp 2*B[[1, 4, 2, 3, 5]] + 3*B[[3, 1, 4, 2, 5]] + 9*B[[4, 1, 3, 5, 2]] + 6*B[[5, 3, 4, 1, 2]] An exception is raised when the matrix is not bistochastic:: sage: M = Matrix([[2,3],[2,2]]) sage: decomp = bistochastic_as_sum_of_permutations(M) Traceback (most recent call last): ... ValueError: The matrix is not bistochastic """ from sage.graphs.bipartite_graph import BipartiteGraph from sage.combinat.free_module import CombinatorialFreeModule from sage.rings.real_mpfr import RR n=M.nrows() if n != M.ncols(): raise ValueError("The matrix is expected to be square") if check and not M.is_bistochastic(normalized = False): raise ValueError("The matrix is not bistochastic") if not RR.has_coerce_map_from(M.base_ring()): raise ValueError("The base ring of the matrix must have a coercion map to RR") CFM=CombinatorialFreeModule(M.base_ring(),Permutations(n)) value=0 G = BipartiteGraph(M,weighted=True) while G.size() > 0: matching = G.matching(use_edge_labels=True) # This minimum is strictly larger than 0 minimum = min([x[2] for x in matching]) for (u,v,l) in matching: if minimum == l: G.delete_edge((u,v,l)) else: G.set_edge_label(u,v,l-minimum) matching.sort(key=lambda x: x[0]) value+=minimum*CFM(Permutation([x[1]-n+1 for x in matching])) return value
- ``check`` (boolean) -- set to ``True`` (default) to checl
- ``check`` (boolean) -- set to ``True`` (default) to check
def bistochastic_as_sum_of_permutations(M, check = True): r""" Returns the positive sum of permutations corresponding to the bistochastic matrix. A stochastic matrix is a matrix such that the sum of the elements of any row is equal to 1. A bistochastic matrix is a stochastic matrix whose transpose matrix is also stochastic ( there are conditions both on the rows and on the columns ). According to the Birkhoff-von Neumann Theorem, any bistochastic matrix can be written as a positive sum of permutation matrices, which also means that the polytope of bistochastic matrices is integer. As a non-bistochastic matrix can obviously not be written as a sum of permutations, this theorem is an equivalence. This function, given a bistochastic matrix, returns the corresponding decomposition. INPUT: - ``M`` -- A bistochastic matrix - ``check`` (boolean) -- set to ``True`` (default) to checl that the matrix is indeed bistochastic OUTPUT: - An element of ``CombinatorialFreeModule``, which is a free `F`-module ( where `F` is the ground ring of the given matrix ) whose basis is indexed by the permutations. .. NOTE:: - In this function, we just assume 1 to be any constant : for us a matrix M is bistochastic if there exists `c>0` such that `M/c` is bistochastic. - You can obtain a sequence of pairs ``(permutation,coeff)``, where ``permutation` is a Sage ``Permutation`` instance, and ``coeff`` its corresponding coefficient from the result of this function by applying the ``list`` function. - If you are interested in the matrix corresponding to a ``Permutation`` you will be glad to learn about the ``Permutation.to_matrix()`` method. - The base ring of the matrix can be anything that can be coerced to ``RR``. .. SEEALSO: - :meth:`as_sum_of_permutations <sage.matrix.matrix2.as_sum_of_permutations>` -- to use this method through the ``Matrix`` class. EXAMPLE: We create a bistochastic matrix from a convex sum of permutations, then try to deduce the decomposition from the matrix :: sage: from sage.combinat.permutation import bistochastic_as_sum_of_permutations sage: L = [] sage: L.append((9,Permutation([4, 1, 3, 5, 2]))) sage: L.append((6,Permutation([5, 3, 4, 1, 2]))) sage: L.append((3,Permutation([3, 1, 4, 2, 5]))) sage: L.append((2,Permutation([1, 4, 2, 3, 5]))) sage: M = sum([c * p.to_matrix() for (c,p) in L]) sage: decomp = bistochastic_as_sum_of_permutations(M) sage: print decomp 2*B[[1, 4, 2, 3, 5]] + 3*B[[3, 1, 4, 2, 5]] + 9*B[[4, 1, 3, 5, 2]] + 6*B[[5, 3, 4, 1, 2]] An exception is raised when the matrix is not bistochastic:: sage: M = Matrix([[2,3],[2,2]]) sage: decomp = bistochastic_as_sum_of_permutations(M) Traceback (most recent call last): ... ValueError: The matrix is not bistochastic """ from sage.graphs.bipartite_graph import BipartiteGraph from sage.combinat.free_module import CombinatorialFreeModule from sage.rings.real_mpfr import RR n=M.nrows() if n != M.ncols(): raise ValueError("The matrix is expected to be square") if check and not M.is_bistochastic(normalized = False): raise ValueError("The matrix is not bistochastic") if not RR.has_coerce_map_from(M.base_ring()): raise ValueError("The base ring of the matrix must have a coercion map to RR") CFM=CombinatorialFreeModule(M.base_ring(),Permutations(n)) value=0 G = BipartiteGraph(M,weighted=True) while G.size() > 0: matching = G.matching(use_edge_labels=True) # This minimum is strictly larger than 0 minimum = min([x[2] for x in matching]) for (u,v,l) in matching: if minimum == l: G.delete_edge((u,v,l)) else: G.set_edge_label(u,v,l-minimum) matching.sort(key=lambda x: x[0]) value+=minimum*CFM(Permutation([x[1]-n+1 for x in matching])) return value
An exception is raised when the matrix is not bistochastic::
An exception is raised when the matrix is not positive and bistochastic::
def bistochastic_as_sum_of_permutations(M, check = True): r""" Returns the positive sum of permutations corresponding to the bistochastic matrix. A stochastic matrix is a matrix such that the sum of the elements of any row is equal to 1. A bistochastic matrix is a stochastic matrix whose transpose matrix is also stochastic ( there are conditions both on the rows and on the columns ). According to the Birkhoff-von Neumann Theorem, any bistochastic matrix can be written as a positive sum of permutation matrices, which also means that the polytope of bistochastic matrices is integer. As a non-bistochastic matrix can obviously not be written as a sum of permutations, this theorem is an equivalence. This function, given a bistochastic matrix, returns the corresponding decomposition. INPUT: - ``M`` -- A bistochastic matrix - ``check`` (boolean) -- set to ``True`` (default) to checl that the matrix is indeed bistochastic OUTPUT: - An element of ``CombinatorialFreeModule``, which is a free `F`-module ( where `F` is the ground ring of the given matrix ) whose basis is indexed by the permutations. .. NOTE:: - In this function, we just assume 1 to be any constant : for us a matrix M is bistochastic if there exists `c>0` such that `M/c` is bistochastic. - You can obtain a sequence of pairs ``(permutation,coeff)``, where ``permutation` is a Sage ``Permutation`` instance, and ``coeff`` its corresponding coefficient from the result of this function by applying the ``list`` function. - If you are interested in the matrix corresponding to a ``Permutation`` you will be glad to learn about the ``Permutation.to_matrix()`` method. - The base ring of the matrix can be anything that can be coerced to ``RR``. .. SEEALSO: - :meth:`as_sum_of_permutations <sage.matrix.matrix2.as_sum_of_permutations>` -- to use this method through the ``Matrix`` class. EXAMPLE: We create a bistochastic matrix from a convex sum of permutations, then try to deduce the decomposition from the matrix :: sage: from sage.combinat.permutation import bistochastic_as_sum_of_permutations sage: L = [] sage: L.append((9,Permutation([4, 1, 3, 5, 2]))) sage: L.append((6,Permutation([5, 3, 4, 1, 2]))) sage: L.append((3,Permutation([3, 1, 4, 2, 5]))) sage: L.append((2,Permutation([1, 4, 2, 3, 5]))) sage: M = sum([c * p.to_matrix() for (c,p) in L]) sage: decomp = bistochastic_as_sum_of_permutations(M) sage: print decomp 2*B[[1, 4, 2, 3, 5]] + 3*B[[3, 1, 4, 2, 5]] + 9*B[[4, 1, 3, 5, 2]] + 6*B[[5, 3, 4, 1, 2]] An exception is raised when the matrix is not bistochastic:: sage: M = Matrix([[2,3],[2,2]]) sage: decomp = bistochastic_as_sum_of_permutations(M) Traceback (most recent call last): ... ValueError: The matrix is not bistochastic """ from sage.graphs.bipartite_graph import BipartiteGraph from sage.combinat.free_module import CombinatorialFreeModule from sage.rings.real_mpfr import RR n=M.nrows() if n != M.ncols(): raise ValueError("The matrix is expected to be square") if check and not M.is_bistochastic(normalized = False): raise ValueError("The matrix is not bistochastic") if not RR.has_coerce_map_from(M.base_ring()): raise ValueError("The base ring of the matrix must have a coercion map to RR") CFM=CombinatorialFreeModule(M.base_ring(),Permutations(n)) value=0 G = BipartiteGraph(M,weighted=True) while G.size() > 0: matching = G.matching(use_edge_labels=True) # This minimum is strictly larger than 0 minimum = min([x[2] for x in matching]) for (u,v,l) in matching: if minimum == l: G.delete_edge((u,v,l)) else: G.set_edge_label(u,v,l-minimum) matching.sort(key=lambda x: x[0]) value+=minimum*CFM(Permutation([x[1]-n+1 for x in matching])) return value
from sage.rings.real_mpfr import RR
from sage.rings.all import RR
def bistochastic_as_sum_of_permutations(M, check = True): r""" Returns the positive sum of permutations corresponding to the bistochastic matrix. A stochastic matrix is a matrix such that the sum of the elements of any row is equal to 1. A bistochastic matrix is a stochastic matrix whose transpose matrix is also stochastic ( there are conditions both on the rows and on the columns ). According to the Birkhoff-von Neumann Theorem, any bistochastic matrix can be written as a positive sum of permutation matrices, which also means that the polytope of bistochastic matrices is integer. As a non-bistochastic matrix can obviously not be written as a sum of permutations, this theorem is an equivalence. This function, given a bistochastic matrix, returns the corresponding decomposition. INPUT: - ``M`` -- A bistochastic matrix - ``check`` (boolean) -- set to ``True`` (default) to checl that the matrix is indeed bistochastic OUTPUT: - An element of ``CombinatorialFreeModule``, which is a free `F`-module ( where `F` is the ground ring of the given matrix ) whose basis is indexed by the permutations. .. NOTE:: - In this function, we just assume 1 to be any constant : for us a matrix M is bistochastic if there exists `c>0` such that `M/c` is bistochastic. - You can obtain a sequence of pairs ``(permutation,coeff)``, where ``permutation` is a Sage ``Permutation`` instance, and ``coeff`` its corresponding coefficient from the result of this function by applying the ``list`` function. - If you are interested in the matrix corresponding to a ``Permutation`` you will be glad to learn about the ``Permutation.to_matrix()`` method. - The base ring of the matrix can be anything that can be coerced to ``RR``. .. SEEALSO: - :meth:`as_sum_of_permutations <sage.matrix.matrix2.as_sum_of_permutations>` -- to use this method through the ``Matrix`` class. EXAMPLE: We create a bistochastic matrix from a convex sum of permutations, then try to deduce the decomposition from the matrix :: sage: from sage.combinat.permutation import bistochastic_as_sum_of_permutations sage: L = [] sage: L.append((9,Permutation([4, 1, 3, 5, 2]))) sage: L.append((6,Permutation([5, 3, 4, 1, 2]))) sage: L.append((3,Permutation([3, 1, 4, 2, 5]))) sage: L.append((2,Permutation([1, 4, 2, 3, 5]))) sage: M = sum([c * p.to_matrix() for (c,p) in L]) sage: decomp = bistochastic_as_sum_of_permutations(M) sage: print decomp 2*B[[1, 4, 2, 3, 5]] + 3*B[[3, 1, 4, 2, 5]] + 9*B[[4, 1, 3, 5, 2]] + 6*B[[5, 3, 4, 1, 2]] An exception is raised when the matrix is not bistochastic:: sage: M = Matrix([[2,3],[2,2]]) sage: decomp = bistochastic_as_sum_of_permutations(M) Traceback (most recent call last): ... ValueError: The matrix is not bistochastic """ from sage.graphs.bipartite_graph import BipartiteGraph from sage.combinat.free_module import CombinatorialFreeModule from sage.rings.real_mpfr import RR n=M.nrows() if n != M.ncols(): raise ValueError("The matrix is expected to be square") if check and not M.is_bistochastic(normalized = False): raise ValueError("The matrix is not bistochastic") if not RR.has_coerce_map_from(M.base_ring()): raise ValueError("The base ring of the matrix must have a coercion map to RR") CFM=CombinatorialFreeModule(M.base_ring(),Permutations(n)) value=0 G = BipartiteGraph(M,weighted=True) while G.size() > 0: matching = G.matching(use_edge_labels=True) # This minimum is strictly larger than 0 minimum = min([x[2] for x in matching]) for (u,v,l) in matching: if minimum == l: G.delete_edge((u,v,l)) else: G.set_edge_label(u,v,l-minimum) matching.sort(key=lambda x: x[0]) value+=minimum*CFM(Permutation([x[1]-n+1 for x in matching])) return value
approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise.
approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits of `z` with ``known_bits=k`` or ``known_digits=k``. PARI is then told to compute the result using `0.8k` of these bits/digits. Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may be specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polynomial is not found, then ``None`` will be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library ``algdep`` command otherwise.
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
- ``height_bound`` - an integer (default ``None``) specifying the maximum
- ``height_bound`` - an integer (default: ``None``) specifying the maximum
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
- ``proof`` - a boolean (default ``False``), requres height_bound to be set
- ``proof`` - a boolean (default: ``False``), requires height_bound to be set
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
This example involves a complex number. ::
This example involves a complex number::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
This example involves a `p`-adic number. ::
This example involves a `p`-adic number::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. ::
compute a 200-bit approximation to `sqrt(2)` which is wrong in the 33'rd bit::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. ::
Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
For stronger results, we need more precicion. ::
For stronger results, we need more precicion::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
We can also use ``proof=True`` to get positive results. ::
We can also use ``proof=True`` to get positive results::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
- ``bound (default 1024)`` - int: highest power to test.
- ``bound (default: 1024)`` - int: highest power to test.
def is_pseudoprime_small_power(n, bound=1024, get_data=False): r""" Return True if `n` is a small power of a pseudoprime, and False otherwise. The result is *NOT* proven correct - *this IS a pseudo-primality test!*. If `get_data` is set to true and `n = p^d`, for a pseudoprime `p` and power `d`, return [(p, d)]. INPUT: - ``n`` - an integer - ``bound (default 1024)`` - int: highest power to test. - ``get_data`` - boolean: return small pseudoprime and the power. EXAMPLES:: sage: is_pseudoprime_small_power(389) True sage: is_pseudoprime_small_power(2000) False sage: is_pseudoprime_small_power(2) True sage: is_pseudoprime_small_power(1024) True sage: is_pseudoprime_small_power(-1) False sage: is_pseudoprime_small_power(1) True sage: is_pseudoprime_small_power(997^100) True The default bound is 1024:: sage: is_pseudoprime_small_power(3^1024) True sage: is_pseudoprime_small_power(3^1025) False But it can be set higher or lower:: sage: is_pseudoprime_small_power(3^1025, bound=2000) True sage: is_pseudoprime_small_power(3^100, bound=20) False Use of the get_data keyword:: sage: is_pseudoprime_small_power(3^1024, get_data=True) [(3, 1024)] sage: is_pseudoprime_small_power(2^256, get_data=True) [(2, 256)] sage: is_pseudoprime_small_power(15, get_data=True) False """ n = ZZ(n) if n.is_pseudoprime() or n == 1: return True if n < 0: return False for i in range(2, bound + 1): p, boo = n.nth_root(i, truncate_mode=True) if boo: if p.is_pseudoprime(): if get_data == True: return [(p, i)] else: return True return False
- ``verbose`` - integer (default 0); pari's debug
- ``verbose`` - integer (default: 0); PARI's debug
def factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds): """ Returns the factorization of n. The result depends on the type of n. If n is an integer, factor returns the factorization of the integer n as an object of type Factorization. If n is not an integer, ``n.factor(proof=proof, **kwds)`` gets called. See ``n.factor??`` for more documentation in this case. .. warning:: This means that applying factor to an integer result of a symbolic computation will not factor the integer, because it is considered as an element of a larger symbolic ring. EXAMPLE:: sage: f(n)=n^2 sage: is_prime(f(3)) False sage: factor(f(3)) 9 INPUT: - ``n`` - an nonzero integer - ``proof`` - bool or None (default: None) - ``int_`` - bool (default: False) whether to return answers as Python ints - ``algorithm`` - string - ``'pari'`` - (default) use the PARI c library - ``'kash'`` - use KASH computer algebra system (requires the optional kash package be installed) - ``'magma'`` - use Magma (requires magma be installed) - ``verbose`` - integer (default 0); pari's debug variable is set to this; e.g., set to 4 or 8 to see lots of output during factorization. OUTPUT: factorization of n The qsieve and ecm commands give access to highly optimized implementations of algorithms for doing certain integer factorization problems. These implementations are not used by the generic factor command, which currently just calls PARI (note that PARI also implements sieve and ecm algorithms, but they aren't as optimized). Thus you might consider using them instead for certain numbers. The factorization returned is an element of the class :class:`~sage.structure.factorization.Factorization`; see Factorization?? for more details, and examples below for usage. A Factorization contains both the unit factor (+1 or -1) and a sorted list of (prime, exponent) pairs. The factorization displays in pretty-print format but it is easy to obtain access to the (prime,exponent) pairs and the unit, to recover the number from its factorization, and even to multiply two factorizations. See examples below. EXAMPLES:: sage: factor(500) 2^2 * 5^3 sage: factor(-20) -1 * 2^2 * 5 sage: f=factor(-20) sage: list(f) [(2, 2), (5, 1)] sage: f.unit() -1 sage: f.value() -20 sage: factor( -next_prime(10^2) * next_prime(10^7) ) -1 * 101 * 10000019 :: sage: factor(-500, algorithm='kash') # optional - kash -1 * 2^2 * 5^3 :: sage: factor(-500, algorithm='magma') # optional - magma -1 * 2^2 * 5^3 :: sage: factor(0) Traceback (most recent call last): ... ArithmeticError: Prime factorization of 0 not defined. sage: factor(1) 1 sage: factor(-1) -1 sage: factor(2^(2^7)+1) 59649589127497217 * 5704689200685129054721 Sage calls PARI's factor, which has proof False by default. Sage has a global proof flag, set to True by default (see :mod:`sage.structure.proof.proof`, or proof.[tab]). To override the default, call this function with proof=False. :: sage: factor(3^89-1, proof=False) 2 * 179 * 1611479891519807 * 5042939439565996049162197 :: sage: factor(2^197 + 1) # takes a long time (e.g., 3 seconds!) 3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843 Any object which has a factor method can be factored like this:: sage: K.<i> = QuadraticField(-1) sage: factor(122+454*i) (-1) * (-2*i - 3) * (-i + 4) * (i + 1)^3 * (-i + 2)^3 To access the data in a factorization:: sage: f = factor(420); f 2^2 * 3 * 5 * 7 sage: [x for x in f] [(2, 2), (3, 1), (5, 1), (7, 1)] sage: [p for p,e in f] [2, 3, 5, 7] sage: [e for p,e in f] [2, 1, 1, 1] sage: [p^e for p,e in f] [4, 3, 5, 7] """ if not isinstance(n, (int,long, integer.Integer)): # this happens for example if n = x**2 + y**2 + 2*x*y try: return n.factor(proof=proof, **kwds) except AttributeError: raise TypeError, "unable to factor n" except TypeError: # just in case factor method doesn't have a proof option. try: return n.factor(**kwds) except AttributeError: raise TypeError, "unable to factor n" #n = abs(n) n = ZZ(n) if n < 0: unit = ZZ(-1) n = -n else: unit = ZZ(1) if n == 0: raise ArithmeticError, "Prime factorization of 0 not defined." if n == 1: return factorization.Factorization([], unit) if n < 10000000000000: return factorization.Factorization(__factor_using_trial_division(n), unit) if algorithm == 'pari': return factorization.Factorization(__factor_using_pari(n, int_=int_, debug_level=verbose, proof=proof), unit) elif algorithm in ['kash', 'magma']: if algorithm == 'kash': from sage.interfaces.all import kash as I else: from sage.interfaces.all import magma as I F = I.eval('Factorization(%s)'%n) i = F.rfind(']') + 1 F = F[:i] F = F.replace("<","(").replace(">",")") F = eval(F) if not int_: F = [(ZZ(a), ZZ(b)) for a,b in F] return factorization.Factorization(F, unit) else: raise ValueError, "Algorithm is not known"
See also: :function:`Partition`, :meth:`Partition.to_exp`
See also: :func:`Partition`, :meth:`Partition.to_exp`
def from_polynomial_exp(self, p): r""" Conversion from polynomial in exponential notation
of `pi`.
of `\pi`.
sage: def maple_leaf(t):
for best style in that case.
for best style in that case. :: sage: plot(arcsin(x),(x,-1,1),ticks=[None,pi/6],tick_formatter=["latex",pi])
sage: def maple_leaf(t):
sage: plot(arcsin(x),(x,-1,1),ticks=[None,pi/6],tick_formatter=["latex",pi])
sage: def maple_leaf(t):
if F.derivative(v)(xyz).valuation(P) == 0:
c = (F.derivative(v))(xyz) try: val = c.valuation(P) except AttributeError: val = c.constant_coefficient().valuation(P) if val == 0:
def has_good_reduction(self, P=None): r""" Returns True iff this point has good reduction modulo a prime.
X = list(X)
return Set_object_enumerated(list(X))
def Set(X): r""" Create the underlying set of $X$. If $X$ is a list, tuple, Python set, or ``X.is_finite()`` is true, this returns a wrapper around Python's enumerated immutable frozenset type with extra functionality. Otherwise it returns a more formal wrapper. If you need the functionality of mutable sets, use Python's builtin set type. EXAMPLES:: sage: X = Set(GF(9,'a')) sage: X {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} sage: type(X) <class 'sage.sets.set.Set_object_enumerated'> sage: Y = X.union(Set(QQ)) sage: Y Set-theoretic union of {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} and Set of elements of Rational Field sage: type(Y) <class 'sage.sets.set.Set_object_union'> Usually sets can be used as dictionary keys. :: sage: d={Set([2*I,1+I]):10} sage: d # key is randomly ordered {{I + 1, 2*I}: 10} sage: d[Set([1+I,2*I])] 10 sage: d[Set((1+I,2*I))] 10 The original object is often forgotten. :: sage: v = [1,2,3] sage: X = Set(v) sage: X {1, 2, 3} sage: v.append(5) sage: X {1, 2, 3} sage: 5 in X False Set also accepts iterators, but be careful to only give *finite* sets. :: sage: list(Set(iter([1, 2, 3, 4, 5]))) [1, 2, 3, 4, 5] TESTS:: sage: Set(Primes()) Set of all prime numbers: 2, 3, 5, 7, ... sage: Set(Subsets([1,2,3])).cardinality() 8 """ if is_Set(X): return X if isinstance(X, Element): raise TypeError, "Element has no defined underlying set" elif isinstance(X, (list, tuple, set, frozenset)): return Set_object_enumerated(frozenset(X)) try: if X.is_finite(): return Set_object_enumerated(X) except AttributeError: pass if is_iterator(X): # Note we are risking an infinite loop here, # but this is the way Python behaves too: try # sage: set(an iterator which does not terminate) X = list(X) return Set_object(X)
def iter_morphisms(self, l=None, codomain=None, min_length=1):
@rename_keyword(deprecated='Sage version 4.6.1', l='arg') def iter_morphisms(self, arg=None, codomain=None, min_length=1):
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
- ``l`` - (optional, default: None) It can be one of the following :
- ``arg`` - (optional, default: None) It can be one of the following :
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
- list of nonnegative integers - The length of the list must be the number of letters in the alphabet, and the `i`-th integer of ``l`` determines the length of the word mapped to by the `i`-th letter of the (ordered) alphabet.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
- ``min_length`` - (default: 1) nonnegative integer. If ``l`` is
- ``min_length`` - (default: 1) nonnegative integer. If ``arg`` is
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
``min_length``. This is ignored if ``l`` is a list.
``min_length``. This is ignored if ``arg`` is a list.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
TypeError: l (=[0, 1, 2]) must be an iterable of 2 integers
TypeError: arg (=[0, 1, 2]) must be an iterable of 2 integers
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
TypeError: l (=[0, 'a']) must be an iterable of 2 integers
TypeError: arg (=[0, 'a']) must be an iterable of 2 integers
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
if l is None:
if arg is None:
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
elif isinstance(l, tuple): if not len(l) == 2 or not all(isinstance(a, (int,Integer)) for a in l): raise TypeError("l (=%s) must be a tuple of 2 integers" %l)
elif isinstance(arg, tuple): if not len(arg) == 2 or not all(isinstance(a, (int,Integer)) for a in arg): raise TypeError("arg (=%s) must be a tuple of 2 integers" %arg)
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
compositions = IntegerListsLex(range(*l),
compositions = IntegerListsLex(range(*arg),
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
l = list(l) if (not len(l) == n or not all(isinstance(a, (int,Integer)) for a in l)):
arg = list(arg) if (not len(arg) == n or not all(isinstance(a, (int,Integer)) for a in arg)):
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
"l (=%s) must be an iterable of %s integers" %(l, n)) compositions = [l]
"arg (=%s) must be an iterable of %s integers" %(arg, n)) compositions = [arg]
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
- Oscar Lazo, William Cauchois (2009-2010): Adding coordinate transformations
- Oscar Lazo, William Cauchois, Jason Grout (2009-2010): Adding coordinate transformations
sage: def f(x,y): return math.exp(x/5)*math.cos(y)
class _CoordTrans(object):
class _Coordinates(object):
sage: def f(x,y): return math.exp(x/5)*math.cos(y)
Sub-classes must implement the ``gen_transform`` method which, given
Sub-classes must implement the :meth:`transform` method which, given
sage: def f(x,y): return math.exp(x/5)*math.cos(y)
def __init__(self, indep_var, dep_vars):
def __init__(self, dep_var, indep_vars):
sage: def f(x,y): return math.exp(x/5)*math.cos(y)
- ``indep_var`` - The independent variable (the function value will be
- ``dep_var`` - The dependent variable (the function value will be
def __init__(self, indep_var, dep_vars): """ INPUT:
- ``dep_vars`` - A list of dependent variables (the parameters will be
- ``indep_vars`` - A list of independent variables (the parameters will be
def __init__(self, indep_var, dep_vars): """ INPUT:
sage: from sage.plot.plot3d.plot3d import _CoordTrans sage: _CoordTrans('y', ['x']) Unknown coordinate system (y in terms of x) """ if hasattr(self, 'all_vars'): if set(self.all_vars) != set(dep_vars + [indep_var]): raise ValueError, 'not all variables were specified for ' + \ 'this coordinate system' self.indep_var = indep_var self.dep_vars = dep_vars def gen_transform(self, **kwds): """ Generate the transformation for this coordinate system in terms of the
sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates as arb sage: x,y,z=var('x,y,z') sage: c=arb((x+z,y*z,z), z, (x,y)) sage: c._name 'Arbitrary Coordinates' """ return self.__class__.__name__ def transform(self, **kwds): """ Return the transformation for this coordinate system in terms of the
def __init__(self, indep_var, dep_vars): """ INPUT:
def to_cartesian(self, func, params):
def to_cartesian(self, func, params=None):
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
- ``params`` - The parameters of func. Correspond to the dependent
- ``params`` - The parameters of func. Corresponds to the dependent
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans
sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
sage: T = _ArbCoordTrans((x + y, x - y, z), z) sage: f(x, y) = x * y sage: T.to_cartesian(f, [x, y]) [x + y, x - y, x*y] """
sage: T = _ArbitraryCoordinates((x + y, x - y, z), z,[x,y]) sage: f(x, y) = 2*x+y sage: T.to_cartesian(f, [x, y]) (x + y, x - y, 2*x + y) sage: [h(1,2) for h in T.to_cartesian(lambda x,y: 2*x+y)] [3, -1, 4] """
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
if any([is_Expression(func), is_RealNumber(func), is_Integer(func)]): return self.gen_transform(**{ self.indep_var: func, self.dep_vars[0]: params[0], self.dep_vars[1]: params[1]
if params is not None and (is_Expression(func) or is_RealNumber(func) or is_Integer(func)): return self.transform(**{ self.dep_var: func, self.indep_vars[0]: params[0], self.indep_vars[1]: params[1]
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
indep_var_dummy = sage.symbolic.ring.var(self.indep_var) dep_var_dummies = sage.symbolic.ring.var(','.join(self.dep_vars)) transformation = self.gen_transform(**{ self.indep_var: indep_var_dummy, self.dep_vars[0]: dep_var_dummies[0], self.dep_vars[1]: dep_var_dummies[1]
dep_var_dummy = sage.symbolic.ring.var(self.dep_var) indep_var_dummies = sage.symbolic.ring.var(','.join(self.indep_vars)) transformation = self.transform(**{ self.dep_var: dep_var_dummy, self.indep_vars[0]: indep_var_dummies[0], self.indep_vars[1]: indep_var_dummies[1]
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
indep_var_dummy: func(x, y), dep_var_dummies[0]: x, dep_var_dummies[1]: y
dep_var_dummy: func(x, y), indep_var_dummies[0]: x, indep_var_dummies[1]: y
def subs_func(t): return lambda x,y: t.subs({ indep_var_dummy: func(x, y), dep_var_dummies[0]: x, dep_var_dummies[1]: y })
_name = 'Unknown coordinate system'
def subs_func(t): return lambda x,y: t.subs({ indep_var_dummy: func(x, y), dep_var_dummies[0]: x, dep_var_dummies[1]: y })
return '%s (%s in terms of %s)' % \ (self._name, self.indep_var, ', '.join(self.dep_vars)) class _ArbCoordTrans(_CoordTrans): """ An arbitrary coordinate system transformation. """ def __init__(self, custom_trans, fvar): """
return '%s coordinate transform (%s in terms of %s)' % \ (self._name, self.dep_var, ', '.join(self.indep_vars)) class _ArbitraryCoordinates(_Coordinates): """ An arbitrary coordinate system. """ _name = "Arbitrary Coordinates" def __init__(self, custom_trans, dep_var, indep_vars): """ Initialize an arbitrary coordinate system.
def __repr__(self): return '%s (%s in terms of %s)' % \ (self._name, self.indep_var, ', '.join(self.dep_vars))
- ``custom_trans`` - A 3-tuple of transformations. This will be returned almost unchanged by ``gen_transform``, except the function variable will be substituted. - ``fvar`` - The function variable. """ super(_ArbCoordTrans, self).__init__('f', ['u', 'v']) self.custom_trans = custom_trans self.fvar = fvar def gen_transform(self, f=None, u=None, v=None):
- ``custom_trans`` - A 3-tuple of transformation functions. - ``dep_var`` - The dependent (function) variable. - ``indep_vars`` - a list of the two other independent variables. EXAMPLES:: sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates sage: x, y, z = var('x y z') sage: T = _ArbitraryCoordinates((x + y, x - y, z), z,[x,y]) sage: f(x, y) = 2*x + y sage: T.to_cartesian(f, [x, y]) (x + y, x - y, 2*x + y) sage: [h(1,2) for h in T.to_cartesian(lambda x,y: 2*x+y)] [3, -1, 4] """ self.dep_var = str(dep_var) self.indep_vars = [str(i) for i in indep_vars] self.custom_trans = tuple(custom_trans) def transform(self, **kwds):
def __init__(self, custom_trans, fvar): """ INPUT:
sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans
sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE:: sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans sage: x, y, z = var('x y z') sage: T = _ArbCoordTrans((x + y, x - y, z), x)