code
stringlengths
17
6.64M
def primes_first_n(n, leave_pari=False): '\n Return the first `n` primes.\n\n INPUT:\n\n - `n` - a nonnegative integer\n\n OUTPUT:\n\n - a list of the first `n` prime numbers.\n\n EXAMPLES::\n\n sage: primes_first_n(10) # needs sage.libs.pari\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n sage: len(primes_first_n(1000)) # needs sage.libs.pari\n 1000\n sage: primes_first_n(0)\n []\n ' if (n < 0): raise ValueError('n must be nonnegative') if (n < 1): return [] return prime_range((nth_prime(n) + 1))
def eratosthenes(n): '\n Return a list of the primes `\\leq n`.\n\n This is extremely slow and is for educational purposes only.\n\n INPUT:\n\n - ``n`` - a positive integer\n\n OUTPUT:\n\n - a list of primes less than or equal to n.\n\n EXAMPLES::\n\n sage: eratosthenes(3)\n [2, 3]\n sage: eratosthenes(50)\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]\n sage: len(eratosthenes(100))\n 25\n sage: eratosthenes(213) == prime_range(213) # needs sage.libs.pari\n True\n\n TESTS::\n\n sage: from numpy import int8 # needs numpy\n sage: eratosthenes(int8(3)) # needs numpy\n [2, 3]\n sage: from gmpy2 import mpz\n sage: eratosthenes(mpz(3))\n [2, 3]\n ' n = int(n) if (n < 2): return [] elif (n == 2): return [ZZ(2)] s = list(range(3, (n + 3), 2)) mroot = int((n ** 0.5)) half = ((n + 1) // 2) i = 0 m = 3 while (m <= mroot): if s[i]: j = (((m * m) - 3) // 2) s[j] = 0 while (j < half): s[j] = 0 j += m i = (i + 1) m = ((2 * i) + 3) return ([ZZ(2)] + [ZZ(x) for x in s if (x and (x <= n))])
def primes(start=2, stop=None, proof=None): '\n Return an iterator over all primes between ``start`` and ``stop-1``,\n inclusive. This is much slower than :func:`prime_range`, but\n potentially uses less memory. As with :func:`next_prime`, the optional\n argument ``proof`` controls whether the numbers returned are\n guaranteed to be prime or not.\n\n This command is like the Python 3 :func:`range` command, except it only\n iterates over primes. In some cases it is better to use :func:`primes` than\n :func:`prime_range`, because :func:`primes` does not build a list of all\n primes in the range in memory all at once. However, it is potentially much\n slower since it simply calls the :func:`next_prime` function repeatedly, and\n :func:`next_prime` is slow.\n\n INPUT:\n\n - ``start`` -- an integer (optional, default: 2) lower bound for the primes\n\n - ``stop`` -- an integer (or infinity) upper (open) bound for the\n primes\n\n - ``proof`` -- bool or ``None`` (default: ``None``) If ``True``, the\n function yields only proven primes. If ``False``, the function uses a\n pseudo-primality test, which is much faster for really big numbers but\n does not provide a proof of primality. If ``None``, uses the global\n default (see :mod:`sage.structure.proof.proof`)\n\n OUTPUT:\n\n - an iterator over primes from ``start`` to ``stop-1``, inclusive\n\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: for p in primes(5, 10):\n ....: print(p)\n 5\n 7\n sage: list(primes(13))\n [2, 3, 5, 7, 11]\n sage: list(primes(10000000000, 10000000100))\n [10000000019, 10000000033, 10000000061, 10000000069, 10000000097]\n sage: max(primes(10^100, 10^100+10^4, proof=False))\n 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009631\n sage: next(p for p in primes(10^20, infinity) if is_prime(2*p+1))\n 100000000000000001243\n\n\n TESTS::\n\n sage: # needs sage.libs.pari\n sage: for a in range(-10, 50):\n ....: for b in range(-10, 50):\n ....: assert list(primes(a,b)) == list(filter(is_prime, range(a,b)))\n sage: sum(primes(-10, 9973, proof=False)) == sum(filter(is_prime, range(-10, 9973)))\n True\n sage: for p in primes(10, infinity):\n ....: if p > 20: break\n ....: print(p)\n 11\n 13\n 17\n 19\n sage: next(p for p in primes(10,oo)) # checks alternate infinity notation\n 11\n sage: from numpy import int8 # needs numpy\n sage: list(primes(int8(13))) # needs numpy\n [2, 3, 5, 7, 11]\n sage: from gmpy2 import mpz\n sage: list(primes(mpz(13)))\n [2, 3, 5, 7, 11]\n ' from sage.rings.infinity import infinity start = ZZ(start) if (stop is None): stop = start start = ZZ(2) elif (stop != infinity): stop = ZZ(stop) n = (start - 1) while True: n = n.next_prime(proof) if (n < stop): (yield n) else: return
def next_prime_power(n): '\n Return the smallest prime power greater than ``n``.\n\n Note that if ``n`` is a prime power, then this function does not return\n ``n``, but the next prime power after ``n``.\n\n This function just calls the method\n :meth:`Integer.next_prime_power() <sage.rings.integer.Integer.next_prime_power>`\n of Integers.\n\n .. SEEALSO::\n\n - :func:`is_prime_power` (and\n :meth:`Integer.is_prime_power() <sage.rings.integer.Integer.is_prime_power()>`)\n - :func:`previous_prime_power` (and\n :meth:`Integer.previous_prime_power() <sage.rings.integer.Integer.next_prime_power>`)\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: next_prime_power(1)\n 2\n sage: next_prime_power(2)\n 3\n sage: next_prime_power(10)\n 11\n sage: next_prime_power(7)\n 8\n sage: next_prime_power(99)\n 101\n\n The same results can be obtained with::\n\n sage: 1.next_prime_power()\n 2\n sage: 2.next_prime_power()\n 3\n sage: 10.next_prime_power()\n 11\n\n Note that `2` is the smallest prime power::\n\n sage: next_prime_power(-10)\n 2\n sage: next_prime_power(0)\n 2\n\n TESTS::\n\n sage: from numpy import int8 # needs numpy\n sage: next_prime_power(int8(10)) # needs numpy sage.libs.pari\n 11\n sage: from gmpy2 import mpz\n sage: next_prime_power(mpz(10))\n 11\n ' return ZZ(n).next_prime_power()
def next_probable_prime(n): '\n Return the next probable prime after self, as determined by PARI.\n\n INPUT:\n\n\n - ``n`` - an integer\n\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: next_probable_prime(-100)\n 2\n sage: next_probable_prime(19)\n 23\n sage: next_probable_prime(int(999999999))\n 1000000007\n sage: next_probable_prime(2^768)\n 1552518092300708935148979488462502555256886017116696611139052038026050952686376886330878408828646477950487730697131073206171580044114814391444287275041181139204454976020849905550265285631598444825262999193716468750892846853816058039\n\n TESTS::\n\n sage: from numpy import int8 # needs numpy\n sage: next_probable_prime(int8(19)) # needs numpy sage.libs.pari\n 23\n sage: from gmpy2 import mpz\n sage: next_probable_prime(mpz(19)) # needs sage.libs.pari\n 23\n ' return ZZ(n).next_probable_prime()
def next_prime(n, proof=None): '\n The next prime greater than the integer n. If n is prime, then this\n function does not return n, but the next prime after n. If the\n optional argument proof is False, this function only returns a\n pseudo-prime, as defined by the PARI nextprime function. If it is\n None, uses the global default (see :mod:`sage.structure.proof.proof`)\n\n INPUT:\n\n\n - ``n`` - integer\n\n - ``proof`` - bool or None (default: None)\n\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: next_prime(-100)\n 2\n sage: next_prime(1)\n 2\n sage: next_prime(2)\n 3\n sage: next_prime(3)\n 5\n sage: next_prime(4)\n 5\n\n Notice that the next_prime(5) is not 5 but 7.\n\n ::\n\n sage: next_prime(5) # needs sage.libs.pari\n 7\n sage: next_prime(2004) # needs sage.libs.pari\n 2011\n\n TESTS::\n\n sage: from numpy import int8 # needs numpy\n sage: next_prime(int8(3)) # needs numpy sage.libs.pari\n 5\n sage: from gmpy2 import mpz\n sage: next_probable_prime(mpz(3)) # needs sage.libs.pari\n 5\n ' return ZZ(n).next_prime(proof)
def previous_prime(n): '\n The largest prime < n. The result is provably correct. If n <= 1,\n this function raises a ValueError.\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: previous_prime(10)\n 7\n sage: previous_prime(7)\n 5\n sage: previous_prime(8)\n 7\n sage: previous_prime(7)\n 5\n sage: previous_prime(5)\n 3\n sage: previous_prime(3)\n 2\n sage: previous_prime(2)\n Traceback (most recent call last):\n ...\n ValueError: no previous prime\n sage: previous_prime(1)\n Traceback (most recent call last):\n ...\n ValueError: no previous prime\n sage: previous_prime(-20)\n Traceback (most recent call last):\n ...\n ValueError: no previous prime\n\n TESTS::\n\n sage: from numpy import int8 # needs numpy\n sage: previous_prime(int8(7)) # needs numpy sage.libs.pari\n 5\n sage: from gmpy2 import mpz\n sage: previous_prime(mpz(7))\n 5\n ' n = (ZZ(n) - 1) if (n <= 1): raise ValueError('no previous prime') if (n <= 3): return ZZ(n) if ((n % 2) == 0): n -= 1 while (not is_prime(n)): n -= 2 return ZZ(n)
def previous_prime_power(n): '\n Return the largest prime power smaller than ``n``.\n\n The result is provably correct. If ``n`` is smaller or equal than ``2`` this\n function raises an error.\n\n This function simply call the method\n :meth:`Integer.previous_prime_power() <sage.rings.integer.Integer.previous_prime_power>`\n of Integers.\n\n .. SEEALSO::\n\n - :func:`is_prime_power` (and :meth:`Integer.is_prime_power()\n <sage.rings.integer.Integer.is_prime_power>`)\n - :func:`next_prime_power` (and :meth:`Integer.next_prime_power()\n <sage.rings.integer.Integer.next_prime_power>`)\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: previous_prime_power(3)\n 2\n sage: previous_prime_power(10)\n 9\n sage: previous_prime_power(7)\n 5\n sage: previous_prime_power(127)\n 125\n\n The same results can be obtained with::\n\n sage: # needs sage.libs.pari\n sage: 3.previous_prime_power()\n 2\n sage: 10.previous_prime_power()\n 9\n sage: 7.previous_prime_power()\n 5\n sage: 127.previous_prime_power()\n 125\n\n Input less than or equal to `2` raises errors::\n\n sage: previous_prime_power(2)\n Traceback (most recent call last):\n ...\n ValueError: no prime power less than 2\n sage: previous_prime_power(-10)\n Traceback (most recent call last):\n ...\n ValueError: no prime power less than 2\n\n ::\n\n sage: n = previous_prime_power(2^16 - 1) # needs sage.libs.pari\n sage: while is_prime(n): # needs sage.libs.pari\n ....: n = previous_prime_power(n)\n sage: factor(n) # needs sage.libs.pari\n 251^2\n\n TESTS::\n\n sage: from numpy import int8 # needs numpy\n sage: previous_prime_power(int8(10)) # needs numpy sage.libs.pari\n 9\n sage: from gmpy2 import mpz\n sage: previous_prime_power(mpz(10)) # needs sage.libs.pari\n 9\n ' return ZZ(n).previous_prime_power()
def random_prime(n, proof=None, lbound=2): "\n Return a random prime `p` between ``lbound`` and `n`.\n\n The returned prime `p` satisfies ``lbound`` `\\leq p \\leq n`.\n\n The returned prime `p` is chosen uniformly at random from the set\n of prime numbers less than or equal to `n`.\n\n INPUT:\n\n - ``n`` - an integer `\\geq 2`.\n\n - ``proof`` - bool or ``None`` (default: ``None``) If ``False``, the function uses a\n pseudo-primality test, which is much faster for really big numbers but\n does not provide a proof of primality. If ``None``, uses the global default\n (see :mod:`sage.structure.proof.proof`)\n\n - ``lbound`` - an integer `\\geq 2`, lower bound for the chosen primes\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: p = random_prime(100000)\n sage: p.is_prime()\n True\n sage: p <= 100000\n True\n sage: random_prime(2)\n 2\n\n Here we generate a random prime between 100 and 200::\n\n sage: p = random_prime(200, lbound=100)\n sage: p.is_prime()\n True\n sage: 100 <= p <= 200\n True\n\n If all we care about is finding a pseudo prime, then we can pass\n in ``proof=False`` ::\n\n sage: p = random_prime(200, proof=False, lbound=100) # needs sage.libs.pari\n sage: p.is_pseudoprime() # needs sage.libs.pari\n True\n sage: 100 <= p <= 200\n True\n\n TESTS::\n\n sage: # needs sage.libs.pari\n sage: type(random_prime(2))\n <class 'sage.rings.integer.Integer'>\n sage: type(random_prime(100))\n <class 'sage.rings.integer.Integer'>\n sage: random_prime(1, lbound=-2) # caused Sage hang #10112\n Traceback (most recent call last):\n ...\n ValueError: n must be greater than or equal to 2\n sage: random_prime(126, lbound=114)\n Traceback (most recent call last):\n ...\n ValueError: there are no primes between 114 and 126 (inclusive)\n\n AUTHORS:\n\n - Jon Hanke (2006-08-08): with standard Stein cleanup\n\n - Jonathan Bober (2007-03-17)\n " from sage.structure.proof.proof import get_flag proof = get_flag(proof, 'arithmetic') n = ZZ(n) if (n < 2): raise ValueError('n must be greater than or equal to 2') if (n < lbound): raise ValueError(('n must be at least lbound: %s' % lbound)) elif (n == 2): return n lbound = max(2, lbound) if (lbound > 2): if ((lbound == 3) or (n <= ((2 * lbound) - 2))): if ((lbound < 25) or (n <= ((6 * lbound) / 5))): if ((lbound < 2010760) or (n <= ((16598 * lbound) / 16597))): if proof: smallest_prime = ZZ((lbound - 1)).next_prime() else: smallest_prime = ZZ((lbound - 1)).next_probable_prime() if (smallest_prime > n): raise ValueError(('there are no primes between %s and %s (inclusive)' % (lbound, n))) if proof: prime_test = is_prime else: prime_test = is_pseudoprime randint = ZZ.random_element while True: p = randint(lbound, n) if prime_test(p): return p
def divisors(n): '\n Return the list of all divisors (up to units) of this element\n of a unique factorization domain.\n\n For an integer, the list of all positive integer divisors\n of this integer, sorted in increasing order, is returned.\n\n INPUT:\n\n - ``n`` - the element\n\n EXAMPLES:\n\n Divisors of integers::\n\n sage: divisors(-3)\n [1, 3]\n sage: divisors(6)\n [1, 2, 3, 6]\n sage: divisors(28)\n [1, 2, 4, 7, 14, 28]\n sage: divisors(2^5)\n [1, 2, 4, 8, 16, 32]\n sage: divisors(100)\n [1, 2, 4, 5, 10, 20, 25, 50, 100]\n sage: divisors(1)\n [1]\n sage: divisors(0)\n Traceback (most recent call last):\n ...\n ValueError: n must be nonzero\n sage: divisors(2^3 * 3^2 * 17)\n [1, 2, 3, 4, 6, 8, 9, 12, 17, 18, 24, 34, 36, 51, 68, 72,\n 102, 136, 153, 204, 306, 408, 612, 1224]\n\n This function works whenever one has unique factorization::\n\n sage: # needs sage.rings.number_field\n sage: K.<a> = QuadraticField(7)\n sage: divisors(K.ideal(7))\n [Fractional ideal (1), Fractional ideal (a), Fractional ideal (7)]\n sage: divisors(K.ideal(3))\n [Fractional ideal (1), Fractional ideal (3),\n Fractional ideal (a - 2), Fractional ideal (a + 2)]\n sage: divisors(K.ideal(35))\n [Fractional ideal (1), Fractional ideal (5), Fractional ideal (a),\n Fractional ideal (7), Fractional ideal (5*a), Fractional ideal (35)]\n\n TESTS::\n\n sage: divisors(int(300))\n [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]\n sage: import numpy # needs numpy\n sage: divisors(numpy.int8(100)) # needs numpy\n [1, 2, 4, 5, 10, 20, 25, 50, 100]\n sage: import gmpy2\n sage: divisors(gmpy2.mpz(100))\n [1, 2, 4, 5, 10, 20, 25, 50, 100]\n sage: divisors([])\n Traceback (most recent call last):\n ...\n TypeError: unable to factor []\n ' try: m = n.divisors except AttributeError: e = py_scalar_to_element(n) if (e is n): f = factor(n) one = parent(n)(1) output = [one] for (p, e) in f: prev = output[:] pn = one for i in range(e): pn *= p output.extend(((a * pn) for a in prev)) output.sort() return output n = e m = n.divisors if (not n): raise ValueError('n must be nonzero') return m()
class Sigma(): '\n Return the sum of the k-th powers of the divisors of n.\n\n INPUT:\n\n\n - ``n`` - integer\n\n - ``k`` - integer (default: 1)\n\n\n OUTPUT: integer\n\n EXAMPLES::\n\n sage: sigma(5)\n 6\n sage: sigma(5,2)\n 26\n\n The sigma function also has a special plotting method.\n\n ::\n\n sage: P = plot(sigma, 1, 100) # needs sage.plot\n\n This method also works with k-th powers.\n\n ::\n\n sage: P = plot(sigma, 1, 100, k=2) # needs sage.plot\n\n AUTHORS:\n\n - William Stein: original implementation\n\n - Craig Citro (2007-06-01): rewrote for huge speedup\n\n TESTS::\n\n sage: sigma(100,4)\n 106811523\n\n sage: # needs sage.libs.pari\n sage: sigma(factorial(100), 3).mod(144169)\n 3672\n sage: sigma(factorial(150), 12).mod(691)\n 176\n sage: RR(sigma(factorial(133),20)) # needs sage.rings.real_mpfr\n 2.80414775675747e4523\n sage: sigma(factorial(100),0)\n 39001250856960000\n sage: sigma(factorial(41),1)\n 229199532273029988767733858700732906511758707916800\n sage: from numpy import int8 # needs numpy\n sage: sigma(int8(100), int8(4)) # needs numpy\n 106811523\n\n sage: from gmpy2 import mpz\n sage: sigma(mpz(100), mpz(4))\n 106811523\n ' def __repr__(self): "\n A description of this class, which computes the sum of the\n k-th powers of the divisors of n.\n\n EXAMPLES::\n\n sage: from sage.arith.misc import Sigma\n sage: Sigma().__repr__()\n 'Function that adds up (k-th powers of) the divisors of n'\n " return 'Function that adds up (k-th powers of) the divisors of n' def __call__(self, n, k=1): '\n Computes the sum of (the k-th powers of) the divisors of n.\n\n EXAMPLES::\n\n sage: from sage.arith.misc import Sigma\n sage: q = Sigma()\n sage: q(10)\n 18\n sage: q(10,2)\n 130\n ' n = ZZ(n) k = ZZ(k) one = ZZ(1) if (k == ZZ(0)): return prod(((expt + one) for (p, expt) in factor(n))) elif (k == one): return prod((((p ** (expt + one)) - one).divide_knowing_divisible_by((p - one)) for (p, expt) in factor(n))) else: return prod((((p ** ((expt + one) * k)) - one).divide_knowing_divisible_by(((p ** k) - one)) for (p, expt) in factor(n))) def plot(self, xmin=1, xmax=50, k=1, pointsize=30, rgbcolor=(0, 0, 1), join=True, **kwds): '\n Plot the sigma (sum of k-th powers of divisors) function.\n\n INPUT:\n\n\n - ``xmin`` - default: 1\n\n - ``xmax`` - default: 50\n\n - ``k`` - default: 1\n\n - ``pointsize`` - default: 30\n\n - ``rgbcolor`` - default: (0,0,1)\n\n - ``join`` - default: True; whether to join the\n points.\n\n - ``**kwds`` - passed on\n\n EXAMPLES::\n\n sage: from sage.arith.misc import Sigma\n sage: p = Sigma().plot() # needs sage.libs.pari sage.plot\n sage: p.ymax() # needs sage.libs.pari sage.plot\n 124.0\n ' v = [(n, sigma(n, k)) for n in range(xmin, (xmax + 1))] from sage.plot.all import list_plot P = list_plot(v, pointsize=pointsize, rgbcolor=rgbcolor, **kwds) if join: P += list_plot(v, plotjoined=True, rgbcolor=(0.7, 0.7, 0.7), **kwds) return P
def gcd(a, b=None, **kwargs): "\n Return the greatest common divisor of ``a`` and ``b``.\n\n If ``a`` is a list and ``b`` is omitted, return instead the\n greatest common divisor of all elements of ``a``.\n\n INPUT:\n\n - ``a,b`` -- two elements of a ring with gcd or\n\n - ``a`` -- a list or tuple of elements of a ring with gcd\n\n Additional keyword arguments are passed to the respectively called\n methods.\n\n OUTPUT:\n\n The given elements are first coerced into a common parent. Then,\n their greatest common divisor *in that common parent* is returned.\n\n EXAMPLES::\n\n sage: GCD(97,100)\n 1\n sage: GCD(97*10^15, 19^20*97^2)\n 97\n sage: GCD(2/3, 4/5)\n 2/15\n sage: GCD([2,4,6,8])\n 2\n sage: GCD(srange(0,10000,10)) # fast !!\n 10\n\n Note that to take the gcd of `n` elements for `n \\not= 2` you must\n put the elements into a list by enclosing them in ``[..]``. Before\n :trac:`4988` the following wrongly returned 3 since the third parameter\n was just ignored::\n\n sage: gcd(3, 6, 2)\n Traceback (most recent call last):\n ...\n TypeError: ...gcd() takes ...\n sage: gcd([3, 6, 2])\n 1\n\n Similarly, giving just one element (which is not a list) gives an error::\n\n sage: gcd(3)\n Traceback (most recent call last):\n ...\n TypeError: 'sage.rings.integer.Integer' object is not iterable\n\n By convention, the gcd of the empty list is (the integer) 0::\n\n sage: gcd([])\n 0\n sage: type(gcd([]))\n <class 'sage.rings.integer.Integer'>\n\n TESTS:\n\n The following shows that indeed coercion takes place before computing\n the gcd. This behaviour was introduced in :trac:`10771`::\n\n sage: R.<x> = QQ[]\n sage: S.<x> = ZZ[]\n sage: p = S.random_element(degree=(0,10))\n sage: q = R.random_element(degree=(0,10))\n sage: parent(gcd(1/p, q))\n Fraction Field of Univariate Polynomial Ring in x over Rational Field\n sage: parent(gcd([1/p, q]))\n Fraction Field of Univariate Polynomial Ring in x over Rational Field\n\n Make sure we try QQ and not merely ZZ (:trac:`13014`)::\n\n sage: bool(gcd(2/5, 3/7) == gcd(SR(2/5), SR(3/7))) # needs sage.symbolic\n True\n\n Make sure that the gcd of Expressions stays symbolic::\n\n sage: parent(gcd(2, 4))\n Integer Ring\n sage: parent(gcd(SR(2), 4)) # needs sage.symbolic\n Symbolic Ring\n sage: parent(gcd(2, SR(4))) # needs sage.symbolic\n Symbolic Ring\n sage: parent(gcd(SR(2), SR(4))) # needs sage.symbolic\n Symbolic Ring\n\n Verify that objects without gcd methods but which cannot be\n coerced to ZZ or QQ raise an error::\n\n sage: F.<a,b> = FreeMonoid(2) # needs sage.groups\n sage: gcd(a, b) # needs sage.groups\n Traceback (most recent call last):\n ...\n TypeError: unable to call gcd with a\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: GCD(int8(97), int8(100)) # needs numpy\n 1\n sage: from gmpy2 import mpq, mpz\n sage: GCD(mpq(2/3), mpq(4/5))\n 2/15\n sage: GCD((mpz(2), mpz(4)))\n 2\n " if (b is not None): try: m = a.gcd except (AttributeError, TypeError): e = py_scalar_to_element(a) if (e is a): raise TypeError('unable to call gcd with {!r}'.format(a)) m = e.gcd try: return m(b, **kwargs) except TypeError: return m(py_scalar_to_element(b), **kwargs) from sage.structure.sequence import Sequence seq = Sequence((py_scalar_to_element(el) for el in a)) if (seq.universe() is ZZ): return GCD_list(seq) else: return __GCD_sequence(seq, **kwargs)
def __GCD_sequence(v, **kwargs): "\n Internal function returning the gcd of the elements of a sequence\n\n INPUT:\n\n\n - ``v`` - A sequence (possibly empty)\n\n\n OUTPUT: The gcd of the elements of the sequence as an element of\n the sequence's universe, or the integer 0 if the sequence is\n empty.\n\n EXAMPLES::\n\n sage: from sage.arith.misc import __GCD_sequence\n sage: from sage.structure.sequence import Sequence\n sage: l = ()\n sage: __GCD_sequence(l)\n 0\n sage: __GCD_sequence(Sequence(srange(10)))\n 1\n sage: X=polygen(QQ)\n sage: __GCD_sequence(Sequence((2*X+4,2*X^2,2)))\n 1\n sage: X=polygen(ZZ)\n sage: __GCD_sequence(Sequence((2*X+4,2*X^2,2)))\n 2\n sage: __GCD_sequence(Sequence((1/1,1/2)))\n 1/2\n\n TESTS::\n\n sage: __GCD_sequence(Sequence((1,1/2,1/5)))\n 1/10\n " if (len(v) == 0): return ZZ(0) if hasattr(v, 'universe'): g = v.universe()(0) else: g = ZZ(0) for vi in v: g = vi.gcd(g, **kwargs) return g
def xlcm(m, n): '\n Extended lcm function: given two positive integers `m,n`, returns\n a triple `(l,m_1,n_1)` such that `l=\\mathop{\\mathrm{lcm}}(m,n)=m_1\n \\cdot n_1` where `m_1|m`, `n_1|n` and `\\gcd(m_1,n_1)=1`, all with no\n factorization.\n\n Used to construct an element of order `l` from elements of orders `m,n`\n in any group: see sage/groups/generic.py for examples.\n\n EXAMPLES::\n\n sage: xlcm(120,36)\n (360, 40, 9)\n\n TESTS::\n\n sage: from numpy import int16 # needs numpy\n sage: xlcm(int16(120), int16(36)) # needs numpy\n (360, 40, 9)\n sage: from gmpy2 import mpz\n sage: xlcm(mpz(120), mpz(36))\n (360, 40, 9)\n ' m = py_scalar_to_element(m) n = py_scalar_to_element(n) g = gcd(m, n) l = ((m * n) // g) g = gcd(m, (n // g)) while (g != 1): m //= g g = gcd(m, g) n = (l // m) return (l, m, n)
def xgcd(a, b): "\n Return a triple ``(g,s,t)`` such that `g = s\\cdot a+t\\cdot b = \\gcd(a,b)`.\n\n .. NOTE::\n\n One exception is if `a` and `b` are not in a principal ideal domain (see\n :wikipedia:`Principal_ideal_domain`), e.g., they are both polynomials\n over the integers. Then this function can't in general return ``(g,s,t)``\n as above, since they need not exist. Instead, over the integers, we\n first multiply `g` by a divisor of the resultant of `a/g` and `b/g`, up\n to sign.\n\n INPUT:\n\n - ``a, b`` - integers or more generally, element of a ring for which the\n xgcd make sense (e.g. a field or univariate polynomials).\n\n OUTPUT:\n\n - ``g, s, t`` - such that `g = s\\cdot a + t\\cdot b`\n\n .. NOTE::\n\n There is no guarantee that the returned cofactors (s and t) are\n minimal.\n\n EXAMPLES::\n\n sage: xgcd(56, 44)\n (4, 4, -5)\n sage: 4*56 + (-5)*44\n 4\n\n sage: g, a, b = xgcd(5/1, 7/1); g, a, b\n (1, 3, -2)\n sage: a*(5/1) + b*(7/1) == g\n True\n\n sage: x = polygen(QQ)\n sage: xgcd(x^3 - 1, x^2 - 1)\n (x - 1, 1, -x)\n\n sage: K.<g> = NumberField(x^2 - 3) # needs sage.rings.number_field\n sage: g.xgcd(g + 2) # needs sage.rings.number_field\n (1, 1/3*g, 0)\n\n sage: # needs sage.rings.number_field\n sage: R.<a,b> = K[]\n sage: S.<y> = R.fraction_field()[]\n sage: xgcd(y^2, a*y + b)\n (1, a^2/b^2, ((-a)/b^2)*y + 1/b)\n sage: xgcd((b+g)*y^2, (a+g)*y + b)\n (1, (a^2 + (2*g)*a + 3)/(b^3 + g*b^2), ((-a + (-g))/b^2)*y + 1/b)\n\n Here is an example of a xgcd for two polynomials over the integers, where the linear\n combination is not the gcd but the gcd multiplied by the resultant::\n\n sage: R.<x> = ZZ[]\n sage: gcd(2*x*(x-1), x^2)\n x\n sage: xgcd(2*x*(x-1), x^2)\n (2*x, -1, 2)\n sage: (2*(x-1)).resultant(x) # needs sage.libs.pari\n 2\n\n Tests with numpy and gmpy2 types::\n\n sage: from numpy import int8 # needs numpy\n sage: xgcd(4, int8(8)) # needs numpy\n (4, 1, 0)\n sage: xgcd(int8(4), int8(8)) # needs numpy\n (4, 1, 0)\n sage: from gmpy2 import mpz\n sage: xgcd(mpz(4), mpz(8))\n (4, 1, 0)\n sage: xgcd(4, mpz(8))\n (4, 1, 0)\n\n TESTS:\n\n We check that :trac:`3330` has been fixed::\n\n sage: # needs sage.rings.number_field\n sage: R.<a,b> = NumberField(x^2 - 3, 'g').extension(x^2 - 7, 'h')[]\n sage: h = R.base_ring().gen()\n sage: S.<y> = R.fraction_field()[]\n sage: xgcd(y^2, a*h*y + b)\n (1, 7*a^2/b^2, (((-h)*a)/b^2)*y + 1/b)\n " try: return a.xgcd(b) except AttributeError: a = py_scalar_to_element(a) b = py_scalar_to_element(b) except TypeError: b = py_scalar_to_element(b) return a.xgcd(b)
def xkcd(n=''): '\n This function is similar to the xgcd function, but behaves\n in a completely different way.\n\n See https://xkcd.com/json.html for more details.\n\n INPUT:\n\n - ``n`` -- an integer (optional)\n\n OUTPUT: a fragment of HTML\n\n EXAMPLES::\n\n sage: xkcd(353) # optional - internet\n <h1>Python</h1><img src="https://imgs.xkcd.com/comics/python.png" title="I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I\'m leaving you."><div>Source: <a href="http://xkcd.com/353" target="_blank">http://xkcd.com/353</a></div>\n ' import contextlib import json from sage.misc.html import html from ssl import create_default_context as default_context from urllib.request import urlopen from urllib.error import HTTPError, URLError data = None if (not n): url = 'https://xkcd.com/info.0.json' else: url = 'https://xkcd.com/{}/info.0.json'.format(n) try: with contextlib.closing(urlopen(url, context=default_context())) as f: data = f.read() except HTTPError as error: if (error.getcode() == 400): raise RuntimeError('could not obtain comic data from {}'.format(url)) except URLError: pass if (n == 1024): data = None if data: data = json.loads(data) img = data['img'] alt = data['alt'] title = data['safe_title'] link = 'http://xkcd.com/{}'.format(data['num']) return html(('<h1>{}</h1><img src="{}" title="{}">'.format(title, img, alt) + '<div>Source: <a href="{0}" target="_blank">{0}</a></div>'.format(link))) return html('<script> alert("Error: -41"); </script>')
def inverse_mod(a, m): '\n The inverse of the ring element a modulo m.\n\n If no special inverse_mod is defined for the elements, it tries to\n coerce them into integers and perform the inversion there\n\n ::\n\n sage: inverse_mod(7, 1)\n 0\n sage: inverse_mod(5, 14)\n 3\n sage: inverse_mod(3, -5)\n 2\n\n Tests with numpy and mpz numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: inverse_mod(int8(5), int8(14)) # needs numpy\n 3\n sage: from gmpy2 import mpz\n sage: inverse_mod(mpz(5), mpz(14))\n 3\n ' try: return a.inverse_mod(m) except AttributeError: return Integer(a).inverse_mod(m)
def get_gcd(order): '\n Return the fastest gcd function for integers of size no larger than\n order.\n\n EXAMPLES::\n\n sage: sage.arith.misc.get_gcd(4000)\n <built-in method gcd_int of sage.rings.fast_arith.arith_int object at ...>\n sage: sage.arith.misc.get_gcd(400000)\n <built-in method gcd_longlong of sage.rings.fast_arith.arith_llong object at ...>\n sage: sage.arith.misc.get_gcd(4000000000)\n <function gcd at ...>\n ' if (order <= 46340): return arith_int().gcd_int elif (order <= 2147483647): return arith_llong().gcd_longlong else: return gcd
def get_inverse_mod(order): '\n Return the fastest inverse_mod function for integers of size no\n larger than order.\n\n EXAMPLES::\n\n sage: sage.arith.misc.get_inverse_mod(6000)\n <built-in method inverse_mod_int of sage.rings.fast_arith.arith_int object at ...>\n sage: sage.arith.misc.get_inverse_mod(600000)\n <built-in method inverse_mod_longlong of sage.rings.fast_arith.arith_llong object at ...>\n sage: sage.arith.misc.get_inverse_mod(6000000000)\n <function inverse_mod at ...>\n ' if (order <= 46340): return arith_int().inverse_mod_int elif (order <= 2147483647): return arith_llong().inverse_mod_longlong else: return inverse_mod
def power_mod(a, n, m): '\n Return the `n`-th power of `a` modulo `m`, where `a` and `m`\n are elements of a ring that implements the modulo operator ``%``.\n\n ALGORITHM: square-and-multiply\n\n EXAMPLES::\n\n sage: power_mod(2, 388, 389)\n 1\n sage: power_mod(2, 390, 391)\n 285\n sage: power_mod(2, -1, 7)\n 4\n sage: power_mod(11, 1, 7)\n 4\n\n This function works for fairly general rings::\n\n sage: R.<x> = ZZ[]\n sage: power_mod(3*x, 10, 7)\n 4*x^10\n sage: power_mod(-3*x^2 + 4, 7, 2*x^3 - 5)\n x^14 + x^8 + x^6 + x^3 + 962509*x^2 - 791910*x - 698281\n\n TESTS::\n\n sage: power_mod(0,0,5)\n 1\n sage: power_mod(11,1,0)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: modulus must be nonzero\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int32 # needs numpy\n sage: power_mod(int32(2), int32(390), int32(391)) # needs numpy\n 285\n sage: from gmpy2 import mpz\n sage: power_mod(mpz(2), mpz(390), mpz(391))\n mpz(285)\n ' if (not m): raise ZeroDivisionError('modulus must be nonzero') a = (a % m) if (m == 1): return a.parent().zero() n = Integer(n) if (not n): return a.parent().one() if (n < 0): a = inverse_mod(a, m) n = (- n) apow = a while (not (n & 1)): apow = ((apow * apow) % m) n >>= 1 power = apow n >>= 1 while n: apow = ((apow * apow) % m) if (n & 1): power = ((power * apow) % m) n >>= 1 return power
def rational_reconstruction(a, m, algorithm='fast'): '\n This function tries to compute `x/y`, where `x/y` is a rational number in\n lowest terms such that the reduction of `x/y` modulo `m` is equal to `a` and\n the absolute values of `x` and `y` are both `\\le \\sqrt{m/2}`. If such `x/y`\n exists, that pair is unique and this function returns it. If no\n such pair exists, this function raises ZeroDivisionError.\n\n An efficient algorithm for computing rational reconstruction is\n very similar to the extended Euclidean algorithm. For more details,\n see Knuth, Vol 2, 3rd ed, pages 656-657.\n\n INPUT:\n\n - ``a`` -- an integer\n\n - ``m`` -- a modulus\n\n - ``algorithm`` -- (default: \'fast\')\n\n - ``\'fast\'`` - a fast implementation using direct GMP library calls\n in Cython.\n\n OUTPUT:\n\n Numerator and denominator `n`, `d` of the unique rational number\n `r=n/d`, if it exists, with `n` and `|d| \\le \\sqrt{N/2}`. Return\n `(0,0)` if no such number exists.\n\n The algorithm for rational reconstruction is described (with a\n complete nontrivial proof) on pages 656-657 of Knuth, Vol 2, 3rd\n ed. as the solution to exercise 51 on page 379. See in particular\n the conclusion paragraph right in the middle of page 657, which\n describes the algorithm thus:\n\n This discussion proves that the problem can be solved\n efficiently by applying Algorithm 4.5.2X with `u=m` and `v=a`,\n but with the following replacement for step X2: If\n `v3 \\le \\sqrt{m/2}`, the algorithm terminates. The pair\n `(x,y)=(|v2|,v3*\\mathrm{sign}(v2))` is then the unique\n solution, provided that `x` and `y` are coprime and\n `x \\le \\sqrt{m/2}`; otherwise there is no solution. (Alg 4.5.2X is\n the extended Euclidean algorithm.)\n\n Knuth remarks that this algorithm is due to Wang, Kornerup, and\n Gregory from around 1983.\n\n EXAMPLES::\n\n sage: m = 100000\n sage: (119*inverse_mod(53,m))%m\n 11323\n sage: rational_reconstruction(11323,m)\n 119/53\n\n ::\n\n sage: rational_reconstruction(400,1000)\n Traceback (most recent call last):\n ...\n ArithmeticError: rational reconstruction of 400 (mod 1000) does not exist\n\n ::\n\n sage: rational_reconstruction(3, 292393)\n 3\n sage: a = Integers(292393)(45/97); a\n 204977\n sage: rational_reconstruction(a, 292393, algorithm=\'fast\')\n 45/97\n sage: rational_reconstruction(293048, 292393)\n Traceback (most recent call last):\n ...\n ArithmeticError: rational reconstruction of 655 (mod 292393) does not exist\n sage: rational_reconstruction(0, 0)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: rational reconstruction with zero modulus\n sage: rational_reconstruction(0, 1, algorithm="foobar")\n Traceback (most recent call last):\n ...\n ValueError: unknown algorithm \'foobar\'\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int32 # needs numpy\n sage: rational_reconstruction(int32(3), int32(292393)) # needs numpy\n 3\n sage: from gmpy2 import mpz\n sage: rational_reconstruction(mpz(3), mpz(292393))\n 3\n ' if (algorithm == 'fast'): return ZZ(a).rational_reconstruction(ZZ(m)) else: raise ValueError(('unknown algorithm %r' % algorithm))
def mqrr_rational_reconstruction(u, m, T): '\n Maximal Quotient Rational Reconstruction.\n\n For research purposes only - this is pure Python, so slow.\n\n INPUT:\n\n - ``u, m, T`` - integers such that `m > u \\ge 0`, `T > 0`.\n\n OUTPUT:\n\n Either integers `n,d` such that `d>0`, `\\mathop{\\mathrm{gcd}}(n,d)=1`, `n/d=u \\bmod m`, and\n `T \\cdot d \\cdot |n| < m`, or ``None``.\n\n Reference: Monagan, Maximal Quotient Rational Reconstruction: An\n Almost Optimal Algorithm for Rational Reconstruction (page 11)\n\n This algorithm is probabilistic.\n\n EXAMPLES::\n\n sage: mqrr_rational_reconstruction(21, 3100, 13)\n (21, 1)\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int16 # needs numpy\n sage: mqrr_rational_reconstruction(int16(21), int16(3100), int16(13)) # needs numpy\n (21, 1)\n sage: from gmpy2 import mpz\n sage: mqrr_rational_reconstruction(mpz(21), mpz(3100), mpz(13))\n (21, 1)\n ' u = py_scalar_to_element(u) m = py_scalar_to_element(m) T = py_scalar_to_element(T) if (u == 0): if (m > T): return (0, 1) else: return None (n, d) = (0, 0) (t0, r0) = (0, m) (t1, r1) = (1, u) while ((r1 != 0) and (r0 > T)): q = (r0 / r1) if (q > T): (n, d, T) = (r1, t1, q) (r0, r1) = (r1, (r0 - (q * r1))) (t0, t1) = (t1, (t0 - (q * t1))) if ((d != 0) and (GCD(n, d) == 1)): return (n, d) return None
def trial_division(n, bound=None): '\n Return the smallest prime divisor <= bound of the positive integer\n n, or n if there is no such prime. If the optional argument bound\n is omitted, then bound <= n.\n\n INPUT:\n\n - ``n`` - a positive integer\n\n - ``bound`` - (optional) a positive integer\n\n OUTPUT:\n\n - ``int`` - a prime p=bound that divides n, or n if\n there is no such prime.\n\n\n EXAMPLES::\n\n sage: trial_division(15)\n 3\n sage: trial_division(91)\n 7\n sage: trial_division(11)\n 11\n sage: trial_division(387833, 300)\n 387833\n sage: # 300 is not big enough to split off a\n sage: # factor, but 400 is.\n sage: trial_division(387833, 400)\n 389\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: trial_division(int8(91)) # needs numpy\n 7\n sage: from gmpy2 import mpz\n sage: trial_division(mpz(91))\n 7\n ' if (bound is None): return ZZ(n).trial_division() else: return ZZ(n).trial_division(bound)
def factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds): '\n Return the factorization of ``n``. The result depends on the\n type of ``n``.\n\n If ``n`` is an integer, returns the factorization as an object\n of type :class:`Factorization`.\n\n If ``n`` is not an integer, ``n.factor(proof=proof, **kwds)`` gets called.\n See ``n.factor??`` for more documentation in this case.\n\n .. warning::\n\n This means that applying :func:`factor` to an integer result of\n a symbolic computation will not factor the integer, because it is\n considered as an element of a larger symbolic ring.\n\n EXAMPLES::\n\n sage: f(n) = n^2 # needs sage.symbolic\n sage: is_prime(f(3)) # needs sage.symbolic\n False\n sage: factor(f(3)) # needs sage.symbolic\n 9\n\n INPUT:\n\n - ``n`` -- a nonzero integer\n\n - ``proof`` -- bool or ``None`` (default: ``None``)\n\n - ``int_`` -- bool (default: ``False``) whether to return\n answers as Python ints\n\n - ``algorithm`` -- string\n\n - ``\'pari\'`` -- (default) use the PARI c library\n\n - ``\'kash\'`` -- use KASH computer algebra system (requires that\n kash be installed)\n\n - ``\'magma\'`` -- use Magma (requires magma be installed)\n\n - ``verbose`` -- integer (default: 0); PARI\'s debug\n variable is set to this; e.g., set to 4 or 8 to see lots of output\n during factorization.\n\n OUTPUT:\n\n - factorization of `n`\n\n The qsieve and ecm commands give access to highly optimized\n implementations of algorithms for doing certain integer\n factorization problems. These implementations are not used by the\n generic :func:`factor` command, which currently just calls PARI (note that\n PARI also implements sieve and ecm algorithms, but they are not as\n optimized). Thus you might consider using them instead for certain\n numbers.\n\n The factorization returned is an element of the class\n :class:`~sage.structure.factorization.Factorization`; use ``Factorization??``\n to see more details, and examples below for usage. A :class:`~sage.structure.factorization.Factorization` contains\n both the unit factor (`+1` or `-1`) and a sorted list of ``(prime, exponent)``\n pairs.\n\n The factorization displays in pretty-print format but it is easy to\n obtain access to the ``(prime, exponent)`` pairs and the unit, to\n recover the number from its factorization, and even to multiply two\n factorizations. See examples below.\n\n EXAMPLES::\n\n sage: factor(500)\n 2^2 * 5^3\n sage: factor(-20)\n -1 * 2^2 * 5\n sage: f=factor(-20)\n sage: list(f)\n [(2, 2), (5, 1)]\n sage: f.unit()\n -1\n sage: f.value()\n -20\n sage: factor(-next_prime(10^2) * next_prime(10^7)) # needs sage.libs.pari\n -1 * 101 * 10000019\n\n ::\n\n sage: factor(293292629867846432923017396246429, algorithm=\'flint\') # needs sage.libs.flint\n 3 * 4852301647696687 * 20148007492971089\n\n ::\n\n sage: factor(-500, algorithm=\'kash\')\n -1 * 2^2 * 5^3\n\n ::\n\n sage: factor(-500, algorithm=\'magma\') # optional - magma\n -1 * 2^2 * 5^3\n\n ::\n\n sage: factor(0)\n Traceback (most recent call last):\n ...\n ArithmeticError: factorization of 0 is not defined\n sage: factor(1)\n 1\n sage: factor(-1)\n -1\n sage: factor(2^(2^7) + 1) # needs sage.libs.pari\n 59649589127497217 * 5704689200685129054721\n\n Sage calls PARI\'s :pari:`factor`, which has ``proof=False`` by default.\n Sage has a global proof flag, set to ``True`` by default (see\n :mod:`sage.structure.proof.proof`, or use ``proof.[tab]``). To override\n the default, call this function with ``proof=False``.\n\n ::\n\n sage: factor(3^89 - 1, proof=False) # needs sage.libs.pari\n 2 * 179 * 1611479891519807 * 5042939439565996049162197\n\n ::\n\n sage: factor(2^197 + 1) # long time (2s) # needs sage.libs.pari\n 3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843\n\n Any object which has a factor method can be factored like this::\n\n sage: K.<i> = QuadraticField(-1) # needs sage.rings.number_field\n sage: factor(122 - 454*i) # needs sage.rings.number_field\n (-i) * (-i - 2)^3 * (i + 1)^3 * (-2*i + 3) * (i + 4)\n\n To access the data in a factorization::\n\n sage: # needs sage.libs.pari\n sage: f = factor(420); f\n 2^2 * 3 * 5 * 7\n sage: [x for x in f]\n [(2, 2), (3, 1), (5, 1), (7, 1)]\n sage: [p for p,e in f]\n [2, 3, 5, 7]\n sage: [e for p,e in f]\n [2, 1, 1, 1]\n sage: [p^e for p,e in f]\n [4, 3, 5, 7]\n\n We can factor Python, numpy and gmpy2 numbers::\n\n sage: factor(math.pi)\n 3.141592653589793\n sage: import numpy # needs numpy\n sage: factor(numpy.int8(30)) # needs numpy sage.libs.pari\n 2 * 3 * 5\n sage: import gmpy2\n sage: factor(gmpy2.mpz(30))\n 2 * 3 * 5\n\n TESTS::\n\n sage: factor(Mod(4, 100))\n Traceback (most recent call last):\n ...\n TypeError: unable to factor 4\n sage: factor("xyz")\n Traceback (most recent call last):\n ...\n TypeError: unable to factor \'xyz\'\n\n Test that :issue:`35219` is fixed::\n\n sage: len(factor(2^2203-1,proof=false))\n 1\n ' try: m = n.factor except AttributeError: e = py_scalar_to_element(n) if (e is n): raise TypeError('unable to factor {!r}'.format(n)) n = e m = n.factor if isinstance(n, Integer): return m(proof=proof, algorithm=algorithm, int_=int_, verbose=verbose, **kwds) try: return m(proof=proof, **kwds) except TypeError: return m(**kwds)
def radical(n, *args, **kwds): '\n Return the product of the prime divisors of n.\n\n This calls ``n.radical(*args, **kwds)``.\n\n EXAMPLES::\n\n sage: radical(2 * 3^2 * 5^5)\n 30\n sage: radical(0)\n Traceback (most recent call last):\n ...\n ArithmeticError: radical of 0 is not defined\n sage: K.<i> = QuadraticField(-1) # needs sage.rings.number_field\n sage: radical(K(2)) # needs sage.rings.number_field\n i + 1\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: radical(int8(50)) # needs numpy\n 10\n sage: from gmpy2 import mpz\n sage: radical(mpz(50))\n 10\n ' try: m = n.radical except AttributeError: e = py_scalar_to_element(n) if (e is n): m = factor(n, *args, **kwds).radical_value else: m = e.radical return m(*args, **kwds)
def prime_divisors(n): '\n Return the list of prime divisors (up to units) of this element\n of a unique factorization domain.\n\n INPUT:\n\n - ``n`` -- any object which can be decomposed into prime factors\n\n OUTPUT:\n\n A list of prime factors of ``n``. For integers, this list is sorted\n in increasing order.\n\n EXAMPLES:\n\n Prime divisors of positive integers::\n\n sage: prime_divisors(1)\n []\n sage: prime_divisors(100)\n [2, 5]\n sage: prime_divisors(2004)\n [2, 3, 167]\n\n If ``n`` is negative, we do *not* include -1 among the prime\n divisors, since -1 is not a prime number::\n\n sage: prime_divisors(-100)\n [2, 5]\n\n For polynomials we get all irreducible factors::\n\n sage: R.<x> = PolynomialRing(QQ)\n sage: prime_divisors(x^12 - 1) # needs sage.libs.pari\n [x - 1, x + 1, x^2 - x + 1, x^2 + 1, x^2 + x + 1, x^4 - x^2 + 1]\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: prime_divisors(int8(-100)) # needs numpy\n [2, 5]\n sage: from gmpy2 import mpz\n sage: prime_divisors(mpz(-100))\n [2, 5]\n ' try: return n.prime_divisors() except AttributeError: pass return [p for (p, _) in factor(n)]
def odd_part(n): '\n The odd part of the integer `n`. This is `n / 2^v`,\n where `v = \\mathrm{valuation}(n,2)`.\n\n EXAMPLES::\n\n sage: odd_part(5)\n 5\n sage: odd_part(4)\n 1\n sage: odd_part(factorial(31))\n 122529844256906551386796875\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: odd_part(int8(5)) # needs numpy\n 5\n sage: from gmpy2 import mpz\n sage: odd_part(mpz(5))\n 5\n ' if (not isinstance(n, Integer)): n = ZZ(n) return n.odd_part()
def prime_to_m_part(n, m): '\n Return the prime-to-``m`` part of ``n``.\n\n This is the largest divisor of ``n`` that is coprime to ``m``.\n\n INPUT:\n\n - ``n`` -- Integer (nonzero)\n\n - ``m`` -- Integer\n\n OUTPUT: Integer\n\n EXAMPLES::\n\n sage: prime_to_m_part(240,2)\n 15\n sage: prime_to_m_part(240,3)\n 80\n sage: prime_to_m_part(240,5)\n 48\n sage: prime_to_m_part(43434,20)\n 21717\n\n Note that integers also have a method with the same name::\n\n sage: 240.prime_to_m_part(2)\n 15\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int16 # needs numpy\n sage: prime_to_m_part(int16(240), int16(2)) # needs numpy\n 15\n sage: from gmpy2 import mpz\n sage: prime_to_m_part(mpz(240), mpz(2))\n 15\n ' return ZZ(n).prime_to_m_part(m)
def is_square(n, root=False): "\n Return whether or not ``n`` is square.\n\n If ``n`` is a square also return the square root.\n If ``n`` is not square, also return ``None``.\n\n INPUT:\n\n - ``n`` -- an integer\n\n - ``root`` -- whether or not to also return a square\n root (default: ``False``)\n\n OUTPUT:\n\n - ``bool`` -- whether or not a square\n\n - ``object`` -- (optional) an actual square if found,\n and ``None`` otherwise.\n\n EXAMPLES::\n\n sage: is_square(2)\n False\n sage: is_square(4)\n True\n sage: is_square(2.2)\n True\n sage: is_square(-2.2)\n False\n sage: is_square(CDF(-2.2)) # needs sage.rings.complex_double\n True\n sage: is_square((x-1)^2) # needs sage.symbolic\n Traceback (most recent call last):\n ...\n NotImplementedError: is_square() not implemented for\n non-constant or relational elements of Symbolic Ring\n\n ::\n\n sage: is_square(4, True)\n (True, 2)\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: is_square(int8(4)) # needs numpy\n True\n sage: from gmpy2 import mpz\n sage: is_square(mpz(4))\n True\n\n Tests with Polynomial::\n\n sage: R.<v> = LaurentPolynomialRing(QQ, 'v')\n sage: H = IwahoriHeckeAlgebra('A3', v**2) # needs sage.combinat sage.modules\n sage: R.<a,b,c,d> = QQ[]\n sage: p = a*b + c*d*a*d*a + 5\n sage: is_square(p**2)\n True\n " try: m = n.is_square except (AttributeError, NotImplementedError): n = py_scalar_to_element(n) m = n.is_square if root: try: return m(root) except TypeError: if m(): return (True, n.sqrt()) else: return (False, None) return m()
def is_squarefree(n): "\n Test whether ``n`` is square free.\n\n EXAMPLES::\n\n sage: is_squarefree(100) # needs sage.libs.pari\n False\n sage: is_squarefree(101) # needs sage.libs.pari\n True\n\n sage: R = ZZ['x']\n sage: x = R.gen()\n sage: is_squarefree((x^2+x+1) * (x-2)) # needs sage.libs.pari\n True\n sage: is_squarefree((x-1)**2 * (x-3)) # needs sage.libs.pari\n False\n\n sage: # needs sage.rings.number_field sage.symbolic\n sage: O = ZZ[sqrt(-1)]\n sage: I = O.gen(1)\n sage: is_squarefree(I + 1)\n True\n sage: is_squarefree(O(2))\n False\n sage: O(2).factor()\n (-I) * (I + 1)^2\n\n This method fails on domains which are not Unique Factorization Domains::\n\n sage: O = ZZ[sqrt(-5)] # needs sage.rings.number_field sage.symbolic\n sage: a = O.gen(1) # needs sage.rings.number_field sage.symbolic\n sage: is_squarefree(a - 3) # needs sage.rings.number_field sage.symbolic\n Traceback (most recent call last):\n ...\n ArithmeticError: non-principal ideal in factorization\n\n Tests with numpy and gmpy2 numbers::\n\n sage: # needs sage.libs.pari\n sage: from numpy import int8 # needs numpy\n sage: is_squarefree(int8(100)) # needs numpy\n False\n sage: is_squarefree(int8(101)) # needs numpy\n True\n sage: from gmpy2 import mpz\n sage: is_squarefree(mpz(100))\n False\n sage: is_squarefree(mpz(101))\n True\n " e = py_scalar_to_element(n) try: return e.is_squarefree() except AttributeError: pass if (e == 0): return False return all(((r[1] == 1) for r in factor(e)))
class Euler_Phi(): "\n Return the value of the Euler phi function on the integer n. We\n defined this to be the number of positive integers <= n that are\n relatively prime to n. Thus if n<=0 then\n ``euler_phi(n)`` is defined and equals 0.\n\n INPUT:\n\n\n - ``n`` - an integer\n\n\n EXAMPLES::\n\n sage: euler_phi(1)\n 1\n sage: euler_phi(2)\n 1\n sage: euler_phi(3) # needs sage.libs.pari\n 2\n sage: euler_phi(12) # needs sage.libs.pari\n 4\n sage: euler_phi(37) # needs sage.libs.pari\n 36\n\n Notice that euler_phi is defined to be 0 on negative numbers and\n 0.\n\n ::\n\n sage: euler_phi(-1)\n 0\n sage: euler_phi(0)\n 0\n sage: type(euler_phi(0))\n <class 'sage.rings.integer.Integer'>\n\n We verify directly that the phi function is correct for 21.\n\n ::\n\n sage: euler_phi(21) # needs sage.libs.pari\n 12\n sage: [i for i in range(21) if gcd(21,i) == 1]\n [1, 2, 4, 5, 8, 10, 11, 13, 16, 17, 19, 20]\n\n The length of the list of integers 'i' in range(n) such that the\n gcd(i,n) == 1 equals euler_phi(n).\n\n ::\n\n sage: len([i for i in range(21) if gcd(21,i) == 1]) == euler_phi(21) # needs sage.libs.pari\n True\n\n The phi function also has a special plotting method.\n\n ::\n\n sage: P = plot(euler_phi, -3, 71) # needs sage.libs.pari sage.plot\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: euler_phi(int8(37)) # needs numpy sage.libs.pari\n 36\n sage: from gmpy2 import mpz\n sage: euler_phi(mpz(37)) # needs sage.libs.pari\n 36\n\n AUTHORS:\n\n - William Stein\n\n - Alex Clemesha (2006-01-10): some examples\n " def __repr__(self): "\n Return a string describing this class.\n\n EXAMPLES::\n\n sage: from sage.arith.misc import Euler_Phi\n sage: Euler_Phi().__repr__()\n 'Number of positive integers <=n but relatively prime to n'\n " return 'Number of positive integers <=n but relatively prime to n' def __call__(self, n): '\n Calls the euler_phi function.\n\n EXAMPLES::\n\n sage: from sage.arith.misc import Euler_Phi\n sage: Euler_Phi()(10) # needs sage.libs.pari\n 4\n sage: Euler_Phi()(720) # needs sage.libs.pari\n 192\n ' if (n <= 0): return ZZ.zero() if (n <= 2): return ZZ.one() from sage.libs.pari.all import pari return ZZ(pari(n).eulerphi()) def plot(self, xmin=1, xmax=50, pointsize=30, rgbcolor=(0, 0, 1), join=True, **kwds): '\n Plot the Euler phi function.\n\n INPUT:\n\n\n - ``xmin`` - default: 1\n\n - ``xmax`` - default: 50\n\n - ``pointsize`` - default: 30\n\n - ``rgbcolor`` - default: (0,0,1)\n\n - ``join`` - default: True; whether to join the\n points.\n\n - ``**kwds`` - passed on\n\n EXAMPLES::\n\n sage: from sage.arith.misc import Euler_Phi\n sage: p = Euler_Phi().plot() # needs sage.libs.pari sage.plot\n sage: p.ymax() # needs sage.libs.pari sage.plot\n 46.0\n ' v = [(n, euler_phi(n)) for n in range(xmin, (xmax + 1))] from sage.plot.all import list_plot P = list_plot(v, pointsize=pointsize, rgbcolor=rgbcolor, **kwds) if join: P += list_plot(v, plotjoined=True, rgbcolor=(0.7, 0.7, 0.7), **kwds) return P
def carmichael_lambda(n): "\n Return the Carmichael function of a positive integer ``n``.\n\n The Carmichael function of `n`, denoted `\\lambda(n)`, is the smallest\n positive integer `k` such that `a^k \\equiv 1 \\pmod{n}` for all\n `a \\in \\ZZ/n\\ZZ` satisfying `\\gcd(a, n) = 1`. Thus, `\\lambda(n) = k`\n is the exponent of the multiplicative group `(\\ZZ/n\\ZZ)^{\\ast}`.\n\n INPUT:\n\n - ``n`` -- a positive integer.\n\n OUTPUT:\n\n - The Carmichael function of ``n``.\n\n ALGORITHM:\n\n If `n = 2, 4` then `\\lambda(n) = \\varphi(n)`. Let `p \\geq 3` be an odd\n prime and let `k` be a positive integer. Then\n `\\lambda(p^k) = p^{k - 1}(p - 1) = \\varphi(p^k)`. If `k \\geq 3`, then\n `\\lambda(2^k) = 2^{k - 2}`. Now consider the case where `n > 3` is\n composite and let `n = p_1^{k_1} p_2^{k_2} \\cdots p_t^{k_t}` be the\n prime factorization of `n`. Then\n\n .. MATH::\n\n \\lambda(n)\n = \\lambda(p_1^{k_1} p_2^{k_2} \\cdots p_t^{k_t})\n = \\text{lcm}(\\lambda(p_1^{k_1}), \\lambda(p_2^{k_2}), \\dots, \\lambda(p_t^{k_t}))\n\n EXAMPLES:\n\n The Carmichael function of all positive integers up to and including 10::\n\n sage: from sage.arith.misc import carmichael_lambda\n sage: list(map(carmichael_lambda, [1..10]))\n [1, 1, 2, 2, 4, 2, 6, 2, 6, 4]\n\n The Carmichael function of the first ten primes::\n\n sage: list(map(carmichael_lambda, primes_first_n(10))) # needs sage.libs.pari\n [1, 2, 4, 6, 10, 12, 16, 18, 22, 28]\n\n Cases where the Carmichael function is equivalent to the Euler phi\n function::\n\n sage: carmichael_lambda(2) == euler_phi(2)\n True\n sage: carmichael_lambda(4) == euler_phi(4) # needs sage.libs.pari\n True\n sage: p = random_prime(1000, lbound=3, proof=True) # needs sage.libs.pari\n sage: k = randint(1, 1000)\n sage: carmichael_lambda(p^k) == euler_phi(p^k) # needs sage.libs.pari\n True\n\n A case where `\\lambda(n) \\neq \\varphi(n)`::\n\n sage: k = randint(3, 1000)\n sage: carmichael_lambda(2^k) == 2^(k - 2) # needs sage.libs.pari\n True\n sage: carmichael_lambda(2^k) == 2^(k - 2) == euler_phi(2^k) # needs sage.libs.pari\n False\n\n Verifying the current implementation of the Carmichael function using\n another implementation. The other implementation that we use for\n verification is an exhaustive search for the exponent of the\n multiplicative group `(\\ZZ/n\\ZZ)^{\\ast}`. ::\n\n sage: from sage.arith.misc import carmichael_lambda\n sage: n = randint(1, 500)\n sage: c = carmichael_lambda(n)\n sage: def coprime(n):\n ....: return [i for i in range(n) if gcd(i, n) == 1]\n sage: def znpower(n, k):\n ....: L = coprime(n)\n ....: return list(map(power_mod, L, [k]*len(L), [n]*len(L)))\n sage: def my_carmichael(n):\n ....: if n == 1:\n ....: return 1\n ....: for k in range(1, n):\n ....: L = znpower(n, k)\n ....: ones = [1] * len(L)\n ....: T = [L[i] == ones[i] for i in range(len(L))]\n ....: if all(T):\n ....: return k\n sage: c == my_carmichael(n)\n True\n\n Carmichael's theorem states that `a^{\\lambda(n)} \\equiv 1 \\pmod{n}`\n for all elements `a` of the multiplicative group `(\\ZZ/n\\ZZ)^{\\ast}`.\n Here, we verify Carmichael's theorem. ::\n\n sage: from sage.arith.misc import carmichael_lambda\n sage: n = randint(2, 1000)\n sage: c = carmichael_lambda(n)\n sage: ZnZ = IntegerModRing(n)\n sage: M = ZnZ.list_of_elements_of_multiplicative_group()\n sage: ones = [1] * len(M)\n sage: P = [power_mod(a, c, n) for a in M]\n sage: P == ones\n True\n\n TESTS:\n\n The input ``n`` must be a positive integer::\n\n sage: from sage.arith.misc import carmichael_lambda\n sage: carmichael_lambda(0)\n Traceback (most recent call last):\n ...\n ValueError: Input n must be a positive integer.\n sage: carmichael_lambda(randint(-10, 0))\n Traceback (most recent call last):\n ...\n ValueError: Input n must be a positive integer.\n\n Bug reported in :trac:`8283`::\n\n sage: from sage.arith.misc import carmichael_lambda\n sage: type(carmichael_lambda(16))\n <class 'sage.rings.integer.Integer'>\n\n REFERENCES:\n\n - :wikipedia:`Carmichael_function`\n " n = Integer(n) if (n < 1): raise ValueError('Input n must be a positive integer.') L = list(n.factor()) t = [] if ((n & 1) == 0): (two, e) = L.pop(0) assert (two == 2) k = ((e - 2) if (e >= 3) else (e - 1)) t.append((1 << k)) t += [((p ** (k - 1)) * (p - 1)) for (p, k) in L] return LCM_list(t)
def crt(a, b, m=None, n=None): "\n Return a solution to a Chinese Remainder Theorem problem.\n\n INPUT:\n\n - ``a``, ``b`` - two residues (elements of some ring for which\n extended gcd is available), or two lists, one of residues and\n one of moduli.\n\n - ``m``, ``n`` - (default: ``None``) two moduli, or ``None``.\n\n OUTPUT:\n\n If ``m``, ``n`` are not ``None``, returns a solution `x` to the\n simultaneous congruences `x\\equiv a \\bmod m` and `x\\equiv b \\bmod\n n`, if one exists. By the Chinese Remainder Theorem, a solution to the\n simultaneous congruences exists if and only if\n `a\\equiv b\\pmod{\\gcd(m,n)}`. The solution `x` is only well-defined modulo\n `\\text{lcm}(m,n)`.\n\n If ``a`` and ``b`` are lists, returns a simultaneous solution to\n the congruences `x\\equiv a_i\\pmod{b_i}`, if one exists.\n\n .. SEEALSO::\n\n - :func:`CRT_list`\n\n EXAMPLES:\n\n Using ``crt`` by giving it pairs of residues and moduli::\n\n sage: crt(2, 1, 3, 5)\n 11\n sage: crt(13, 20, 100, 301)\n 28013\n sage: crt([2, 1], [3, 5])\n 11\n sage: crt([13, 20], [100, 301])\n 28013\n\n You can also use upper case::\n\n sage: c = CRT(2,3, 3, 5); c\n 8\n sage: c % 3 == 2\n True\n sage: c % 5 == 3\n True\n\n Note that this also works for polynomial rings::\n\n sage: # needs sage.rings.number_field\n sage: x = polygen(ZZ, 'x')\n sage: K.<a> = NumberField(x^3 - 7)\n sage: R.<y> = K[]\n sage: f = y^2 + 3\n sage: g = y^3 - 5\n sage: CRT(1, 3, f, g)\n -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26\n sage: CRT(1, a, f, g)\n (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52\n\n You can also do this for any number of moduli::\n\n sage: # needs sage.rings.number_field\n sage: K.<a> = NumberField(x^3 - 7)\n sage: R.<x> = K[]\n sage: CRT([], [])\n 0\n sage: CRT([a], [x])\n a\n sage: f = x^2 + 3\n sage: g = x^3 - 5\n sage: h = x^5 + x^2 - 9\n sage: k = CRT([1, a, 3], [f, g, h]); k\n (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8\n + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6\n + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4\n + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2\n + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828\n sage: k.mod(f)\n 1\n sage: k.mod(g)\n a\n sage: k.mod(h)\n 3\n\n If the moduli are not coprime, a solution may not exist::\n\n sage: crt(4, 8, 8, 12)\n 20\n sage: crt(4, 6, 8, 12)\n Traceback (most recent call last):\n ...\n ValueError: no solution to crt problem since gcd(8,12) does not divide 4-6\n\n sage: x = polygen(QQ)\n sage: crt(2, 3, x - 1, x + 1)\n -1/2*x + 5/2\n sage: crt(2, x, x^2 - 1, x^2 + 1)\n -1/2*x^3 + x^2 + 1/2*x + 1\n sage: crt(2, x, x^2 - 1, x^3 - 1)\n Traceback (most recent call last):\n ...\n ValueError: no solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x\n\n sage: crt(int(2), int(3), int(7), int(11))\n 58\n\n crt also work with numpy and gmpy2 numbers::\n\n sage: import numpy # needs numpy\n sage: crt(numpy.int8(2), numpy.int8(3), numpy.int8(7), numpy.int8(11)) # needs numpy\n 58\n sage: from gmpy2 import mpz\n sage: crt(mpz(2), mpz(3), mpz(7), mpz(11))\n 58\n sage: crt(mpz(2), 3, mpz(7), numpy.int8(11)) # needs numpy\n 58\n " if isinstance(a, list): return CRT_list(a, b) try: f = (b - a).quo_rem except (TypeError, AttributeError): a = py_scalar_to_element(a) b = py_scalar_to_element(b) f = (b - a).quo_rem (g, alpha, beta) = XGCD(m, n) (q, r) = f(g) if (r != 0): raise ValueError(('no solution to crt problem since gcd(%s,%s) does not divide %s-%s' % (m, n, a, b))) from sage.arith.functions import lcm x = (a + ((q * alpha) * py_scalar_to_element(m))) return (x % lcm(m, n))
def CRT_list(values, moduli): ' Given a list ``values`` of elements and a list of corresponding\n ``moduli``, find a single element that reduces to each element of\n ``values`` modulo the corresponding moduli.\n\n .. SEEALSO::\n\n - :func:`crt`\n\n EXAMPLES::\n\n sage: CRT_list([2,3,2], [3,5,7])\n 23\n sage: x = polygen(QQ)\n sage: c = CRT_list([3], [x]); c\n 3\n sage: c.parent()\n Univariate Polynomial Ring in x over Rational Field\n\n It also works if the moduli are not coprime::\n\n sage: CRT_list([32,2,2],[60,90,150])\n 452\n\n But with non coprime moduli there is not always a solution::\n\n sage: CRT_list([32,2,1],[60,90,150])\n Traceback (most recent call last):\n ...\n ValueError: no solution to crt problem since gcd(180,150) does not divide 92-1\n\n The arguments must be lists::\n\n sage: CRT_list([1,2,3],"not a list")\n Traceback (most recent call last):\n ...\n ValueError: arguments to CRT_list should be lists\n sage: CRT_list("not a list",[2,3])\n Traceback (most recent call last):\n ...\n ValueError: arguments to CRT_list should be lists\n\n The list of moduli must have the same length as the list of elements::\n\n sage: CRT_list([1,2,3],[2,3,5])\n 23\n sage: CRT_list([1,2,3],[2,3])\n Traceback (most recent call last):\n ...\n ValueError: arguments to CRT_list should be lists of the same length\n sage: CRT_list([1,2,3],[2,3,5,7])\n Traceback (most recent call last):\n ...\n ValueError: arguments to CRT_list should be lists of the same length\n\n TESTS::\n\n sage: CRT([32r,2r,2r],[60r,90r,150r])\n 452\n sage: from numpy import int8 # needs numpy\n sage: CRT_list([int8(2), int8(3), int8(2)], [int8(3), int8(5), int8(7)]) # needs numpy\n 23\n sage: from gmpy2 import mpz\n sage: CRT_list([mpz(2),mpz(3),mpz(2)], [mpz(3),mpz(5),mpz(7)])\n 23\n\n Make sure we are not mutating the input lists::\n\n sage: xs = [1,2,3]\n sage: ms = [5,7,9]\n sage: CRT_list(xs, ms)\n 156\n sage: xs\n [1, 2, 3]\n sage: ms\n [5, 7, 9]\n ' if ((not isinstance(values, list)) or (not isinstance(moduli, list))): raise ValueError('arguments to CRT_list should be lists') if (len(values) != len(moduli)): raise ValueError('arguments to CRT_list should be lists of the same length') if (not values): return ZZ.zero() if (len(values) == 1): return moduli[0].parent()(values[0]) from sage.arith.functions import lcm while (len(values) > 1): (vs, ms) = (values[::2], moduli[::2]) for (i, (v, m)) in enumerate(zip(values[1::2], moduli[1::2])): vs[i] = CRT(vs[i], v, ms[i], m) ms[i] = lcm(ms[i], m) (values, moduli) = (vs, ms) return (values[0] % moduli[0])
def CRT_basis(moduli): '\n Return a CRT basis for the given moduli.\n\n INPUT:\n\n - ``moduli`` - list of pairwise coprime moduli `m` which admit an\n extended Euclidean algorithm\n\n OUTPUT:\n\n - a list of elements `a_i` of the same length as `m` such that\n `a_i` is congruent to 1 modulo `m_i` and to 0 modulo `m_j` for\n `j\\not=i`.\n\n EXAMPLES::\n\n sage: a1 = ZZ(mod(42,5))\n sage: a2 = ZZ(mod(42,13))\n sage: c1,c2 = CRT_basis([5,13])\n sage: mod(a1*c1+a2*c2,5*13)\n 42\n\n A polynomial example::\n\n sage: x=polygen(QQ)\n sage: mods = [x,x^2+1,2*x-3]\n sage: b = CRT_basis(mods)\n sage: b\n [-2/3*x^3 + x^2 - 2/3*x + 1, 6/13*x^3 - x^2 + 6/13*x, 8/39*x^3 + 8/39*x]\n sage: [[bi % mj for mj in mods] for bi in b]\n [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n ' n = len(moduli) if (n == 0): return [] M = prod(moduli) cs = [] for m in moduli: Mm = (M // m) (d, _, v) = xgcd(m, Mm) if (not d.is_one()): raise ValueError('moduli must be coprime') cs.append(((v * Mm) % M)) return cs
def CRT_vectors(X, moduli): '\n Vector form of the Chinese Remainder Theorem: given a list of integer\n vectors `v_i` and a list of coprime moduli `m_i`, find a vector `w` such\n that `w = v_i \\pmod m_i` for all `i`. This is more efficient than applying\n :func:`CRT` to each entry.\n\n INPUT:\n\n - ``X`` - list or tuple, consisting of lists/tuples/vectors/etc of\n integers of the same length\n - ``moduli`` - list of len(X) moduli\n\n OUTPUT:\n\n - ``list`` - application of CRT componentwise.\n\n EXAMPLES::\n\n sage: CRT_vectors([[3,5,7],[3,5,11]], [2,3])\n [3, 5, 5]\n\n sage: CRT_vectors([vector(ZZ, [2,3,1]), Sequence([1,7,8], ZZ)], [8,9]) # needs sage.modules\n [10, 43, 17]\n ' if ((len(X) == 0) or (len(X[0]) == 0)): return [] n = len(X) if (n != len(moduli)): raise ValueError('number of moduli must equal length of X') a = CRT_basis(moduli) modulus = prod(moduli) return [(sum(((a[i] * X[i][j]) for i in range(n))) % modulus) for j in range(len(X[0]))]
def binomial(x, m, **kwds): "\n Return the binomial coefficient\n\n .. MATH::\n\n \\binom{x}{m} = x (x-1) \\cdots (x-m+1) / m!\n\n which is defined for `m \\in \\ZZ` and any\n `x`. We extend this definition to include cases when\n `x-m` is an integer but `m` is not by\n\n .. MATH::\n\n \\binom{x}{m} = \\binom{x}{x-m}\n\n If `m < 0`, return `0`.\n\n INPUT:\n\n - ``x``, ``m`` - numbers or symbolic expressions. Either ``m``\n or ``x-m`` must be an integer.\n\n OUTPUT: number or symbolic expression (if input is symbolic)\n\n EXAMPLES::\n\n sage: from sage.arith.misc import binomial\n sage: binomial(5, 2)\n 10\n sage: binomial(2, 0)\n 1\n sage: binomial(1/2, 0) # needs sage.libs.pari\n 1\n sage: binomial(3, -1)\n 0\n sage: binomial(20, 10)\n 184756\n sage: binomial(-2, 5)\n -6\n sage: binomial(-5, -2)\n 0\n sage: binomial(RealField()('2.5'), 2) # needs sage.rings.real_mpfr\n 1.87500000000000\n sage: binomial(Zp(5)(99),50)\n 3 + 4*5^3 + 2*5^4 + 4*5^5 + 4*5^6 + 4*5^7 + 4*5^8 + 5^9 + 2*5^10 + 3*5^11 +\n 4*5^12 + 4*5^13 + 2*5^14 + 3*5^15 + 3*5^16 + 4*5^17 + 4*5^18 + 2*5^19 + O(5^20)\n sage: binomial(Qp(3)(2/3),2)\n 2*3^-2 + 2*3^-1 + 2 + 2*3 + 2*3^2 + 2*3^3 + 2*3^4 + 2*3^5 + 2*3^6 + 2*3^7 +\n 2*3^8 + 2*3^9 + 2*3^10 + 2*3^11 + 2*3^12 + 2*3^13 + 2*3^14 + 2*3^15 + 2*3^16 + 2*3^17 + O(3^18)\n sage: n = var('n'); binomial(n, 2) # needs sage.symbolic\n 1/2*(n - 1)*n\n sage: n = var('n'); binomial(n, n) # needs sage.symbolic\n 1\n sage: n = var('n'); binomial(n, n - 1) # needs sage.symbolic\n n\n sage: binomial(2^100, 2^100)\n 1\n\n sage: x = polygen(ZZ)\n sage: binomial(x, 3)\n 1/6*x^3 - 1/2*x^2 + 1/3*x\n sage: binomial(x, x - 3)\n 1/6*x^3 - 1/2*x^2 + 1/3*x\n\n If `x \\in \\ZZ`, there is an optional 'algorithm' parameter, which\n can be 'gmp' (faster for small values; alias: 'mpir') or\n 'pari' (faster for large values)::\n\n sage: a = binomial(100, 45, algorithm='gmp')\n sage: b = binomial(100, 45, algorithm='pari') # needs sage.libs.pari\n sage: a == b # needs sage.libs.pari\n True\n\n TESTS:\n\n We test that certain binomials are very fast (this should be\n instant) -- see :trac:`3309`::\n\n sage: a = binomial(RR(1140000.78), 23310000)\n\n We test conversion of arguments to Integers -- see :trac:`6870`::\n\n sage: binomial(1/2, 1/1) # needs sage.libs.pari\n 1/2\n sage: binomial(10^20 + 1/1, 10^20)\n 100000000000000000001\n sage: binomial(SR(10**7), 10**7) # needs sage.symbolic\n 1\n sage: binomial(3/2, SR(1/1)) # needs sage.symbolic\n 3/2\n\n Some floating point cases -- see :trac:`7562`, :trac:`9633`, and\n :trac:`12448`::\n\n sage: binomial(1., 3)\n 0.000000000000000\n sage: binomial(-2., 3)\n -4.00000000000000\n sage: binomial(0.5r, 5)\n 0.02734375\n sage: a = binomial(float(1001), float(1)); a\n 1001.0\n sage: type(a)\n <class 'float'>\n sage: binomial(float(1000), 1001)\n 0.0\n\n Test more output types::\n\n sage: type(binomial(5r, 2))\n <class 'int'>\n sage: type(binomial(5, 2r))\n <class 'sage.rings.integer.Integer'>\n\n sage: type(binomial(5.0r, 2))\n <class 'float'>\n\n sage: type(binomial(5/1, 2))\n <class 'sage.rings.rational.Rational'>\n\n sage: R = Integers(11)\n sage: b = binomial(R(7), R(3))\n sage: b\n 2\n sage: b.parent()\n Ring of integers modulo 11\n\n Test symbolic and uni/multivariate polynomials::\n\n sage: x = polygen(ZZ)\n sage: binomial(x, 3)\n 1/6*x^3 - 1/2*x^2 + 1/3*x\n sage: binomial(x, 3).parent()\n Univariate Polynomial Ring in x over Rational Field\n\n sage: K.<x,y> = Integers(7)[]\n sage: binomial(y,3)\n 6*y^3 + 3*y^2 + 5*y\n sage: binomial(y,3).parent()\n Multivariate Polynomial Ring in x, y over Ring of integers modulo 7\n\n sage: n = var('n') # needs sage.symbolic\n sage: binomial(n,2) # needs sage.symbolic\n 1/2*(n - 1)*n\n\n Test p-adic numbers::\n\n sage: binomial(Qp(3)(-1/2),4) # p-adic number with valuation >= 0\n 1 + 3 + 2*3^2 + 3^3 + 2*3^4 + 3^6 + 3^7 + 3^8 + 3^11 + 2*3^14 + 2*3^16 + 2*3^17 + 2*3^19 + O(3^20)\n\n Check that :trac:`35811` is fixed::\n\n sage: binomial(Qp(3)(1/3),4) # p-adic number with negative valuation\n 2*3^-5 + 2*3^-4 + 3^-3 + 2*3^-2 + 2*3^-1 + 2 + 2*3 + 2*3^2 + 2*3^3 + 2*3^4 + 2*3^5 +\n 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^10 + 2*3^11 + 2*3^12 + 2*3^13 + 2*3^14 + O(3^15)\n\n sage: binomial(Qp(3)(1/3),10).parent()\n 3-adic Field with capped relative precision 20\n\n sage: F.<w>=Qq(9); binomial(w,4) # p-adic extension field\n (w + 2)*3^-1 + (w + 1) + (2*w + 1)*3 + 2*w*3^2 + (2*w + 2)*3^3 + 2*w*3^4 + (2*w + 2)*3^5 +\n 2*w*3^6 + (2*w + 2)*3^7 + 2*w*3^8 + (2*w + 2)*3^9 + 2*w*3^10 + (2*w + 2)*3^11 + 2*w*3^12 +\n (2*w + 2)*3^13 + 2*w*3^14 + (2*w + 2)*3^15 + 2*w*3^16 + (2*w + 2)*3^17 + 2*w*3^18 + O(3^19)\n sage: F.<w>=Qq(9); binomial(w,10).parent()\n 3-adic Unramified Extension Field in w defined by x^2 + 2*x + 2\n\n Invalid inputs::\n\n sage: x = polygen(ZZ)\n sage: binomial(x, x^2)\n Traceback (most recent call last):\n ...\n TypeError: either m or x-m must be an integer\n\n sage: k, i = var('k,i') # needs sage.symbolic\n sage: binomial(k,i) # needs sage.symbolic\n Traceback (most recent call last):\n ...\n TypeError: either m or x-m must be an integer\n\n sage: R6 = Zmod(6)\n sage: binomial(R6(5), 2)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: factorial(2) not invertible in Ring of integers modulo 6\n\n sage: R7 = Zmod(7)\n sage: binomial(R7(10), 7)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: factorial(7) not invertible in Ring of integers modulo 7\n\n The last two examples failed to execute since `2!` and `7!` are respectively\n not invertible in `\\ZZ/6\\ZZ` and `\\ZZ/7\\ZZ`. One can check that there\n is no well defined value for that binomial coefficient in the quotient::\n\n sage: R6(binomial(5,2))\n 4\n sage: R6(binomial(5+6,2))\n 1\n\n sage: R7(binomial(3, 7))\n 0\n sage: R7(binomial(10, 7))\n 1\n sage: R7(binomial(17, 7))\n 2\n\n For symbolic manipulation, you should use the function\n :func:`~sage.functions.other.binomial` from the module\n :mod:`sage.functions.other`::\n\n sage: from sage.functions.other import binomial\n sage: binomial(k, i) # needs sage.symbolic\n binomial(k, i)\n\n binomial support numpy and gmpy2 parameters::\n\n sage: from sage.arith.misc import binomial\n sage: import numpy # needs numpy\n sage: binomial(numpy.int32(20), numpy.int32(10)) # needs numpy\n 184756\n sage: import gmpy2\n sage: binomial(gmpy2.mpz(20), gmpy2.mpz(10))\n mpz(184756)\n " try: m = ZZ(m) except TypeError: try: m = ZZ((x - m)) except TypeError: raise TypeError('either m or x-m must be an integer') P = parent(x) x = py_scalar_to_element(x) try: return P(x.binomial(m, **kwds)) except (AttributeError, TypeError): pass try: x = ZZ(x) except (TypeError, ValueError): pass else: try: c = P.characteristic() except AttributeError: pass else: if ((c > 0) and any(((c.gcd(k) > 1) for k in range(2, (m + 1))))): raise ZeroDivisionError('factorial({}) not invertible in {}'.format(m, P)) return P(x.binomial(m, **kwds)) if (isinstance(x, Rational) or isinstance(P, (RealField, ComplexField))): return P(x.__pari__().binomial(m)) if (m < ZZ.zero()): return P(0) return (P(prod(((x - i) for i in range(m)))) / m.factorial())
def multinomial(*ks): '\n Return the multinomial coefficient.\n\n INPUT:\n\n - either an arbitrary number of integer arguments `k_1,\\dots,k_n`\n - or an iterable (e.g. a list) of integers `[k_1,\\dots,k_n]`\n\n OUTPUT:\n\n Return the integer:\n\n .. MATH::\n\n \\binom{k_1 + \\cdots + k_n}{k_1, \\cdots, k_n}\n =\\frac{\\left(\\sum_{i=1}^n k_i\\right)!}{\\prod_{i=1}^n k_i!}\n = \\prod_{i=1}^n \\binom{\\sum_{j=1}^i k_j}{k_i}\n\n EXAMPLES::\n\n sage: multinomial(0, 0, 2, 1, 0, 0)\n 3\n sage: multinomial([0, 0, 2, 1, 0, 0])\n 3\n sage: multinomial(3, 2)\n 10\n sage: multinomial(2^30, 2, 1)\n 618970023101454657175683075\n sage: multinomial([2^30, 2, 1])\n 618970023101454657175683075\n sage: multinomial(Composition([1, 3]))\n 4\n sage: multinomial(Partition([4, 2])) # needs sage.combinat\n 15\n\n TESTS:\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: multinomial(int8(3), int8(2)) # needs numpy\n 10\n sage: from gmpy2 import mpz\n sage: multinomial(mpz(3), mpz(2))\n mpz(10)\n\n sage: multinomial(range(1), range(2))\n Traceback (most recent call last):\n ...\n ValueError: multinomial takes only one iterable argument\n\n AUTHORS:\n\n - Gabriel Ebner\n ' if isinstance(ks[0], Iterable): if (len(ks) > 1): raise ValueError('multinomial takes only one iterable argument') keys = ks[0] else: keys = ks (s, c) = (0, 1) for k in keys: s += k c *= binomial(s, k) return c
def binomial_coefficients(n): '\n Return a dictionary containing pairs\n `\\{(k_1,k_2) : C_{k,n}\\}` where `C_{k_n}` are\n binomial coefficients and `n = k_1 + k_2`.\n\n INPUT:\n\n\n - ``n`` - an integer\n\n\n OUTPUT: dict\n\n EXAMPLES::\n\n sage: sorted(binomial_coefficients(3).items())\n [((0, 3), 1), ((1, 2), 3), ((2, 1), 3), ((3, 0), 1)]\n\n Notice the coefficients above are the same as below::\n\n sage: R.<x,y> = QQ[]\n sage: (x+y)^3\n x^3 + 3*x^2*y + 3*x*y^2 + y^3\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: sorted(binomial_coefficients(int8(3)).items()) # needs numpy\n [((0, 3), 1), ((1, 2), 3), ((2, 1), 3), ((3, 0), 1)]\n sage: from gmpy2 import mpz\n sage: sorted(binomial_coefficients(mpz(3)).items())\n [((0, 3), 1), ((1, 2), 3), ((2, 1), 3), ((3, 0), 1)]\n\n AUTHORS:\n\n - Fredrik Johansson\n ' n = py_scalar_to_element(n) d = {(0, n): 1, (n, 0): 1} a = 1 for k in range(1, ((n // 2) + 1)): a = ((a * ((n - k) + 1)) // k) d[(k, (n - k))] = d[((n - k), k)] = a return d
def multinomial_coefficients(m, n): '\n Return a dictionary containing pairs\n `\\{(k_1, k_2, ..., k_m) : C_{k, n}\\}` where\n `C_{k, n}` are multinomial coefficients such that\n `n = k_1 + k_2 + ...+ k_m`.\n\n INPUT:\n\n - ``m`` - integer\n - ``n`` - integer\n\n OUTPUT: dict\n\n EXAMPLES::\n\n sage: sorted(multinomial_coefficients(2, 5).items())\n [((0, 5), 1), ((1, 4), 5), ((2, 3), 10), ((3, 2), 10), ((4, 1), 5), ((5, 0), 1)]\n\n Notice that these are the coefficients of `(x+y)^5`::\n\n sage: R.<x,y> = QQ[]\n sage: (x+y)^5\n x^5 + 5*x^4*y + 10*x^3*y^2 + 10*x^2*y^3 + 5*x*y^4 + y^5\n\n ::\n\n sage: sorted(multinomial_coefficients(3, 2).items())\n [((0, 0, 2), 1), ((0, 1, 1), 2), ((0, 2, 0), 1), ((1, 0, 1), 2), ((1, 1, 0), 2), ((2, 0, 0), 1)]\n\n ALGORITHM: The algorithm we implement for computing the multinomial\n coefficients is based on the following result:\n\n .. MATH::\n\n \\binom{n}{k_1, \\cdots, k_m} =\n \\frac{k_1+1}{n-k_1}\\sum_{i=2}^m \\binom{n}{k_1+1, \\cdots, k_i-1, \\cdots}\n\n e.g.::\n\n sage: k = (2, 4, 1, 0, 2, 6, 0, 0, 3, 5, 7, 1) # random value\n sage: n = sum(k)\n sage: s = 0\n sage: for i in range(1, len(k)):\n ....: ki = list(k)\n ....: ki[0] += 1\n ....: ki[i] -= 1\n ....: s += multinomial(n, *ki)\n sage: multinomial(n, *k) == (k[0] + 1) / (n - k[0]) * s\n True\n\n TESTS::\n\n sage: multinomial_coefficients(0, 0)\n {(): 1}\n sage: multinomial_coefficients(0, 3)\n {}\n sage: from numpy import int8 # needs numpy\n sage: sorted(multinomial_coefficients(int8(2), int8(5)).items()) # needs numpy\n [((0, 5), 1), ((1, 4), 5), ((2, 3), 10), ((3, 2), 10), ((4, 1), 5), ((5, 0), 1)]\n sage: from gmpy2 import mpz\n sage: sorted(multinomial_coefficients(mpz(2), mpz(5)).items())\n [((0, 5), 1), ((1, 4), 5), ((2, 3), 10), ((3, 2), 10), ((4, 1), 5), ((5, 0), 1)]\n ' if (not m): if n: return {} else: return {(): 1} m = py_scalar_to_element(m) n = py_scalar_to_element(n) if (m == 2): return binomial_coefficients(n) t = ([n] + ([0] * (m - 1))) r = {tuple(t): 1} if n: j = 0 else: j = m while (j < (m - 1)): tj = t[j] if j: t[j] = 0 t[0] = tj if (tj > 1): t[(j + 1)] += 1 j = 0 start = 1 v = 0 else: j += 1 start = (j + 1) v = r[tuple(t)] t[j] += 1 for k in range(start, m): if t[k]: t[k] -= 1 v += r[tuple(t)] t[k] += 1 t[0] -= 1 r[tuple(t)] = ((v * tj) // (n - t[0])) return r
def kronecker_symbol(x, y): '\n The Kronecker symbol `(x|y)`.\n\n INPUT:\n\n - ``x`` -- integer\n\n - ``y`` -- integer\n\n OUTPUT:\n\n - an integer\n\n EXAMPLES::\n\n sage: kronecker_symbol(13,21)\n -1\n sage: kronecker_symbol(101,4)\n 1\n\n This is also available as :func:`kronecker`::\n\n sage: kronecker(3,5)\n -1\n sage: kronecker(3,15)\n 0\n sage: kronecker(2,15)\n 1\n sage: kronecker(-2,15)\n -1\n sage: kronecker(2/3,5)\n 1\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: kronecker_symbol(int8(13),int8(21)) # needs numpy\n -1\n sage: from gmpy2 import mpz\n sage: kronecker_symbol(mpz(13),mpz(21))\n -1\n ' x = (QQ(x).numerator() * QQ(x).denominator()) return ZZ(x.kronecker(y))
def legendre_symbol(x, p): '\n The Legendre symbol `(x|p)`, for `p` prime.\n\n .. note::\n\n The :func:`kronecker_symbol` command extends the Legendre\n symbol to composite moduli and `p=2`.\n\n INPUT:\n\n\n - ``x`` - integer\n\n - ``p`` - an odd prime number\n\n\n EXAMPLES::\n\n sage: legendre_symbol(2,3)\n -1\n sage: legendre_symbol(1,3)\n 1\n sage: legendre_symbol(1,2)\n Traceback (most recent call last):\n ...\n ValueError: p must be odd\n sage: legendre_symbol(2,15)\n Traceback (most recent call last):\n ...\n ValueError: p must be a prime\n sage: kronecker_symbol(2,15)\n 1\n sage: legendre_symbol(2/3,7)\n -1\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: legendre_symbol(int8(2), int8(3)) # needs numpy\n -1\n sage: from gmpy2 import mpz\n sage: legendre_symbol(mpz(2),mpz(3))\n -1\n ' x = (QQ(x).numerator() * QQ(x).denominator()) p = ZZ(p) if (not p.is_prime()): raise ValueError('p must be a prime') if (p == 2): raise ValueError('p must be odd') return x.kronecker(p)
def jacobi_symbol(a, b): '\n The Jacobi symbol of integers a and b, where b is odd.\n\n .. note::\n\n The :func:`kronecker_symbol` command extends the Jacobi\n symbol to all integers b.\n\n If\n\n `b = p_1^{e_1} * ... * p_r^{e_r}`\n\n then\n\n `(a|b) = (a|p_1)^{e_1} ... (a|p_r)^{e_r}`\n\n where `(a|p_j)` are Legendre Symbols.\n\n\n\n INPUT:\n\n - ``a`` - an integer\n\n - ``b`` - an odd integer\n\n EXAMPLES::\n\n sage: jacobi_symbol(10,777)\n -1\n sage: jacobi_symbol(10,5)\n 0\n sage: jacobi_symbol(10,2)\n Traceback (most recent call last):\n ...\n ValueError: second input must be odd, 2 is not odd\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int16 # needs numpy\n sage: jacobi_symbol(int16(10), int16(777)) # needs numpy\n -1\n sage: from gmpy2 import mpz\n sage: jacobi_symbol(mpz(10),mpz(777))\n -1\n ' if ((b % 2) == 0): raise ValueError(('second input must be odd, %s is not odd' % b)) return kronecker_symbol(a, b)
def primitive_root(n, check=True): '\n Return a positive integer that generates the multiplicative group\n of integers modulo `n`, if one exists; otherwise, raise a\n :class:`ValueError`.\n\n A primitive root exists if `n=4` or `n=p^k` or `n=2p^k`, where `p`\n is an odd prime and `k` is a nonnegative number.\n\n INPUT:\n\n - ``n`` -- a non-zero integer\n - ``check`` -- bool (default: True); if False, then `n` is assumed\n to be a positive integer possessing a primitive root, and behavior\n is undefined otherwise.\n\n OUTPUT:\n\n A primitive root of `n`. If `n` is prime, this is the smallest\n primitive root.\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: primitive_root(23)\n 5\n sage: primitive_root(-46)\n 5\n sage: primitive_root(25)\n 2\n sage: print([primitive_root(p) for p in primes(100)])\n [1, 2, 2, 3, 2, 2, 3, 2, 5, 2, 3, 2, 6, 3, 5, 2, 2, 2, 2, 7, 5, 3, 2, 3, 5]\n sage: primitive_root(8)\n Traceback (most recent call last):\n ...\n ValueError: no primitive root\n\n .. NOTE::\n\n It takes extra work to check if `n` has a primitive root; to\n avoid this, use ``check=False``, which may slightly speed things\n up (but could also result in undefined behavior). For example,\n the second call below is an order of magnitude faster than the\n first:\n\n ::\n\n sage: n = 10^50 + 151 # a prime\n sage: primitive_root(n) # needs sage.libs.pari\n 11\n sage: primitive_root(n, check=False) # needs sage.libs.pari\n 11\n\n TESTS:\n\n Various special cases::\n\n sage: # needs sage.libs.pari\n sage: primitive_root(-1)\n 0\n sage: primitive_root(0)\n Traceback (most recent call last):\n ...\n ValueError: no primitive root\n sage: primitive_root(1)\n 0\n sage: primitive_root(2)\n 1\n sage: primitive_root(3)\n 2\n sage: primitive_root(4)\n 3\n\n We test that various numbers without primitive roots give\n an error - see :trac:`10836`::\n\n sage: # needs sage.libs.pari\n sage: primitive_root(15)\n Traceback (most recent call last):\n ...\n ValueError: no primitive root\n sage: primitive_root(16)\n Traceback (most recent call last):\n ...\n ValueError: no primitive root\n sage: primitive_root(1729)\n Traceback (most recent call last):\n ...\n ValueError: no primitive root\n sage: primitive_root(4*7^8)\n Traceback (most recent call last):\n ...\n ValueError: no primitive root\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: primitive_root(int8(-46)) # needs numpy sage.libs.pari\n 5\n sage: from gmpy2 import mpz\n sage: primitive_root(mpz(-46)) # needs sage.libs.pari\n 5\n ' from sage.libs.pari.all import pari if (not check): return ZZ(pari(n).znprimroot()) n = ZZ(n).abs() if (n <= 4): if n: return (n - 1) elif (n % 2): if n.is_prime_power(): return ZZ(pari(n).znprimroot()) else: m = (n // 2) if ((m % 2) and m.is_prime_power()): return ZZ(pari(n).znprimroot()) raise ValueError('no primitive root')
def nth_prime(n): '\n\n Return the n-th prime number (1-indexed, so that 2 is the 1st prime.)\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n - the n-th prime number\n\n EXAMPLES::\n\n sage: nth_prime(3) # needs sage.libs.pari\n 5\n sage: nth_prime(10) # needs sage.libs.pari\n 29\n sage: nth_prime(10^7) # needs sage.libs.pari\n 179424673\n\n ::\n\n sage: nth_prime(0)\n Traceback (most recent call last):\n ...\n ValueError: nth prime meaningless for non-positive n (=0)\n\n TESTS::\n\n sage: all(prime_pi(nth_prime(j)) == j for j in range(1, 1000, 10)) # needs sage.libs.pari sage.symbolic\n True\n sage: from numpy import int8 # needs numpy\n sage: nth_prime(int8(10)) # needs numpy sage.libs.pari\n 29\n sage: from gmpy2 import mpz\n sage: nth_prime(mpz(10)) # needs sage.libs.pari\n 29\n ' if (n <= 0): raise ValueError(('nth prime meaningless for non-positive n (=%s)' % n)) from sage.libs.pari.all import pari return ZZ(pari.prime(n))
def quadratic_residues(n): '\n Return a sorted list of all squares modulo the integer `n`\n in the range `0\\leq x < |n|`.\n\n EXAMPLES::\n\n sage: quadratic_residues(11)\n [0, 1, 3, 4, 5, 9]\n sage: quadratic_residues(1)\n [0]\n sage: quadratic_residues(2)\n [0, 1]\n sage: quadratic_residues(8)\n [0, 1, 4]\n sage: quadratic_residues(-10)\n [0, 1, 4, 5, 6, 9]\n sage: v = quadratic_residues(1000); len(v)\n 159\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: quadratic_residues(int8(11)) # needs numpy\n [0, 1, 3, 4, 5, 9]\n sage: from gmpy2 import mpz\n sage: quadratic_residues(mpz(11))\n [0, 1, 3, 4, 5, 9]\n ' n = abs(int(n)) return sorted(set((ZZ(((a * a) % n)) for a in range(((n // 2) + 1)))))
class Moebius(): "\n Return the value of the Möbius function of abs(n), where n is an\n integer.\n\n DEFINITION: `\\mu(n)` is 0 if `n` is not square\n free, and otherwise equals `(-1)^r`, where `n` has\n `r` distinct prime factors.\n\n For simplicity, if `n=0` we define `\\mu(n) = 0`.\n\n IMPLEMENTATION: Factors or - for integers - uses the PARI C\n library.\n\n INPUT:\n\n\n - ``n`` - anything that can be factored.\n\n\n OUTPUT: 0, 1, or -1\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: moebius(-5)\n -1\n sage: moebius(9)\n 0\n sage: moebius(12)\n 0\n sage: moebius(-35)\n 1\n sage: moebius(-1)\n 1\n sage: moebius(7)\n -1\n\n ::\n\n sage: moebius(0) # potentially nonstandard!\n 0\n\n The moebius function even makes sense for non-integer inputs.\n\n ::\n\n sage: x = GF(7)['x'].0\n sage: moebius(x + 2) # needs sage.libs.pari\n -1\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: moebius(int8(-5)) # needs numpy sage.libs.pari\n -1\n sage: from gmpy2 import mpz\n sage: moebius(mpz(-5)) # needs sage.libs.pari\n -1\n " def __call__(self, n): '\n EXAMPLES::\n\n sage: from sage.arith.misc import Moebius\n sage: Moebius().__call__(7) # needs sage.libs.pari\n -1\n ' n = py_scalar_to_element(n) if (not isinstance(n, Integer)): if (n < 0): n = (- n) F = factor(n) for (_, e) in F: if (e >= 2): return 0 return ((- 1) ** len(F)) if (n == 0): return ZZ.zero() from sage.libs.pari.all import pari return ZZ(pari(n).moebius()) def __repr__(self): "\n Return a description of this function.\n\n EXAMPLES::\n\n sage: from sage.arith.misc import Moebius\n sage: q = Moebius()\n sage: q.__repr__()\n 'The Moebius function'\n " return 'The Moebius function' def plot(self, xmin=0, xmax=50, pointsize=30, rgbcolor=(0, 0, 1), join=True, **kwds): '\n Plot the Möbius function.\n\n INPUT:\n\n\n - ``xmin`` - default: 0\n\n - ``xmax`` - default: 50\n\n - ``pointsize`` - default: 30\n\n - ``rgbcolor`` - default: (0,0,1)\n\n - ``join`` - default: True; whether to join the points\n (very helpful in seeing their order).\n\n - ``**kwds`` - passed on\n\n EXAMPLES::\n\n sage: from sage.arith.misc import Moebius\n sage: p = Moebius().plot() # needs sage.libs.pari sage.plot\n sage: p.ymax() # needs sage.libs.pari sage.plot\n 1.0\n ' values = self.range(xmin, (xmax + 1)) v = [(n, values[(n - xmin)]) for n in range(xmin, (xmax + 1))] from sage.plot.all import list_plot P = list_plot(v, pointsize=pointsize, rgbcolor=rgbcolor, **kwds) if join: P += list_plot(v, plotjoined=True, rgbcolor=(0.7, 0.7, 0.7), **kwds) return P def range(self, start, stop=None, step=None): '\n Return the Möbius function evaluated at the given range of values,\n i.e., the image of the list range(start, stop, step) under the\n Möbius function.\n\n This is much faster than directly computing all these values with a\n list comprehension.\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: v = moebius.range(-10, 10); v\n [1, 0, 0, -1, 1, -1, 0, -1, -1, 1, 0, 1, -1, -1, 0, -1, 1, -1, 0, 0]\n sage: v == [moebius(n) for n in range(-10, 10)]\n True\n sage: v = moebius.range(-1000, 2000, 4)\n sage: v == [moebius(n) for n in range(-1000, 2000, 4)]\n True\n ' if (stop is None): (start, stop) = (1, int(start)) else: start = int(start) stop = int(stop) if (step is None): step = 1 else: step = int(step) if ((start <= 0 < stop) and ((start % step) == 0)): return ((self.range(start, 0, step) + [ZZ.zero()]) + self.range(step, stop, step)) from sage.libs.pari.all import pari if (step == 1): v = pari(('vector(%s, i, moebius(i-1+%s))' % ((stop - start), start))) else: n = len(range(start, stop, step)) v = pari(('vector(%s, i, moebius(%s*(i-1) + %s))' % (n, step, start))) return [Integer(x) for x in v]
def continuant(v, n=None): "\n Function returns the continuant of the sequence `v` (list\n or tuple).\n\n Definition: see Graham, Knuth and Patashnik, *Concrete Mathematics*,\n section 6.7: Continuants. The continuant is defined by\n\n - `K_0() = 1`\n - `K_1(x_1) = x_1`\n - `K_n(x_1, \\cdots, x_n) = K_{n-1}(x_n, \\cdots x_{n-1})x_n + K_{n-2}(x_1, \\cdots, x_{n-2})`\n\n If ``n = None`` or ``n > len(v)`` the default\n ``n = len(v)`` is used.\n\n INPUT:\n\n - ``v`` - list or tuple of elements of a ring\n - ``n`` - optional integer\n\n OUTPUT: element of ring (integer, polynomial, etcetera).\n\n EXAMPLES::\n\n sage: continuant([1,2,3])\n 10\n sage: p = continuant([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10])\n sage: q = continuant([1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10])\n sage: p/q\n 517656/190435\n sage: F = continued_fraction([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10])\n sage: F.convergent(14)\n 517656/190435\n sage: x = PolynomialRing(RationalField(), 'x', 5).gens()\n sage: continuant(x)\n x0*x1*x2*x3*x4 + x0*x1*x2 + x0*x1*x4 + x0*x3*x4 + x2*x3*x4 + x0 + x2 + x4\n sage: continuant(x, 3)\n x0*x1*x2 + x0 + x2\n sage: continuant(x, 2)\n x0*x1 + 1\n\n We verify the identity\n\n .. MATH::\n\n K_n(z,z,\\cdots,z) = \\sum_{k=0}^n \\binom{n-k}{k} z^{n-2k}\n\n for `n = 6` using polynomial arithmetic::\n\n sage: z = QQ['z'].0\n sage: continuant((z,z,z,z,z,z,z,z,z,z,z,z,z,z,z), 6)\n z^6 + 5*z^4 + 6*z^2 + 1\n\n sage: continuant(9)\n Traceback (most recent call last):\n ...\n TypeError: object of type 'sage.rings.integer.Integer' has no len()\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: continuant([int8(1), int8(2), int8(3)]) # needs numpy\n 10\n sage: from gmpy2 import mpz\n sage: continuant([mpz(1), mpz(2), mpz(3)])\n mpz(10)\n\n AUTHORS:\n\n - Jaap Spies (2007-02-06)\n " m = len(v) if ((n is None) or (m < n)): n = m if (n == 0): return 1 if (n == 1): return v[0] (a, b) = (1, v[0]) for k in range(1, n): (a, b) = (b, (a + (b * v[k]))) return b
def number_of_divisors(n): '\n Return the number of divisors of the integer n.\n\n INPUT:\n\n - ``n`` - a nonzero integer\n\n OUTPUT:\n\n - an integer, the number of divisors of n\n\n EXAMPLES::\n\n sage: number_of_divisors(100) # needs sage.libs.pari\n 9\n sage: number_of_divisors(-720) # needs sage.libs.pari\n 30\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: number_of_divisors(int8(100)) # needs numpy sage.libs.pari\n 9\n sage: from gmpy2 import mpz\n sage: number_of_divisors(mpz(100)) # needs sage.libs.pari\n 9\n ' m = ZZ(n) if m.is_zero(): raise ValueError('input must be nonzero') from sage.libs.pari.all import pari return ZZ(pari(m).numdiv())
def hilbert_symbol(a, b, p, algorithm='pari'): "\n Return 1 if `ax^2 + by^2` `p`-adically represents\n a nonzero square, otherwise returns `-1`. If either a or b\n is 0, returns 0.\n\n INPUT:\n\n\n - ``a, b`` - integers\n\n - ``p`` - integer; either prime or -1 (which\n represents the archimedean place)\n\n - ``algorithm`` - string\n\n - ``'pari'`` - (default) use the PARI C library\n\n - ``'direct'`` - use a Python implementation\n\n - ``'all'`` - use both PARI and direct and check that\n the results agree, then return the common answer\n\n\n OUTPUT: integer (0, -1, or 1)\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: hilbert_symbol(-1, -1, -1, algorithm='all')\n -1\n sage: hilbert_symbol(2, 3, 5, algorithm='all')\n 1\n sage: hilbert_symbol(4, 3, 5, algorithm='all')\n 1\n sage: hilbert_symbol(0, 3, 5, algorithm='all')\n 0\n sage: hilbert_symbol(-1, -1, 2, algorithm='all')\n -1\n sage: hilbert_symbol(1, -1, 2, algorithm='all')\n 1\n sage: hilbert_symbol(3, -1, 2, algorithm='all')\n -1\n\n sage: hilbert_symbol(QQ(-1)/QQ(4), -1, 2) == -1 # needs sage.libs.pari\n True\n sage: hilbert_symbol(QQ(-1)/QQ(4), -1, 3) == 1 # needs sage.libs.pari\n True\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: hilbert_symbol(int8(2), int8(3), int8(5), algorithm='all') # needs numpy sage.libs.pari\n 1\n sage: from gmpy2 import mpz\n sage: hilbert_symbol(mpz(2), mpz(3), mpz(5), algorithm='all') # needs sage.libs.pari\n 1\n\n AUTHORS:\n\n - William Stein and David Kohel (2006-01-05)\n " p = ZZ(p) if ((p != (- 1)) and (not p.is_prime())): raise ValueError('p must be prime or -1') a = (QQ(a).numerator() * QQ(a).denominator()) b = (QQ(b).numerator() * QQ(b).denominator()) if (algorithm == 'pari'): if (p == (- 1)): p = 0 from sage.libs.pari.all import pari return ZZ(pari(a).hilbert(b, p)) elif (algorithm == 'direct'): if ((a == 0) or (b == 0)): return ZZ(0) p = ZZ(p) one = ZZ(1) if (p != (- 1)): p_sqr = (p ** 2) while ((a % p_sqr) == 0): a //= p_sqr while ((b % p_sqr) == 0): b //= p_sqr if ((p != 2) and (True in ((kronecker(x, p) == 1) for x in (a, b, (a + b))))): return one if ((a % p) == 0): if ((b % p) == 0): return (hilbert_symbol(p, (- (b // p)), p) * hilbert_symbol((a // p), b, p)) elif ((p == 2) and ((b % 4) == 3)): if (kronecker((a + b), p) == (- 1)): return (- one) elif (kronecker(b, p) == (- 1)): return (- one) elif ((b % p) == 0): if ((p == 2) and ((a % 4) == 3)): if (kronecker((a + b), p) == (- 1)): return (- one) elif (kronecker(a, p) == (- 1)): return (- one) elif ((p == 2) and ((a % 4) == 3) and ((b % 4) == 3)): return (- one) return one elif (algorithm == 'all'): ans_pari = hilbert_symbol(a, b, p, algorithm='pari') ans_direct = hilbert_symbol(a, b, p, algorithm='direct') if (ans_pari != ans_direct): raise RuntimeError(('there is a bug in hilbert_symbol; two ways of computing the Hilbert symbol (%s,%s)_%s disagree' % (a, b, p))) return ans_pari else: raise ValueError(f'algorithm {algorithm} not defined')
def hilbert_conductor(a, b): '\n Return the product of all (finite) primes where the Hilbert symbol is -1.\n\n This is the (reduced) discriminant of the quaternion algebra `(a,b)`\n over `\\QQ`.\n\n INPUT:\n\n - ``a``, ``b`` -- integers\n\n OUTPUT:\n\n squarefree positive integer\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: hilbert_conductor(-1, -1)\n 2\n sage: hilbert_conductor(-1, -11)\n 11\n sage: hilbert_conductor(-2, -5)\n 5\n sage: hilbert_conductor(-3, -17)\n 17\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: hilbert_conductor(int8(-3), int8(-17)) # needs numpy sage.libs.pari\n 17\n sage: from gmpy2 import mpz\n sage: hilbert_conductor(mpz(-3), mpz(-17)) # needs sage.libs.pari\n 17\n\n AUTHOR:\n\n - Gonzalo Tornaria (2009-03-02)\n ' (a, b) = (ZZ(a), ZZ(b)) return ZZ.prod((p for p in set([2]).union(prime_divisors(a), prime_divisors(b)) if (hilbert_symbol(a, b, p) == (- 1))))
def hilbert_conductor_inverse(d): '\n Finds a pair of integers `(a,b)` such that ``hilbert_conductor(a,b) == d``.\n\n The quaternion algebra `(a,b)` over `\\QQ` will then have (reduced)\n discriminant `d`.\n\n INPUT:\n\n - ``d`` -- square-free positive integer\n\n OUTPUT: pair of integers\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: hilbert_conductor_inverse(2)\n (-1, -1)\n sage: hilbert_conductor_inverse(3)\n (-1, -3)\n sage: hilbert_conductor_inverse(6)\n (-1, 3)\n sage: hilbert_conductor_inverse(30)\n (-3, -10)\n sage: hilbert_conductor_inverse(4)\n Traceback (most recent call last):\n ...\n ValueError: d needs to be squarefree\n sage: hilbert_conductor_inverse(-1)\n Traceback (most recent call last):\n ...\n ValueError: d needs to be positive\n\n AUTHOR:\n\n - Gonzalo Tornaria (2009-03-02)\n\n TESTS::\n\n sage: for i in range(100): # needs sage.libs.pari\n ....: d = ZZ.random_element(2**32).squarefree_part()\n ....: if hilbert_conductor(*hilbert_conductor_inverse(d)) != d:\n ....: print("hilbert_conductor_inverse failed for d = {}".format(d))\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: hilbert_conductor_inverse(int8(30)) # needs numpy sage.libs.pari\n (-3, -10)\n sage: from gmpy2 import mpz\n sage: hilbert_conductor_inverse(mpz(30)) # needs sage.libs.pari\n (-3, -10)\n ' Z = ZZ d = Z(d) if (d <= 0): raise ValueError('d needs to be positive') if (d == 1): return (Z((- 1)), Z(1)) if (d == 2): return (Z((- 1)), Z((- 1))) if d.is_prime(): if ((d % 4) == 3): return (Z((- 1)), (- d)) if ((d % 8) == 5): return (Z((- 2)), (- d)) q = 3 while (((q % 4) != 3) or (kronecker_symbol(d, q) != (- 1))): q = next_prime(q) return (Z((- q)), (- d)) else: mo = moebius(d) if (mo == 0): raise ValueError('d needs to be squarefree') if (((d % 2) == 0) and (((mo * d) % 16) != 2)): dd = ((mo * d) / 2) else: dd = (mo * d) q = 1 while (hilbert_conductor((- q), dd) != d): q += 1 if ((dd % q) == 0): dd /= q return (Z((- q)), Z(dd))
def falling_factorial(x, a): "\n Return the falling factorial `(x)_a`.\n\n The notation in the literature is a mess: often `(x)_a`,\n but there are many other notations: GKP: Concrete Mathematics uses\n `x^{\\underline{a}}`.\n\n Definition: for integer `a \\ge 0` we have\n `x(x-1) \\cdots (x-a+1)`. In all other cases we use the\n GAMMA-function: `\\frac {\\Gamma(x+1)} {\\Gamma(x-a+1)}`.\n\n INPUT:\n\n - ``x`` -- element of a ring\n\n - ``a`` -- a non-negative integer or\n\n - ``x and a`` -- any numbers\n\n OUTPUT: the falling factorial\n\n .. SEEALSO:: :func:`rising_factorial`\n\n EXAMPLES::\n\n sage: falling_factorial(10, 3)\n 720\n sage: falling_factorial(10, 10)\n 3628800\n sage: factorial(10)\n 3628800\n\n sage: # needs sage.symbolic\n sage: falling_factorial(10, RR('3.0'))\n 720.000000000000\n sage: falling_factorial(10, RR('3.3'))\n 1310.11633396601\n sage: a = falling_factorial(1 + I, I); a\n gamma(I + 2)\n sage: CC(a)\n 0.652965496420167 + 0.343065839816545*I\n sage: falling_factorial(1 + I, 4)\n 4*I + 2\n sage: falling_factorial(I, 4)\n -10\n\n sage: M = MatrixSpace(ZZ, 4, 4) # needs sage.modules\n sage: A = M([1,0,1,0, 1,0,1,0, 1,0,10,10, 1,0,1,1]) # needs sage.modules\n sage: falling_factorial(A, 2) # A(A - I) # needs sage.modules\n [ 1 0 10 10]\n [ 1 0 10 10]\n [ 20 0 101 100]\n [ 2 0 11 10]\n\n sage: x = ZZ['x'].0\n sage: falling_factorial(x, 4)\n x^4 - 6*x^3 + 11*x^2 - 6*x\n\n TESTS:\n\n Check that :trac:`14858` is fixed::\n\n sage: falling_factorial(-4, SR(2)) # needs sage.symbolic\n 20\n\n Check that :trac:`16770` is fixed::\n\n sage: d = var('d') # needs sage.symbolic\n sage: parent(falling_factorial(d, 0)) # needs sage.symbolic\n Symbolic Ring\n\n Check that :trac:`20075` is fixed::\n\n sage: bool(falling_factorial(int(4), int(2)) == falling_factorial(4,2))\n True\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: falling_factorial(int8(10), int8(3)) # needs numpy\n 720\n sage: from gmpy2 import mpz\n sage: falling_factorial(mpz(10), mpz(3))\n 720\n\n AUTHORS:\n\n - Jaap Spies (2006-03-05)\n " from sage.structure.element import Expression x = py_scalar_to_element(x) a = py_scalar_to_element(a) if ((isinstance(a, Integer) or (isinstance(a, Expression) and a.is_integer())) and (a >= 0)): return prod(((x - i) for i in range(a)), z=x.parent().one()) from sage.functions.all import gamma return (gamma((x + 1)) / gamma(((x - a) + 1)))
def rising_factorial(x, a): "\n Return the rising factorial `(x)^a`.\n\n The notation in the literature is a mess: often `(x)^a`,\n but there are many other notations: GKP: Concrete Mathematics uses\n `x^{\\overline{a}}`.\n\n The rising factorial is also known as the Pochhammer symbol, see\n Maple and Mathematica.\n\n Definition: for integer `a \\ge 0` we have\n `x(x+1) \\cdots (x+a-1)`. In all other cases we use the\n GAMMA-function: `\\frac {\\Gamma(x+a)} {\\Gamma(x)}`.\n\n INPUT:\n\n - ``x`` -- element of a ring\n\n - ``a`` -- a non-negative integer or\n\n - ``x and a`` -- any numbers\n\n OUTPUT: the rising factorial\n\n .. SEEALSO:: :func:`falling_factorial`\n\n EXAMPLES::\n\n sage: rising_factorial(10,3)\n 1320\n\n sage: # needs sage.symbolic\n sage: rising_factorial(10, RR('3.0'))\n 1320.00000000000\n sage: rising_factorial(10, RR('3.3'))\n 2826.38895824964\n sage: a = rising_factorial(1+I, I); a\n gamma(2*I + 1)/gamma(I + 1)\n sage: CC(a)\n 0.266816390637832 + 0.122783354006372*I\n sage: a = rising_factorial(I, 4); a\n -10\n\n sage: x = polygen(ZZ)\n sage: rising_factorial(x, 4)\n x^4 + 6*x^3 + 11*x^2 + 6*x\n\n TESTS:\n\n Check that :trac:`14858` is fixed::\n\n sage: bool(rising_factorial(-4, 2) == # needs sage.symbolic\n ....: rising_factorial(-4, SR(2)) ==\n ....: rising_factorial(SR(-4), SR(2)))\n True\n\n Check that :trac:`16770` is fixed::\n\n sage: d = var('d') # needs sage.symbolic\n sage: parent(rising_factorial(d, 0)) # needs sage.symbolic\n Symbolic Ring\n\n Check that :trac:`20075` is fixed::\n\n sage: bool(rising_factorial(int(4), int(2)) == rising_factorial(4,2))\n True\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: rising_factorial(int8(10), int8(3)) # needs numpy\n 1320\n sage: from gmpy2 import mpz\n sage: rising_factorial(mpz(10), mpz(3))\n 1320\n\n AUTHORS:\n\n - Jaap Spies (2006-03-05)\n " from sage.structure.element import Expression x = py_scalar_to_element(x) a = py_scalar_to_element(a) if ((isinstance(a, Integer) or (isinstance(a, Expression) and a.is_integer())) and (a >= 0)): return prod(((x + i) for i in range(a)), z=x.parent().one()) from sage.functions.all import gamma return (gamma((x + a)) / gamma(x))
def integer_ceil(x): '\n Return the ceiling of x.\n\n EXAMPLES::\n\n sage: integer_ceil(5.4)\n 6\n sage: integer_ceil(x) # needs sage.symbolic\n Traceback (most recent call last):\n ...\n NotImplementedError: computation of ceil of x not implemented\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import float32 # needs numpy\n sage: integer_ceil(float32(5.4)) # needs numpy\n 6\n sage: from gmpy2 import mpfr\n sage: integer_ceil(mpfr(5.4))\n 6\n ' try: return ZZ(x.ceil()) except AttributeError: try: return ZZ(math.ceil(float(x))) except TypeError: pass raise NotImplementedError(('computation of ceil of %s not implemented' % x))
def integer_floor(x): '\n Return the largest integer `\\leq x`.\n\n INPUT:\n\n - ``x`` - an object that has a floor method or is\n coercible to int\n\n OUTPUT: an Integer\n\n EXAMPLES::\n\n sage: integer_floor(5.4)\n 5\n sage: integer_floor(float(5.4))\n 5\n sage: integer_floor(-5/2)\n -3\n sage: integer_floor(RDF(-5/2))\n -3\n\n sage: integer_floor(x) # needs sage.symbolic\n Traceback (most recent call last):\n ...\n NotImplementedError: computation of floor of x not implemented\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import float32 # needs numpy\n sage: integer_floor(float32(5.4)) # needs numpy\n 5\n sage: from gmpy2 import mpfr\n sage: integer_floor(mpfr(5.4))\n 5\n ' try: return ZZ(x.floor()) except AttributeError: try: return ZZ(math.floor(float(x))) except TypeError: pass raise NotImplementedError(('computation of floor of %s not implemented' % x))
def integer_trunc(i): '\n Truncate to the integer closer to zero\n\n EXAMPLES::\n\n sage: from sage.arith.misc import integer_trunc as trunc\n sage: trunc(-3/2), trunc(-1), trunc(-1/2), trunc(0), trunc(1/2), trunc(1), trunc(3/2)\n (-1, -1, 0, 0, 0, 1, 1)\n sage: isinstance(trunc(3/2), Integer)\n True\n ' if (i >= 0): return integer_floor(i) else: return integer_ceil(i)
def two_squares(n): '\n Write the integer `n` as a sum of two integer squares if possible;\n otherwise raise a :class:`ValueError`.\n\n INPUT:\n\n - ``n`` -- an integer\n\n OUTPUT: a tuple `(a,b)` of non-negative integers such that\n `n = a^2 + b^2` with `a <= b`.\n\n EXAMPLES::\n\n sage: two_squares(389)\n (10, 17)\n sage: two_squares(21)\n Traceback (most recent call last):\n ...\n ValueError: 21 is not a sum of 2 squares\n sage: two_squares(21^2)\n (0, 21)\n sage: a, b = two_squares(100000000000000000129); a, b # needs sage.libs.pari\n (4418521500, 8970878873)\n sage: a^2 + b^2 # needs sage.libs.pari\n 100000000000000000129\n sage: two_squares(2^222 + 1) # needs sage.libs.pari\n (253801659504708621991421712450521, 2583712713213354898490304645018692)\n sage: two_squares(0)\n (0, 0)\n sage: two_squares(-1)\n Traceback (most recent call last):\n ...\n ValueError: -1 is not a sum of 2 squares\n\n TESTS::\n\n sage: for _ in range(100): # needs sage.libs.pari\n ....: a = ZZ.random_element(2**16, 2**20)\n ....: b = ZZ.random_element(2**16, 2**20)\n ....: n = a**2 + b**2\n ....: aa, bb = two_squares(n)\n ....: assert aa**2 + bb**2 == n\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int16 # needs numpy\n sage: two_squares(int16(389)) # needs numpy\n (10, 17)\n sage: from gmpy2 import mpz\n sage: two_squares(mpz(389))\n (10, 17)\n\n ALGORITHM:\n\n See https://schorn.ch/lagrange.html\n ' n = ZZ(n) if (n <= 0): if (n == 0): z = ZZ.zero() return (z, z) raise ValueError(('%s is not a sum of 2 squares' % n)) if (n.nbits() <= 32): from sage.rings import sum_of_squares return sum_of_squares.two_squares_pyx(n) F = n.factor(proof=False) for (p, e) in F: if ((e % 2) and ((p % 4) == 3)): raise ValueError(('%s is not a sum of 2 squares' % n)) from sage.rings.finite_rings.integer_mod import Mod a = ZZ.one() b = ZZ.zero() for (p, e) in F: if (e >= 2): m = (p ** (e // 2)) a *= m b *= m if (e % 2): if (p == 2): (a, b) = ((a - b), (a + b)) else: y = Mod(2, p) while True: s = (y ** ((p - 1) / 4)) if (not ((s * s) + 1)): s = s.lift() break y += 1 r = p while ((s * s) > p): (r, s) = (s, (r % s)) r %= s (a, b) = (((a * r) - (b * s)), ((b * r) + (a * s))) a = a.abs() b = b.abs() assert (((a * a) + (b * b)) == n) if (a <= b): return (a, b) else: return (b, a)
def three_squares(n): '\n Write the integer `n` as a sum of three integer squares if possible;\n otherwise raise a :class:`ValueError`.\n\n INPUT:\n\n - ``n`` -- an integer\n\n OUTPUT: a tuple `(a,b,c)` of non-negative integers such that\n `n = a^2 + b^2 + c^2` with `a <= b <= c`.\n\n EXAMPLES::\n\n sage: three_squares(389)\n (1, 8, 18)\n sage: three_squares(946)\n (9, 9, 28)\n sage: three_squares(2986)\n (3, 24, 49)\n sage: three_squares(7^100)\n (0, 0, 1798465042647412146620280340569649349251249)\n sage: three_squares(11^111 - 1) # needs sage.libs.pari\n (616274160655975340150706442680, 901582938385735143295060746161,\n 6270382387635744140394001363065311967964099981788593947233)\n sage: three_squares(7 * 2^41) # needs sage.libs.pari\n (1048576, 2097152, 3145728)\n sage: three_squares(7 * 2^42)\n Traceback (most recent call last):\n ...\n ValueError: 30786325577728 is not a sum of 3 squares\n sage: three_squares(0)\n (0, 0, 0)\n sage: three_squares(-1)\n Traceback (most recent call last):\n ...\n ValueError: -1 is not a sum of 3 squares\n\n TESTS::\n\n sage: for _ in range(100): # needs sage.libs.pari\n ....: a = ZZ.random_element(2**16, 2**20)\n ....: b = ZZ.random_element(2**16, 2**20)\n ....: c = ZZ.random_element(2**16, 2**20)\n ....: n = a**2 + b**2 + c**2\n ....: aa, bb, cc = three_squares(n)\n ....: assert aa**2 + bb**2 + cc**2 == n\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int16 # needs numpy\n sage: three_squares(int16(389)) # needs numpy\n (1, 8, 18)\n sage: from gmpy2 import mpz\n sage: three_squares(mpz(389))\n (1, 8, 18)\n\n ALGORITHM:\n\n See https://schorn.ch/lagrange.html\n ' n = ZZ(n) if (n <= 0): if (n == 0): z = ZZ.zero() return (z, z, z) raise ValueError(('%s is not a sum of 3 squares' % n)) if (n.nbits() <= 32): from sage.rings import sum_of_squares return sum_of_squares.three_squares_pyx(n) e = (n.valuation(2) // 2) m = (ZZ.one() << e) N = (n >> (2 * e)) (x, r) = N.sqrtrem() if (not r): z = ZZ.zero() return (z, z, (x * m)) if ((N % 4) == 1): if (x % 2): x -= 1 while (x >= 0): p = (N - (x * x)) if p.is_pseudoprime(): break x -= 2 elif ((N % 4) == 2): if ((x % 2) == 0): x -= 1 while (x >= 0): p = (N - (x * x)) if p.is_pseudoprime(): break x -= 2 elif ((N % 8) == 3): if ((x % 2) == 0): x -= 1 while (x >= 0): p = ((N - (x * x)) >> 1) if p.is_pseudoprime(): break x -= 2 else: raise ValueError(('%s is not a sum of 3 squares' % n)) if (x < 0): if (N > 10000): from warnings import warn warn(('Brute forcing sum of 3 squares for large N = %s' % N), RuntimeWarning) x = N.isqrt() while True: try: (a, b) = two_squares((N - (x * x))) break except ValueError: x -= 1 assert (x >= 0) if (x >= b): return ((a * m), (b * m), (x * m)) elif (x >= a): return ((a * m), (x * m), (b * m)) else: return ((x * m), (a * m), (b * m))
def four_squares(n): '\n Write the integer `n` as a sum of four integer squares.\n\n INPUT:\n\n - ``n`` -- an integer\n\n OUTPUT: a tuple `(a,b,c,d)` of non-negative integers such that\n `n = a^2 + b^2 + c^2 + d^2` with `a <= b <= c <= d`.\n\n EXAMPLES::\n\n sage: four_squares(3)\n (0, 1, 1, 1)\n sage: four_squares(13)\n (0, 0, 2, 3)\n sage: four_squares(130)\n (0, 0, 3, 11)\n sage: four_squares(1101011011004)\n (90, 102, 1220, 1049290)\n sage: four_squares(10^100 - 1) # needs sage.libs.pari\n (155024616290, 2612183768627, 14142135623730950488016887,\n 99999999999999999999999999999999999999999999999999)\n sage: for i in range(2^129, 2^129 + 10000): # long time # needs sage.libs.pari\n ....: S = four_squares(i)\n ....: assert sum(x^2 for x in S) == i\n\n TESTS::\n\n sage: for _ in range(100):\n ....: n = ZZ.random_element(2**32, 2**34)\n ....: aa, bb, cc, dd = four_squares(n)\n ....: assert aa**2 + bb**2 + cc**2 + dd**2 == n\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int16 # needs numpy\n sage: four_squares(int16(389)) # needs numpy\n (0, 1, 8, 18)\n sage: from gmpy2 import mpz\n sage: four_squares(mpz(389))\n (0, 1, 8, 18)\n ' n = ZZ(n) if (n <= 0): if (n == 0): z = ZZ.zero() return (z, z, z, z) raise ValueError(('%s is not a sum of 4 squares' % n)) if (n.nbits() <= 32): from sage.rings import sum_of_squares return sum_of_squares.four_squares_pyx(n) e = (n.valuation(2) // 2) m = (ZZ.one() << e) N = (n >> (2 * e)) x = N.isqrt() y = (N - (x * x)) if ((y >= 7) and (((y % 4) == 0) or ((y % 8) == 7))): x -= 1 y += ((2 * x) + 1) (a, b, c) = three_squares(y) return ((a * m), (b * m), (c * m), (x * m))
def sum_of_k_squares(k, n): '\n Write the integer `n` as a sum of `k` integer squares if possible;\n otherwise raise a :class:`ValueError`.\n\n INPUT:\n\n - ``k`` -- a non-negative integer\n\n - ``n`` -- an integer\n\n OUTPUT: a tuple `(x_1, ..., x_k)` of non-negative integers such that\n their squares sum to `n`.\n\n EXAMPLES::\n\n sage: sum_of_k_squares(2, 9634)\n (15, 97)\n sage: sum_of_k_squares(3, 9634)\n (0, 15, 97)\n sage: sum_of_k_squares(4, 9634)\n (1, 2, 5, 98)\n sage: sum_of_k_squares(5, 9634)\n (0, 1, 2, 5, 98)\n sage: sum_of_k_squares(6, 11^1111 - 1) # needs sage.libs.pari\n (19215400822645944253860920437586326284, 37204645194585992174252915693267578306,\n 3473654819477394665857484221256136567800161086815834297092488779216863122,\n 5860191799617673633547572610351797996721850737768032876360978911074629287841061578270832330322236796556721252602860754789786937515870682024273948,\n 20457423294558182494001919812379023992538802203730791019728543439765347851316366537094696896669915675685581905102118246887673397020172285247862426612188418787649371716686651256443143210952163970564228423098202682066311189439731080552623884051737264415984619097656479060977602722566383385989,\n 311628095411678159849237738619458396497534696043580912225334269371611836910345930320700816649653412141574887113710604828156159177769285115652741014638785285820578943010943846225597311231847997461959204894255074229895666356909071243390280307709880906261008237873840245959883405303580405277298513108957483306488193844321589356441983980532251051786704380984788999660195252373574924026139168936921591652831237741973242604363696352878914129671292072201700073286987126265965322808664802662993006926302359371379531571194266134916767573373504566621665949840469229781956838744551367172353)\n sage: sum_of_k_squares(7, 0)\n (0, 0, 0, 0, 0, 0, 0)\n sage: sum_of_k_squares(30,999999)\n (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7, 44, 999)\n sage: sum_of_k_squares(1, 9)\n (3,)\n sage: sum_of_k_squares(1, 10)\n Traceback (most recent call last):\n ...\n ValueError: 10 is not a sum of 1 square\n sage: sum_of_k_squares(1, -10)\n Traceback (most recent call last):\n ...\n ValueError: -10 is not a sum of 1 square\n sage: sum_of_k_squares(0, 9)\n Traceback (most recent call last):\n ...\n ValueError: 9 is not a sum of 0 squares\n sage: sum_of_k_squares(0, 0)\n ()\n sage: sum_of_k_squares(7, -1)\n Traceback (most recent call last):\n ...\n ValueError: -1 is not a sum of 7 squares\n sage: sum_of_k_squares(-1, 0)\n Traceback (most recent call last):\n ...\n ValueError: k = -1 must be non-negative\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int16 # needs numpy\n sage: sum_of_k_squares(int16(2), int16(9634)) # needs numpy\n (15, 97)\n sage: from gmpy2 import mpz\n sage: sum_of_k_squares(mpz(2), mpz(9634))\n (15, 97)\n ' n = ZZ(n) k = int(k) if (k <= 4): if (k == 4): return four_squares(n) if (k == 3): return three_squares(n) if (k == 2): return two_squares(n) if (k == 1): if (n >= 0): (x, r) = n.sqrtrem() if (not r): return (x,) raise ValueError(('%s is not a sum of 1 square' % n)) if (k == 0): if (n == 0): return tuple() raise ValueError(('%s is not a sum of 0 squares' % n)) raise ValueError(('k = %s must be non-negative' % k)) if (n < 0): raise ValueError(('%s is not a sum of %s squares' % (n, k))) t = [] while (k > 4): x = n.isqrt() t.insert(0, x) n -= (x * x) k -= 1 t = (list(four_squares(n)) + t) return tuple(t)
def subfactorial(n): '\n Subfactorial or rencontres numbers, or derangements: number of\n permutations of `n` elements with no fixed points.\n\n INPUT:\n\n\n - ``n`` - non negative integer\n\n\n OUTPUT:\n\n\n - ``integer`` - function value\n\n\n EXAMPLES::\n\n sage: subfactorial(0)\n 1\n sage: subfactorial(1)\n 0\n sage: subfactorial(8)\n 14833\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: subfactorial(int8(8)) # needs numpy\n 14833\n sage: from gmpy2 import mpz\n sage: subfactorial(mpz(8))\n 14833\n\n AUTHORS:\n\n - Jaap Spies (2007-01-23)\n ' return (factorial(n) * sum(((((- 1) ** k) / factorial(k)) for k in range((n + 1)))))
def is_power_of_two(n): '\n Return whether ``n`` is a power of 2.\n\n INPUT:\n\n - ``n`` -- integer\n\n OUTPUT:\n\n boolean\n\n EXAMPLES::\n\n sage: is_power_of_two(1024)\n True\n sage: is_power_of_two(1)\n True\n sage: is_power_of_two(24)\n False\n sage: is_power_of_two(0)\n False\n sage: is_power_of_two(-4)\n False\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: is_power_of_two(int8(16)) # needs numpy\n True\n sage: is_power_of_two(int8(24)) # needs numpy\n False\n sage: from gmpy2 import mpz\n sage: is_power_of_two(mpz(16))\n True\n sage: is_power_of_two(mpz(24))\n False\n ' return (ZZ(n).popcount() == 1)
def differences(lis, n=1): '\n Return the `n` successive differences of the elements in ``lis``.\n\n EXAMPLES::\n\n sage: differences(prime_range(50)) # needs sage.libs.pari\n [1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4]\n sage: differences([i^2 for i in range(1,11)])\n [3, 5, 7, 9, 11, 13, 15, 17, 19]\n sage: differences([i^3 + 3*i for i in range(1,21)])\n [10, 22, 40, 64, 94, 130, 172, 220, 274, 334, 400, 472, 550, 634, 724, 820, 922, 1030, 1144]\n sage: differences([i^3 - i^2 for i in range(1,21)], 2)\n [10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94, 100, 106, 112]\n sage: differences([p - i^2 for i, p in enumerate(prime_range(50))], 3) # needs sage.libs.pari\n [-1, 2, -4, 4, -4, 4, 0, -6, 8, -6, 0, 4]\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: differences([int8(1), int8(4), int8(6), int8(19)]) # needs numpy\n [3, 2, 13]\n sage: from gmpy2 import mpz\n sage: differences([mpz(1), mpz(4), mpz(6), mpz(19)])\n [mpz(3), mpz(2), mpz(13)]\n\n AUTHORS:\n\n - Timothy Clemans (2008-03-09)\n ' n = ZZ(n) if (n < 1): raise ValueError('n must be greater than 0') lis = [(lis[(i + 1)] - num) for (i, num) in enumerate(lis[:(- 1)])] if (n == 1): return lis return differences(lis, (n - 1))
def _key_complex_for_display(a): '\n Key function to sort complex numbers for display only.\n\n Real numbers (with a zero imaginary part) come before complex numbers,\n and are sorted. Complex numbers are sorted by their real part\n unless their real parts are quite close, in which case they are\n sorted by their imaginary part.\n\n EXAMPLES::\n\n sage: import sage.arith.misc\n sage: key_c = sage.arith.misc._key_complex_for_display\n\n sage: key_c(CC(5)) # needs sage.rings.real_mpfr\n (0, 5.00000000000000)\n sage: key_c(CC(5, 5)) # needs sage.rings.real_mpfr\n (1, 5.00000000, 5.00000000000000)\n\n sage: CIF200 = ComplexIntervalField(200) # needs sage.rings.complex_interval_field\n sage: key_c(CIF200(5)) # needs sage.rings.complex_interval_field\n (0, 5)\n sage: key_c(CIF200(5, 5)) # needs sage.rings.complex_interval_field\n (1, 5.00000000, 5)\n ' ar = a.real() ai = a.imag() if (not ai): return (0, ar) epsilon = ar.parent()(1e-10) if (ar.abs() < epsilon): ar_truncated = 0 elif (ar.prec() < 34): ar_truncated = ar else: ar_truncated = ar.n(digits=9) return (1, ar_truncated, ai)
def sort_complex_numbers_for_display(nums): '\n Given a list of complex numbers (or a list of tuples, where the\n first element of each tuple is a complex number), we sort the list\n in a "pretty" order.\n\n Real numbers (with a zero imaginary part) come before complex numbers,\n and are sorted. Complex numbers are sorted by their real part\n unless their real parts are quite close, in which case they are\n sorted by their imaginary part.\n\n This is not a useful function mathematically (not least because\n there is no principled way to determine whether the real components\n should be treated as equal or not). It is called by various\n polynomial root-finders; its purpose is to make doctest printing\n more reproducible.\n\n We deliberately choose a cumbersome name for this function to\n discourage use, since it is mathematically meaningless.\n\n EXAMPLES::\n\n sage: # needs sage.rings.complex_double\n sage: import sage.arith.misc\n sage: sort_c = sort_complex_numbers_for_display\n sage: nums = [CDF(i) for i in range(3)]\n sage: for i in range(3):\n ....: nums.append(CDF(i + RDF.random_element(-3e-11, 3e-11),\n ....: RDF.random_element()))\n ....: nums.append(CDF(i + RDF.random_element(-3e-11, 3e-11),\n ....: RDF.random_element()))\n sage: shuffle(nums)\n sage: nums = sort_c(nums)\n sage: for i in range(len(nums)):\n ....: if nums[i].imag():\n ....: first_non_real = i\n ....: break\n ....: else:\n ....: first_non_real = len(nums)\n sage: assert first_non_real >= 3\n sage: for i in range(first_non_real - 1):\n ....: assert nums[i].real() <= nums[i + 1].real()\n sage: def truncate(n):\n ....: if n.real() < 1e-10:\n ....: return 0\n ....: else:\n ....: return n.real().n(digits=9)\n sage: for i in range(first_non_real, len(nums)-1):\n ....: assert truncate(nums[i]) <= truncate(nums[i + 1])\n ....: if truncate(nums[i]) == truncate(nums[i + 1]):\n ....: assert nums[i].imag() <= nums[i+1].imag()\n ' if (not nums): return nums if isinstance(nums[0], tuple): return sorted(nums, key=(lambda t: _key_complex_for_display(t[0]))) else: return sorted(nums, key=_key_complex_for_display)
def fundamental_discriminant(D): '\n Return the discriminant of the quadratic extension\n `K=Q(\\sqrt{D})`, i.e. an integer d congruent to either 0 or\n 1, mod 4, and such that, at most, the only square dividing it is\n 4.\n\n INPUT:\n\n - ``D`` - an integer\n\n OUTPUT:\n\n - an integer, the fundamental discriminant\n\n EXAMPLES::\n\n sage: fundamental_discriminant(102)\n 408\n sage: fundamental_discriminant(720)\n 5\n sage: fundamental_discriminant(2)\n 8\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: fundamental_discriminant(int8(102)) # needs numpy\n 408\n sage: from gmpy2 import mpz\n sage: fundamental_discriminant(mpz(102))\n 408\n ' D = ZZ(D) D = D.squarefree_part() if ((D % 4) == 1): return D return (4 * D)
def squarefree_divisors(x): "\n Return an iterator over the squarefree divisors (up to units)\n of this ring element.\n\n Depends on the output of the prime_divisors function.\n\n Squarefree divisors of an integer are not necessarily\n yielded in increasing order.\n\n INPUT:\n\n - x -- an element of any ring for which the prime_divisors\n function works.\n\n EXAMPLES:\n\n Integers with few prime divisors::\n\n sage: list(squarefree_divisors(7))\n [1, 7]\n sage: list(squarefree_divisors(6))\n [1, 2, 3, 6]\n sage: list(squarefree_divisors(12))\n [1, 2, 3, 6]\n\n Squarefree divisors are not yielded in increasing order::\n\n sage: list(squarefree_divisors(30))\n [1, 2, 3, 6, 5, 10, 15, 30]\n\n TESTS:\n\n Check that the first divisor (i.e. `1`) is a Sage integer (see\n :trac:`17852`)::\n\n sage: a = next(squarefree_divisors(14))\n sage: a\n 1\n sage: type(a)\n <class 'sage.rings.integer.Integer'>\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: list(squarefree_divisors(int8(12))) # needs numpy\n [1, 2, 3, 6]\n sage: from gmpy2 import mpz\n sage: list(squarefree_divisors(mpz(12)))\n [1, 2, 3, 6]\n " from sage.combinat.subset import powerset for a in powerset(prime_divisors(x)): (yield prod(a, ZZ.one()))
def dedekind_sum(p, q, algorithm='default'): "\n Return the Dedekind sum `s(p,q)` defined for integers `p`, `q` as\n\n .. MATH::\n\n s(p,q) = \\sum_{i=0}^{q-1} \\left(\\!\\left(\\frac{i}{q}\\right)\\!\\right)\n \\left(\\!\\left(\\frac{pi}{q}\\right)\\!\\right)\n\n where\n\n .. MATH::\n\n ((x))=\\begin{cases}\n x-\\lfloor x \\rfloor - \\frac{1}{2} &\\mbox{if }\n x \\in \\QQ \\setminus \\ZZ \\\\\n 0 & \\mbox{if } x \\in \\ZZ.\n \\end{cases}\n\n .. WARNING::\n\n Caution is required as the Dedekind sum sometimes depends on the\n algorithm or is left undefined when `p` and `q` are not coprime.\n\n INPUT:\n\n - ``p``, ``q`` -- integers\n - ``algorithm`` -- must be one of the following\n\n - ``'default'`` - (default) use FLINT\n - ``'flint'`` - use FLINT\n - ``'pari'`` - use PARI (gives different results if `p` and `q`\n are not coprime)\n\n OUTPUT: a rational number\n\n EXAMPLES:\n\n Several small values::\n\n sage: for q in range(10): print([dedekind_sum(p,q) for p in range(q+1)]) # needs sage.libs.flint\n [0]\n [0, 0]\n [0, 0, 0]\n [0, 1/18, -1/18, 0]\n [0, 1/8, 0, -1/8, 0]\n [0, 1/5, 0, 0, -1/5, 0]\n [0, 5/18, 1/18, 0, -1/18, -5/18, 0]\n [0, 5/14, 1/14, -1/14, 1/14, -1/14, -5/14, 0]\n [0, 7/16, 1/8, 1/16, 0, -1/16, -1/8, -7/16, 0]\n [0, 14/27, 4/27, 1/18, -4/27, 4/27, -1/18, -4/27, -14/27, 0]\n\n Check relations for restricted arguments::\n\n sage: q = 23; dedekind_sum(1, q); (q-1)*(q-2)/(12*q) # needs sage.libs.flint\n 77/46\n 77/46\n sage: p, q = 100, 723 # must be coprime\n sage: dedekind_sum(p, q) + dedekind_sum(q, p) # needs sage.libs.flint\n 31583/86760\n sage: -1/4 + (p/q + q/p + 1/(p*q))/12\n 31583/86760\n\n We check that evaluation works with large input::\n\n sage: dedekind_sum(3^54 - 1, 2^93 + 1) # needs sage.libs.flint\n 459340694971839990630374299870/29710560942849126597578981379\n sage: dedekind_sum(3^54 - 1, 2^93 + 1, algorithm='pari') # needs sage.libs.pari\n 459340694971839990630374299870/29710560942849126597578981379\n\n We check consistency of the results::\n\n sage: dedekind_sum(5, 7, algorithm='default') # needs sage.libs.flint\n -1/14\n sage: dedekind_sum(5, 7, algorithm='flint') # needs sage.libs.flint\n -1/14\n sage: dedekind_sum(5, 7, algorithm='pari') # needs sage.libs.pari\n -1/14\n sage: dedekind_sum(6, 8, algorithm='default') # needs sage.libs.flint\n -1/8\n sage: dedekind_sum(6, 8, algorithm='flint') # needs sage.libs.flint\n -1/8\n sage: dedekind_sum(6, 8, algorithm='pari') # needs sage.libs.pari\n -1/8\n\n Tests with numpy and gmpy2 numbers::\n\n sage: from numpy import int8 # needs numpy\n sage: dedekind_sum(int8(5), int8(7), algorithm='default') # needs numpy sage.libs.flint\n -1/14\n sage: from gmpy2 import mpz\n sage: dedekind_sum(mpz(5), mpz(7), algorithm='default') # needs sage.libs.flint\n -1/14\n\n REFERENCES:\n\n - [Ap1997]_\n\n - :wikipedia:`Dedekind\\_sum`\n " if ((algorithm == 'default') or (algorithm == 'flint')): from sage.libs.flint.arith import dedekind_sum as flint_dedekind_sum return flint_dedekind_sum(p, q) if (algorithm == 'pari'): import sage.interfaces.gp x = sage.interfaces.gp.gp(('sumdedekind(%s,%s)' % (p, q))) return Rational(x) raise ValueError('unknown algorithm')
def gauss_sum(char_value, finite_field): '\n Return the Gauss sums for a general finite field.\n\n INPUT:\n\n - ``char_value`` -- choice of multiplicative character, given by\n its value on the ``finite_field.multiplicative_generator()``\n\n - ``finite_field`` -- a finite field\n\n OUTPUT:\n\n an element of the parent ring of ``char_value``, that can be any\n field containing enough roots of unity, for example the\n ``UniversalCyclotomicField``, ``QQbar`` or ``ComplexField``\n\n For a finite field `F` of characteristic `p`, the Gauss sum\n associated to a multiplicative character `\\chi` (with values in a\n ring `K`) is defined as\n\n .. MATH::\n\n \\sum_{x \\in F^{\\times}} \\chi(x) \\zeta_p^{\\operatorname{Tr} x},\n\n where `\\zeta_p \\in K` is a primitive root of unity of order `p` and\n Tr is the trace map from `F` to its prime field `\\GF{p}`.\n\n For more info on Gauss sums, see :wikipedia:`Gauss_sum`.\n\n .. TODO::\n\n Implement general Gauss sums for an arbitrary pair\n ``(multiplicative_character, additive_character)``\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari sage.rings.number_field\n sage: from sage.arith.misc import gauss_sum\n sage: F = GF(5); q = 5\n sage: zq = UniversalCyclotomicField().zeta(q - 1)\n sage: L = [gauss_sum(zq**i, F) for i in range(5)]; L\n [-1,\n E(20)^4 + E(20)^13 - E(20)^16 - E(20)^17,\n E(5) - E(5)^2 - E(5)^3 + E(5)^4,\n E(20)^4 - E(20)^13 - E(20)^16 + E(20)^17,\n -1]\n sage: [g*g.conjugate() for g in L]\n [1, 5, 5, 5, 1]\n\n sage: # needs sage.libs.pari sage.rings.number_field\n sage: F = GF(11**2); q = 11**2\n sage: zq = UniversalCyclotomicField().zeta(q - 1)\n sage: g = gauss_sum(zq**4, F)\n sage: g*g.conjugate()\n 121\n\n TESTS::\n\n sage: # needs sage.libs.pari sage.rings.number_field\n sage: F = GF(11); q = 11\n sage: zq = UniversalCyclotomicField().zeta(q - 1)\n sage: gauss_sum(zq**2, F).n(60)\n 2.6361055643248352 + 2.0126965627574471*I\n\n sage: zq = QQbar.zeta(q - 1) # needs sage.libs.pari sage.rings.number_field\n sage: gauss_sum(zq**2, F) # needs sage.libs.pari sage.rings.number_field\n 2.636105564324836? + 2.012696562757447?*I\n\n sage: zq = ComplexField(60).zeta(q - 1) # needs sage.libs.pari sage.rings.number_field\n sage: gauss_sum(zq**2, F) # needs sage.libs.pari sage.rings.number_field\n 2.6361055643248352 + 2.0126965627574471*I\n\n sage: # needs sage.libs.pari sage.rings.number_field\n sage: F = GF(7); q = 7\n sage: zq = QQbar.zeta(q - 1)\n sage: D = DirichletGroup(7, QQbar)\n sage: all(D[i].gauss_sum() == gauss_sum(zq**i, F) for i in range(6))\n True\n\n sage: gauss_sum(1, QQ) # needs sage.libs.pari sage.rings.number_field\n Traceback (most recent call last):\n ...\n ValueError: second input must be a finite field\n\n .. SEEALSO::\n\n - :func:`sage.rings.padics.misc.gauss_sum` for a `p`-adic version\n - :meth:`sage.modular.dirichlet.DirichletCharacter.gauss_sum`\n for prime finite fields\n - :meth:`sage.modular.dirichlet.DirichletCharacter.gauss_sum_numerical`\n for prime finite fields\n ' from sage.categories.fields import Fields if (finite_field not in Fields().Finite()): raise ValueError('second input must be a finite field') ring = char_value.parent() q = finite_field.cardinality() p = finite_field.characteristic() gen = finite_field.multiplicative_generator() zeta_p_powers = ring.zeta(p).powers(p) zeta_q = char_value resu = ring.zero() gen_power = finite_field.one() zq_power = ring.one() for k in range((q - 1)): resu += (zq_power * zeta_p_powers[gen_power.trace().lift()]) gen_power *= gen zq_power *= zeta_q return resu
def dedekind_psi(N): '\n Return the value of the Dedekind psi function at ``N``.\n\n INPUT:\n\n - ``N`` -- a positive integer\n\n OUTPUT:\n\n an integer\n\n The Dedekind psi function is the multiplicative function defined by\n\n .. MATH::\n\n \\psi(n) = n \\prod_{p|n, p prime} (1 + 1/p).\n\n See :wikipedia:`Dedekind_psi_function` and :oeis:`A001615`.\n\n EXAMPLES::\n\n sage: from sage.arith.misc import dedekind_psi\n sage: [dedekind_psi(d) for d in range(1, 12)]\n [1, 3, 4, 6, 6, 12, 8, 12, 12, 18, 12]\n ' N = Integer(N) return Integer((N * prod(((1 + (1 / p)) for p in N.prime_divisors()))))
def symbolic_expression(x): "\n Create a symbolic expression or vector of symbolic expressions from x.\n\n INPUT:\n\n - ``x`` - an object\n\n OUTPUT:\n\n - a symbolic expression.\n\n EXAMPLES::\n\n sage: a = symbolic_expression(3/2); a\n 3/2\n sage: type(a)\n <class 'sage.symbolic.expression.Expression'>\n sage: R.<x> = QQ[]; type(x)\n <class 'sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint'>\n sage: a = symbolic_expression(2*x^2 + 3); a\n 2*x^2 + 3\n sage: type(a)\n <class 'sage.symbolic.expression.Expression'>\n sage: from sage.structure.element import Expression\n sage: isinstance(a, Expression)\n True\n sage: a in SR\n True\n sage: a.parent()\n Symbolic Ring\n\n Note that equations exist in the symbolic ring::\n\n sage: E = EllipticCurve('15a'); E\n Elliptic Curve defined by y^2 + x*y + y = x^3 + x^2 - 10*x - 10 over Rational Field\n sage: symbolic_expression(E)\n x*y + y^2 + y == x^3 + x^2 - 10*x - 10\n sage: symbolic_expression(E) in SR\n True\n\n If ``x`` is a list or tuple, create a vector of symbolic expressions::\n\n sage: v = symbolic_expression([x,1]); v\n (x, 1)\n sage: v.base_ring()\n Symbolic Ring\n sage: v = symbolic_expression((x,1)); v\n (x, 1)\n sage: v.base_ring()\n Symbolic Ring\n sage: v = symbolic_expression((3,1)); v\n (3, 1)\n sage: v.base_ring()\n Symbolic Ring\n sage: E = EllipticCurve('15a'); E\n Elliptic Curve defined by y^2 + x*y + y = x^3 + x^2 - 10*x - 10 over Rational Field\n sage: v = symbolic_expression([E,E]); v\n (x*y + y^2 + y == x^3 + x^2 - 10*x - 10, x*y + y^2 + y == x^3 + x^2 - 10*x - 10)\n sage: v.base_ring()\n Symbolic Ring\n\n Likewise, if ``x`` is a vector, create a vector of symbolic expressions::\n\n sage: u = vector([1, 2, 3])\n sage: v = symbolic_expression(u); v\n (1, 2, 3)\n sage: v.parent()\n Vector space of dimension 3 over Symbolic Ring\n\n If ``x`` is a list or tuple of lists/tuples/vectors, create a matrix of symbolic expressions::\n\n sage: M = symbolic_expression([[1, x, x^2], (x, x^2, x^3), vector([x^2, x^3, x^4])]); M\n [ 1 x x^2]\n [ x x^2 x^3]\n [x^2 x^3 x^4]\n sage: M.parent()\n Full MatrixSpace of 3 by 3 dense matrices over Symbolic Ring\n\n If ``x`` is a matrix, create a matrix of symbolic expressions::\n\n sage: A = matrix([[1, 2, 3], [4, 5, 6]])\n sage: B = symbolic_expression(A); B\n [1 2 3]\n [4 5 6]\n sage: B.parent()\n Full MatrixSpace of 2 by 3 dense matrices over Symbolic Ring\n\n If ``x`` is a function, for example defined by a ``lambda`` expression, create a\n symbolic function::\n\n sage: f = symbolic_expression(lambda z: z^2 + 1); f\n z |--> z^2 + 1\n sage: f.parent()\n Callable function ring with argument z\n sage: f(7)\n 50\n\n If ``x`` is a list or tuple of functions, or if ``x`` is a function that returns a list\n or tuple, create a callable symbolic vector::\n\n sage: symbolic_expression([lambda mu, nu: mu^2 + nu^2, lambda mu, nu: mu^2 - nu^2])\n (mu, nu) |--> (mu^2 + nu^2, mu^2 - nu^2)\n sage: f = symbolic_expression(lambda uwu: [1, uwu, uwu^2]); f\n uwu |--> (1, uwu, uwu^2)\n sage: f.parent()\n Vector space of dimension 3 over Callable function ring with argument uwu\n sage: f(5)\n (1, 5, 25)\n sage: f(5).parent()\n Vector space of dimension 3 over Symbolic Ring\n\n TESTS:\n\n Lists, tuples, and vectors of length 0 become vectors over a symbolic ring::\n\n sage: symbolic_expression([]).parent()\n Vector space of dimension 0 over Symbolic Ring\n sage: symbolic_expression(()).parent()\n Vector space of dimension 0 over Symbolic Ring\n sage: symbolic_expression(vector(QQ, 0)).parent()\n Vector space of dimension 0 over Symbolic Ring\n\n If a matrix has dimension 0, the result is still a matrix over a symbolic ring::\n\n sage: symbolic_expression(matrix(QQ, 2, 0)).parent()\n Full MatrixSpace of 2 by 0 dense matrices over Symbolic Ring\n sage: symbolic_expression(matrix(QQ, 0, 3)).parent()\n Full MatrixSpace of 0 by 3 dense matrices over Symbolic Ring\n\n Also functions defined using ``def`` can be used, but we do not advertise it as a use case::\n\n sage: def sos(x, y):\n ....: return x^2 + y^2\n sage: symbolic_expression(sos)\n (x, y) |--> x^2 + y^2\n\n Functions that take a varying number of arguments or keyword-only arguments are not accepted::\n\n sage: def variadic(x, *y):\n ....: return x\n sage: symbolic_expression(variadic)\n Traceback (most recent call last):\n ...\n TypeError: unable to convert <function variadic at 0x...> to a symbolic expression\n\n sage: def function_with_keyword_only_arg(x, *, sign=1):\n ....: return sign * x\n sage: symbolic_expression(function_with_keyword_only_arg)\n Traceback (most recent call last):\n ...\n TypeError: unable to convert <function function_with_keyword_only_arg at 0x...>\n to a symbolic expression\n " from sage.symbolic.expression import Expression from sage.symbolic.ring import SR from sage.modules.free_module_element import is_FreeModuleElement from sage.structure.element import is_Matrix if isinstance(x, Expression): return x elif hasattr(x, '_symbolic_'): return x._symbolic_(SR) elif (isinstance(x, (tuple, list)) or is_FreeModuleElement(x)): expressions = [symbolic_expression(item) for item in x] if (not expressions): return vector(SR, 0) if is_FreeModuleElement(expressions[0]): return matrix(expressions) return vector(expressions) elif is_Matrix(x): if ((not x.nrows()) or (not x.ncols())): return matrix(SR, x.nrows(), x.ncols()) rows = [symbolic_expression(row) for row in x.rows()] return matrix(rows) elif callable(x): from inspect import signature, Parameter try: s = signature(x) except ValueError: pass else: if all(((param.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD)) for param in s.parameters.values())): vars = [SR.var(name) for name in s.parameters.keys()] result = x(*vars) if isinstance(result, (tuple, list)): return vector(SR, result).function(*vars) else: return SR(result).function(*vars) return SR(x)
def symbolic_sum(expression, v, a, b, algorithm='maxima', hold=False): "\n Return the symbolic sum `\\sum_{v = a}^b expression` with respect\n to the variable `v` with endpoints `a` and `b`.\n\n INPUT:\n\n - ``expression`` -- a symbolic expression\n\n - ``v`` -- a variable or variable name\n\n - ``a`` -- lower endpoint of the sum\n\n - ``b`` -- upper endpoint of the sum\n\n - ``algorithm`` -- (default: ``'maxima'``) one of\n\n - ``'maxima'`` -- use Maxima (the default)\n\n - ``'maple'`` -- (optional) use Maple\n\n - ``'mathematica'`` -- (optional) use Mathematica\n\n - ``'giac'`` -- (optional) use Giac\n\n - ``'sympy'`` -- use SymPy\n\n - ``hold`` -- (default: ``False``) if ``True``, don't evaluate\n\n EXAMPLES::\n\n sage: k, n = var('k,n')\n sage: from sage.calculus.calculus import symbolic_sum\n sage: symbolic_sum(k, k, 1, n).factor()\n 1/2*(n + 1)*n\n\n ::\n\n sage: symbolic_sum(1/k^4, k, 1, oo)\n 1/90*pi^4\n\n ::\n\n sage: symbolic_sum(1/k^5, k, 1, oo)\n zeta(5)\n\n A well known binomial identity::\n\n sage: symbolic_sum(binomial(n,k), k, 0, n)\n 2^n\n\n And some truncations thereof::\n\n sage: assume(n>1)\n sage: symbolic_sum(binomial(n,k), k, 1, n)\n 2^n - 1\n sage: symbolic_sum(binomial(n,k), k, 2, n)\n 2^n - n - 1\n sage: symbolic_sum(binomial(n,k), k, 0, n-1)\n 2^n - 1\n sage: symbolic_sum(binomial(n,k), k, 1, n-1)\n 2^n - 2\n\n The binomial theorem::\n\n sage: x, y = var('x, y')\n sage: symbolic_sum(binomial(n,k) * x^k * y^(n-k), k, 0, n)\n (x + y)^n\n\n ::\n\n sage: symbolic_sum(k * binomial(n, k), k, 1, n)\n 2^(n - 1)*n\n\n ::\n\n sage: symbolic_sum((-1)^k*binomial(n,k), k, 0, n)\n 0\n\n ::\n\n sage: symbolic_sum(2^(-k)/(k*(k+1)), k, 1, oo)\n -log(2) + 1\n\n Summing a hypergeometric term::\n\n sage: symbolic_sum(binomial(n, k) * factorial(k) / factorial(n+1+k), k, 0, n)\n 1/2*sqrt(pi)/factorial(n + 1/2)\n\n We check a well known identity::\n\n sage: bool(symbolic_sum(k^3, k, 1, n) == symbolic_sum(k, k, 1, n)^2)\n True\n\n A geometric sum::\n\n sage: a, q = var('a, q')\n sage: symbolic_sum(a*q^k, k, 0, n)\n (a*q^(n + 1) - a)/(q - 1)\n\n For the geometric series, we will have to assume\n the right values for the sum to converge::\n\n sage: assume(abs(q) < 1)\n sage: symbolic_sum(a*q^k, k, 0, oo)\n -a/(q - 1)\n\n A divergent geometric series. Don't forget\n to forget your assumptions::\n\n sage: forget()\n sage: assume(q > 1)\n sage: symbolic_sum(a*q^k, k, 0, oo)\n Traceback (most recent call last):\n ...\n ValueError: Sum is divergent.\n sage: forget()\n sage: assumptions() # check the assumptions were really forgotten\n []\n\n A summation performed by Mathematica::\n\n sage: symbolic_sum(1/(1+k^2), k, -oo, oo, algorithm='mathematica') # optional - mathematica\n pi*coth(pi)\n\n An example of this summation with Giac::\n\n sage: symbolic_sum(1/(1+k^2), k, -oo, oo, algorithm='giac').factor()\n pi*(e^(2*pi) + 1)/((e^pi + 1)*(e^pi - 1))\n\n The same summation is solved by SymPy::\n\n sage: symbolic_sum(1/(1+k^2), k, -oo, oo, algorithm='sympy')\n pi/tanh(pi)\n\n SymPy and Maxima 5.39.0 can do the following (see\n :trac:`22005`)::\n\n sage: sum(1/((2*n+1)^2-4)^2, n, 0, Infinity, algorithm='sympy')\n 1/64*pi^2\n sage: sum(1/((2*n+1)^2-4)^2, n, 0, Infinity)\n 1/64*pi^2\n\n Use Maple as a backend for summation::\n\n sage: symbolic_sum(binomial(n,k)*x^k, k, 0, n, algorithm='maple') # optional - maple\n (x + 1)^n\n\n If you don't want to evaluate immediately give the ``hold`` keyword::\n\n sage: s = sum(n, n, 1, k, hold=True); s\n sum(n, n, 1, k)\n sage: s.unhold()\n 1/2*k^2 + 1/2*k\n sage: s.subs(k == 10)\n sum(n, n, 1, 10)\n sage: s.subs(k == 10).unhold()\n 55\n sage: s.subs(k == 10).n()\n 55.0000000000000\n\n TESTS:\n\n :trac:`10564` is fixed::\n\n sage: sum (n^3 * x^n, n, 0, infinity)\n (x^3 + 4*x^2 + x)/(x^4 - 4*x^3 + 6*x^2 - 4*x + 1)\n\n .. note::\n\n Sage can currently only understand a subset of the output of Maxima,\n Maple and Mathematica, so even if the chosen backend can perform\n the summation the result might not be convertible into a Sage\n expression.\n " if (not (isinstance(v, Expression) and v.is_symbol())): if isinstance(v, str): v = var(v) else: raise TypeError('need a summation variable') if ((v in SR(a).variables()) or (v in SR(b).variables())): raise ValueError('summation limits must not depend on the summation variable') if hold: from sage.functions.other import symbolic_sum as ssum return ssum(expression, v, a, b) if (algorithm == 'maxima'): return maxima.sr_sum(expression, v, a, b) elif (algorithm == 'mathematica'): try: sum = ('Sum[%s, {%s, %s, %s}]' % tuple([repr(expr._mathematica_()) for expr in (expression, v, a, b)])) except TypeError: raise ValueError('Mathematica cannot make sense of input') from sage.interfaces.mathematica import mathematica try: result = mathematica(sum) except TypeError: raise ValueError(('Mathematica cannot make sense of: %s' % sum)) return result.sage() elif (algorithm == 'maple'): sum = ('sum(%s, %s=%s..%s)' % tuple([repr(expr._maple_()) for expr in (expression, v, a, b)])) from sage.interfaces.maple import maple try: result = maple(sum).simplify() except TypeError: raise ValueError(('Maple cannot make sense of: %s' % sum)) return result.sage() elif (algorithm == 'giac'): sum = ('sum(%s, %s, %s, %s)' % tuple([repr(expr._giac_()) for expr in (expression, v, a, b)])) from sage.interfaces.giac import giac try: result = giac(sum) except TypeError: raise ValueError(('Giac cannot make sense of: %s' % sum)) return result.sage() elif (algorithm == 'sympy'): (expression, v, a, b) = (expr._sympy_() for expr in (expression, v, a, b)) from sympy import summation from sage.interfaces.sympy import sympy_init sympy_init() result = summation(expression, (v, a, b)) try: return result._sage_() except AttributeError: raise AttributeError('Unable to convert SymPy result (={}) into Sage'.format(result)) else: raise ValueError(('unknown algorithm: %s' % algorithm))
def nintegral(ex, x, a, b, desired_relative_error='1e-8', maximum_num_subintervals=200): "\n Return a floating point machine precision numerical approximation\n to the integral of ``self`` from `a` to\n `b`, computed using floating point arithmetic via maxima.\n\n INPUT:\n\n - ``x`` -- variable to integrate with respect to\n\n - ``a`` -- lower endpoint of integration\n\n - ``b`` -- upper endpoint of integration\n\n - ``desired_relative_error`` -- (default: ``1e-8``) the\n desired relative error\n\n - ``maximum_num_subintervals`` -- (default: 200)\n maximal number of subintervals\n\n OUTPUT:\n\n - float: approximation to the integral\n\n - float: estimated absolute error of the\n approximation\n\n - the number of integrand evaluations\n\n - an error code:\n\n - ``0`` -- no problems were encountered\n\n - ``1`` -- too many subintervals were done\n\n - ``2`` -- excessive roundoff error\n\n - ``3`` -- extremely bad integrand behavior\n\n - ``4`` -- failed to converge\n\n - ``5`` -- integral is probably divergent or slowly\n convergent\n\n - ``6`` -- the input is invalid; this includes the case of\n ``desired_relative_error`` being too small to be achieved\n\n ALIAS: :func:`nintegrate` is the same as :func:`nintegral`\n\n REMARK: There is also a function\n :func:`numerical_integral` that implements numerical\n integration using the GSL C library. It is potentially much faster\n and applies to arbitrary user defined functions.\n\n Also, there are limits to the precision to which Maxima can compute\n the integral due to limitations in quadpack.\n In the following example, remark that the last value of the returned\n tuple is ``6``, indicating that the input was invalid, in this case\n because of a too high desired precision.\n\n ::\n\n sage: f = x\n sage: f.nintegral(x, 0, 1, 1e-14)\n (0.0, 0.0, 0, 6)\n\n EXAMPLES::\n\n sage: f(x) = exp(-sqrt(x))\n sage: f.nintegral(x, 0, 1)\n (0.5284822353142306, 4.163...e-11, 231, 0)\n\n We can also use the :func:`numerical_integral` function,\n which calls the GSL C library.\n\n ::\n\n sage: numerical_integral(f, 0, 1)\n (0.528482232253147, 6.83928460...e-07)\n\n Note that in exotic cases where floating point evaluation of the\n expression leads to the wrong value, then the output can be\n completely wrong::\n\n sage: f = exp(pi*sqrt(163)) - 262537412640768744\n\n Despite appearance, `f` is really very close to 0, but one\n gets a nonzero value since the definition of\n ``float(f)`` is that it makes all constants inside the\n expression floats, then evaluates each function and each arithmetic\n operation using float arithmetic::\n\n sage: float(f)\n -480.0\n\n Computing to higher precision we see the truth::\n\n sage: f.n(200)\n -7.4992740280181431112064614366622348652078895136533593355718e-13\n sage: f.n(300)\n -7.49927402801814311120646143662663009137292462589621789352095066181709095575681963967103004e-13\n\n Now numerically integrating, we see why the answer is wrong::\n\n sage: f.nintegrate(x,0,1)\n (-480.000000000000..., 5.32907051820075...e-12, 21, 0)\n\n It is just because every floating point evaluation of `f` returns `-480.0`\n in floating point.\n\n Important note: using PARI/GP one can compute numerical integrals\n to high precision::\n\n sage: gp.eval('intnum(x=17,42,exp(-x^2)*log(x))')\n '2.565728500561051474934096410 E-127' # 32-bit\n '2.5657285005610514829176211363206621657 E-127' # 64-bit\n sage: old_prec = gp.set_real_precision(50)\n sage: gp.eval('intnum(x=17,42,exp(-x^2)*log(x))')\n '2.5657285005610514829173563961304957417746108003917 E-127'\n sage: gp.set_real_precision(old_prec)\n 57\n\n Note that the input function above is a string in PARI syntax.\n " try: v = ex._maxima_().quad_qags(x, a, b, epsrel=desired_relative_error, limit=maximum_num_subintervals) except TypeError as err: if ('ERROR' in str(err)): raise ValueError('Maxima (via quadpack) cannot compute the integral') else: raise TypeError(err) if ('quad_qags' in str(v)): raise ValueError('Maxima (via quadpack) cannot compute the integral') return (float(v[0]), float(v[1]), Integer(v[2]), Integer(v[3]))
def symbolic_product(expression, v, a, b, algorithm='maxima', hold=False): "\n Return the symbolic product `\\prod_{v = a}^b expression` with respect\n to the variable `v` with endpoints `a` and `b`.\n\n INPUT:\n\n - ``expression`` -- a symbolic expression\n\n - ``v`` -- a variable or variable name\n\n - ``a`` -- lower endpoint of the product\n\n - ``b`` -- upper endpoint of the prduct\n\n - ``algorithm`` -- (default: ``'maxima'``) one of\n\n - ``'maxima'`` -- use Maxima (the default)\n\n - ``'giac'`` -- use Giac\n\n - ``'sympy'`` -- use SymPy\n\n - ``'mathematica'`` -- (optional) use Mathematica\n\n - ``hold`` - (default: ``False``) if ``True``, don't evaluate\n\n EXAMPLES::\n\n sage: i, k, n = var('i,k,n')\n sage: from sage.calculus.calculus import symbolic_product\n sage: symbolic_product(k, k, 1, n)\n factorial(n)\n sage: symbolic_product(x + i*(i+1)/2, i, 1, 4)\n x^4 + 20*x^3 + 127*x^2 + 288*x + 180\n sage: symbolic_product(i^2, i, 1, 7)\n 25401600\n sage: f = function('f')\n sage: symbolic_product(f(i), i, 1, 7)\n f(7)*f(6)*f(5)*f(4)*f(3)*f(2)*f(1)\n sage: symbolic_product(f(i), i, 1, n)\n product(f(i), i, 1, n)\n sage: assume(k>0)\n sage: symbolic_product(integrate (x^k, x, 0, 1), k, 1, n)\n 1/factorial(n + 1)\n sage: symbolic_product(f(i), i, 1, n).log().log_expand()\n sum(log(f(i)), i, 1, n)\n\n TESTS:\n\n Verify that :trac:`30520` is fixed::\n\n sage: symbolic_product(-x^2,x,1,n)\n (-1)^n*factorial(n)^2\n\n " if (not (isinstance(v, Expression) and v.is_symbol())): if isinstance(v, str): v = var(v) else: raise TypeError('need a multiplication variable') if ((v in SR(a).variables()) or (v in SR(b).variables())): raise ValueError('product limits must not depend on the multiplication variable') if hold: from sage.functions.other import symbolic_product as sprod return sprod(expression, v, a, b) if (algorithm == 'maxima'): return maxima.sr_prod(expression, v, a, b) elif (algorithm == 'mathematica'): try: prod = ('Product[%s, {%s, %s, %s}]' % tuple([repr(expr._mathematica_()) for expr in (expression, v, a, b)])) except TypeError: raise ValueError('Mathematica cannot make sense of input') from sage.interfaces.mathematica import mathematica try: result = mathematica(prod) except TypeError: raise ValueError(('Mathematica cannot make sense of: %s' % sum)) return result.sage() elif (algorithm == 'giac'): prod = ('product(%s, %s, %s, %s)' % tuple([repr(expr._giac_()) for expr in (expression, v, a, b)])) from sage.interfaces.giac import giac try: result = giac(prod) except TypeError: raise ValueError(('Giac cannot make sense of: %s' % sum)) return result.sage() elif (algorithm == 'sympy'): (expression, v, a, b) = (expr._sympy_() for expr in (expression, v, a, b)) from sympy import product as sproduct from sage.interfaces.sympy import sympy_init sympy_init() result = sproduct(expression, (v, a, b)) try: return result._sage_() except AttributeError: raise AttributeError('Unable to convert SymPy result (={}) into Sage'.format(result)) else: raise ValueError(('unknown algorithm: %s' % algorithm))
def minpoly(ex, var='x', algorithm=None, bits=None, degree=None, epsilon=0): "\n Return the minimal polynomial of ``self``, if possible.\n\n INPUT:\n\n - ``var`` -- polynomial variable name (default 'x')\n\n - ``algorithm`` -- ``'algebraic'`` or ``'numerical'`` (default\n both, but with numerical first)\n\n - ``bits`` -- the number of bits to use in numerical\n approx\n\n - ``degree`` -- the expected algebraic degree\n\n - ``epsilon`` -- return without error as long as\n f(self) epsilon, in the case that the result cannot be proven.\n\n All of the above parameters are optional, with epsilon=0, ``bits`` and\n ``degree`` tested up to 1000 and 24 by default respectively. The\n numerical algorithm will be faster if bits and/or degree are given\n explicitly. The algebraic algorithm ignores the last three\n parameters.\n\n\n OUTPUT: The minimal polynomial of ``self``. If the numerical algorithm\n is used, then it is proved symbolically when ``epsilon=0`` (default).\n\n If the minimal polynomial could not be found, two distinct kinds of\n errors are raised. If no reasonable candidate was found with the\n given ``bits``/``degree`` parameters, a :class:`ValueError` will be\n raised. If a reasonable candidate was found but (perhaps due to\n limits in the underlying symbolic package) was unable to be proved\n correct, a :class:`NotImplementedError` will be raised.\n\n ALGORITHM: Two distinct algorithms are used, depending on the\n algorithm parameter. By default, the numerical algorithm is\n attempted first, then the algebraic one.\n\n Algebraic: Attempt to evaluate this expression in ``QQbar``, using\n cyclotomic fields to resolve exponential and trig functions at\n rational multiples of `\\pi`, field extensions to handle roots and\n rational exponents, and computing compositums to represent the full\n expression as an element of a number field where the minimal\n polynomial can be computed exactly. The ``bits``, ``degree``, and ``epsilon``\n parameters are ignored.\n\n Numerical: Computes a numerical approximation of\n ``self`` and use PARI's :pari:`algdep` to get a candidate\n minpoly `f`. If `f(\\mathtt{self})`,\n evaluated to a higher precision, is close enough to 0 then evaluate\n `f(\\mathtt{self})` symbolically, attempting to prove\n vanishing. If this fails, and ``epsilon`` is non-zero,\n return `f` if and only if\n `f(\\mathtt{self}) < \\mathtt{epsilon}`.\n Otherwise raise a :class:`ValueError` (if no suitable\n candidate was found) or a :class:`NotImplementedError` (if a\n likely candidate was found but could not be proved correct).\n\n EXAMPLES: First some simple examples::\n\n sage: sqrt(2).minpoly()\n x^2 - 2\n sage: minpoly(2^(1/3))\n x^3 - 2\n sage: minpoly(sqrt(2) + sqrt(-1))\n x^4 - 2*x^2 + 9\n sage: minpoly(sqrt(2)-3^(1/3))\n x^6 - 6*x^4 + 6*x^3 + 12*x^2 + 36*x + 1\n\n\n Works with trig and exponential functions too.\n\n ::\n\n sage: sin(pi/3).minpoly()\n x^2 - 3/4\n sage: sin(pi/7).minpoly()\n x^6 - 7/4*x^4 + 7/8*x^2 - 7/64\n sage: minpoly(exp(I*pi/17))\n x^16 - x^15 + x^14 - x^13 + x^12 - x^11 + x^10 - x^9 + x^8\n - x^7 + x^6 - x^5 + x^4 - x^3 + x^2 - x + 1\n\n Here we verify it gives the same result as the abstract number\n field.\n\n ::\n\n sage: (sqrt(2) + sqrt(3) + sqrt(6)).minpoly()\n x^4 - 22*x^2 - 48*x - 23\n sage: K.<a,b> = NumberField([x^2-2, x^2-3])\n sage: (a+b+a*b).absolute_minpoly()\n x^4 - 22*x^2 - 48*x - 23\n\n The :func:`minpoly` function is used implicitly when creating\n number fields::\n\n sage: x = var('x')\n sage: eqn = x^3 + sqrt(2)*x + 5 == 0\n sage: a = solve(eqn, x)[0].rhs()\n sage: QQ[a]\n Number Field in a with defining polynomial x^6 + 10*x^3 - 2*x^2 + 25\n with a = 0.7185272465828846? - 1.721353471724806?*I\n\n Here we solve a cubic and then recover it from its complicated\n radical expansion.\n\n ::\n\n sage: f = x^3 - x + 1\n sage: a = f.solve(x)[0].rhs(); a\n -1/2*(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3)*(I*sqrt(3) + 1)\n - 1/6*(-I*sqrt(3) + 1)/(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3)\n sage: a.minpoly()\n x^3 - x + 1\n\n Note that simplification may be necessary to see that the minimal\n polynomial is correct.\n\n ::\n\n sage: a = sqrt(2)+sqrt(3)+sqrt(5)\n sage: f = a.minpoly(); f\n x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576\n sage: f(a)\n (sqrt(5) + sqrt(3) + sqrt(2))^8 - 40*(sqrt(5) + sqrt(3) + sqrt(2))^6\n + 352*(sqrt(5) + sqrt(3) + sqrt(2))^4 - 960*(sqrt(5) + sqrt(3) + sqrt(2))^2\n + 576\n sage: f(a).expand()\n 0\n\n ::\n\n sage: a = sin(pi/7)\n sage: f = a.minpoly(algorithm='numerical'); f\n x^6 - 7/4*x^4 + 7/8*x^2 - 7/64\n sage: f(a).horner(a).numerical_approx(100)\n 0.00000000000000000000000000000\n\n The degree must be high enough (default tops out at 24).\n\n ::\n\n sage: a = sqrt(3) + sqrt(2)\n sage: a.minpoly(algorithm='numerical', bits=100, degree=3)\n Traceback (most recent call last):\n ...\n ValueError: Could not find minimal polynomial (100 bits, degree 3).\n sage: a.minpoly(algorithm='numerical', bits=100, degree=10)\n x^4 - 10*x^2 + 1\n\n ::\n\n sage: cos(pi/33).minpoly(algorithm='algebraic')\n x^10 + 1/2*x^9 - 5/2*x^8 - 5/4*x^7 + 17/8*x^6 + 17/16*x^5\n - 43/64*x^4 - 43/128*x^3 + 3/64*x^2 + 3/128*x + 1/1024\n sage: cos(pi/33).minpoly(algorithm='numerical')\n x^10 + 1/2*x^9 - 5/2*x^8 - 5/4*x^7 + 17/8*x^6 + 17/16*x^5\n - 43/64*x^4 - 43/128*x^3 + 3/64*x^2 + 3/128*x + 1/1024\n\n Sometimes it fails, as it must given that some numbers aren't algebraic::\n\n sage: sin(1).minpoly(algorithm='numerical')\n Traceback (most recent call last):\n ...\n ValueError: Could not find minimal polynomial (1000 bits, degree 24).\n\n .. note::\n\n Of course, failure to produce a minimal polynomial does not\n necessarily indicate that this number is transcendental.\n " if ((algorithm is None) or algorithm.startswith('numeric')): bits_list = ([bits] if bits else [100, 200, 500, 1000]) degree_list = ([degree] if degree else [2, 4, 8, 12, 24]) for bits in bits_list: a = ex.numerical_approx(bits) check_bits = int(((1.25 * bits) + 80)) aa = ex.numerical_approx(check_bits) for degree in degree_list: f = QQ[var](algdep(a, degree)) error = abs(f(aa)) dx = (~ RR((Integer(1) << ((check_bits - degree) - 2)))) expected_error = (abs(f.derivative()(CC(aa))) * dx) if (error < expected_error): ff = f.factor() for (g, e) in ff: lead = g.leading_coefficient() if (lead != 1): g = (g / lead) expected_error = (abs(g.derivative()(CC(aa))) * dx) error = abs(g(aa)) if (error < expected_error): if (g(ex).simplify_trig().canonicalize_radical() == 0): return g elif (epsilon and (error < epsilon)): return g elif (algorithm is not None): raise NotImplementedError(('Could not prove minimal polynomial %s (epsilon %s)' % (g, RR(error).str(no_sci=False)))) if (algorithm is not None): raise ValueError(('Could not find minimal polynomial (%s bits, degree %s).' % (bits, degree))) if ((algorithm is None) or (algorithm == 'algebraic')): from sage.rings.qqbar import QQbar return QQ[var](QQbar(ex).minpoly()) raise ValueError(('Unknown algorithm: %s' % algorithm))
def limit(ex, dir=None, taylor=False, algorithm='maxima', **argv): '\n Return the limit as the variable `v` approaches `a`\n from the given direction.\n\n ::\n\n expr.limit(x = a)\n expr.limit(x = a, dir=\'+\')\n\n INPUT:\n\n - ``dir`` -- (default: ``None``); may have the value\n ``\'plus\'`` (or ``\'+\'`` or ``\'right\'`` or ``\'above\'``) for a limit from above,\n ``\'minus\'`` (or ``\'-\'`` or ``\'left\'`` or ``\'below\'``) for a limit from below, or may be omitted\n (implying a two-sided limit is to be computed).\n\n - ``taylor`` -- (default: ``False``); if ``True``, use Taylor\n series, which allows more limits to be computed (but may also\n crash in some obscure cases due to bugs in Maxima).\n\n - ``**argv`` - 1 named parameter\n\n .. note::\n\n The output may also use ``und`` (undefined), ``ind``\n (indefinite but bounded), and ``infinity`` (complex\n infinity).\n\n EXAMPLES::\n\n sage: x = var(\'x\')\n sage: f = (1 + 1/x)^x\n sage: f.limit(x=oo)\n e\n sage: f.limit(x=5)\n 7776/3125\n\n Domain to real, a regression in 5.46.0, see https://sf.net/p/maxima/bugs/4138 ::\n\n sage: maxima_calculus.eval("domain:real")\n ...\n sage: f.limit(x=1.2).n()\n 2.06961575467...\n sage: maxima_calculus.eval("domain:complex");\n ...\n\n Otherwise, it works ::\n\n sage: f.limit(x=I, taylor=True)\n (-I + 1)^I\n sage: f(x=1.2)\n 2.0696157546720...\n sage: f(x=I)\n (-I + 1)^I\n sage: CDF(f(x=I))\n 2.0628722350809046 + 0.7450070621797239*I\n sage: CDF(f.limit(x=I))\n 2.0628722350809046 + 0.7450070621797239*I\n\n Notice that Maxima may ask for more information::\n\n sage: var(\'a\')\n a\n sage: limit(x^a,x=0)\n Traceback (most recent call last):\n ...\n ValueError: Computation failed since Maxima requested additional\n constraints; using the \'assume\' command before evaluation\n *may* help (example of legal syntax is \'assume(a>0)\', see\n `assume?` for more details)\n Is a positive, negative or zero?\n\n With this example, Maxima is looking for a LOT of information::\n\n sage: assume(a>0)\n sage: limit(x^a,x=0) # random - maxima 5.46.0 does not need extra assumption\n Traceback (most recent call last):\n ...\n ValueError: Computation failed since Maxima requested additional\n constraints; using the \'assume\' command before evaluation *may* help\n (example of legal syntax is \'assume(a>0)\', see `assume?` for\n more details)\n Is a an integer?\n sage: assume(a,\'integer\')\n sage: limit(x^a, x=0) # random - maxima 5.46.0 does not need extra assumption\n Traceback (most recent call last):\n ...\n ValueError: Computation failed since Maxima requested additional\n constraints; using the \'assume\' command before evaluation *may* help\n (example of legal syntax is \'assume(a>0)\', see `assume?` for\n more details)\n Is a an even number?\n sage: assume(a, \'even\')\n sage: limit(x^a, x=0)\n 0\n sage: forget()\n\n More examples::\n\n sage: limit(x*log(x), x=0, dir=\'+\')\n 0\n sage: lim((x+1)^(1/x), x=0)\n e\n sage: lim(e^x/x, x=oo)\n +Infinity\n sage: lim(e^x/x, x=-oo)\n 0\n sage: lim(-e^x/x, x=oo)\n -Infinity\n sage: lim((cos(x))/(x^2), x=0)\n +Infinity\n sage: lim(sqrt(x^2+1) - x, x=oo)\n 0\n sage: lim(x^2/(sec(x)-1), x=0)\n 2\n sage: lim(cos(x)/(cos(x)-1), x=0)\n -Infinity\n sage: lim(x*sin(1/x), x=0)\n 0\n sage: limit(e^(-1/x), x=0, dir=\'right\')\n 0\n sage: limit(e^(-1/x), x=0, dir=\'left\')\n +Infinity\n\n ::\n\n sage: f = log(log(x)) / log(x)\n sage: forget(); assume(x < -2); lim(f, x=0, taylor=True)\n 0\n sage: forget()\n\n Here ind means "indefinite but bounded"::\n\n sage: lim(sin(1/x), x = 0)\n ind\n\n We can use other packages than maxima, namely "sympy", "giac", "fricas".\n\n With the standard package Giac::\n\n sage: from sage.libs.giac.giac import libgiac # random\n sage: (exp(-x)/(2+sin(x))).limit(x=oo, algorithm=\'giac\')\n 0\n sage: limit(e^(-1/x), x=0, dir=\'right\', algorithm=\'giac\')\n 0\n sage: limit(e^(-1/x), x=0, dir=\'left\', algorithm=\'giac\')\n +Infinity\n sage: (x / (x+2^x+cos(x))).limit(x=-infinity, algorithm=\'giac\')\n 1\n\n With the optional package FriCAS::\n\n sage: (x / (x+2^x+cos(x))).limit(x=-infinity, algorithm=\'fricas\') # optional - fricas\n 1\n sage: limit(e^(-1/x), x=0, dir=\'right\', algorithm=\'fricas\') # optional - fricas\n 0\n sage: limit(e^(-1/x), x=0, dir=\'left\', algorithm=\'fricas\') # optional - fricas\n +Infinity\n\n One can also call Mathematica\'s online interface::\n\n sage: limit(pi+log(x)/x,x=oo, algorithm=\'mathematica_free\') # optional - internet\n pi\n\n TESTS::\n\n sage: lim(x^2, x=2, dir=\'nugget\')\n Traceback (most recent call last):\n ...\n ValueError: dir must be one of None, \'plus\', \'+\', \'above\', \'right\',\n \'minus\', \'-\', \'below\', \'left\'\n\n sage: x.limit(x=3, algorithm=\'nugget\')\n Traceback (most recent call last):\n ...\n ValueError: Unknown algorithm: nugget\n\n We check that :trac:`3718` is fixed, so that\n Maxima gives correct limits for the floor function::\n\n sage: limit(floor(x), x=0, dir=\'-\')\n -1\n sage: limit(floor(x), x=0, dir=\'+\')\n 0\n sage: limit(floor(x), x=0)\n ...nd\n\n Maxima gives the right answer here, too, showing\n that :trac:`4142` is fixed::\n\n sage: f = sqrt(1 - x^2)\n sage: g = diff(f, x); g\n -x/sqrt(-x^2 + 1)\n sage: limit(g, x=1, dir=\'-\')\n -Infinity\n\n ::\n\n sage: limit(1/x, x=0)\n Infinity\n sage: limit(1/x, x=0, dir=\'+\')\n +Infinity\n sage: limit(1/x, x=0, dir=\'-\')\n -Infinity\n\n Check that :trac:`8942` is fixed::\n\n sage: f(x) = (cos(pi/4 - x) - tan(x)) / (1 - sin(pi/4 + x))\n sage: limit(f(x), x=pi/4, dir=\'minus\')\n +Infinity\n sage: limit(f(x), x=pi/4, dir=\'plus\')\n -Infinity\n sage: limit(f(x), x=pi/4)\n Infinity\n\n Check that :trac:`12708` is fixed::\n\n sage: limit(tanh(x), x=0)\n 0\n\n Check that :trac:`15386` is fixed::\n\n sage: n = var(\'n\')\n sage: assume(n>0)\n sage: sequence = -(3*n^2 + 1)*(-1)^n / sqrt(n^5 + 8*n^3 + 8)\n sage: limit(sequence, n=infinity)\n 0\n\n Check if :trac:`23048` is fixed::\n\n sage: (1/(x-3)).limit(x=3, dir=\'below\')\n -Infinity\n\n From :trac:`14677`::\n\n sage: f = (x^x - sin(x)^sin(x)) / (x^3*log(x))\n sage: limit(f, x=0, algorithm=\'fricas\') # optional - fricas\n und\n\n sage: limit(f, x=0, dir=\'right\', algorithm=\'fricas\') # optional - fricas\n 1/6\n\n From :trac:`26497`::\n\n sage: mu, y, sigma = var("mu, y, sigma")\n sage: f = 1/2*sqrt(2)*e^(-1/2*(mu - log(y))^2/sigma^2)/(sqrt(pi)*sigma*y)\n sage: limit(f, y=0, algorithm=\'fricas\') # optional - fricas\n 0\n\n From :trac:`26060`::\n\n sage: limit(x / (x + 2^x + cos(x)), x=-infinity)\n 1\n ' if (not isinstance(ex, Expression)): ex = SR(ex) if (len(argv) != 1): raise ValueError('call the limit function like this, e.g. limit(expr, x=2).') else: (k,) = argv.keys() v = var(k) a = argv[k] if (taylor and (algorithm == 'maxima')): algorithm = 'maxima_taylor' dir_plus = ['plus', '+', 'above', 'right'] dir_minus = ['minus', '-', 'below', 'left'] dir_both = (([None] + dir_plus) + dir_minus) if (dir not in dir_both): raise ValueError(('dir must be one of ' + ', '.join(map(repr, dir_both)))) if (algorithm == 'maxima'): if (dir is None): l = maxima.sr_limit(ex, v, a) elif (dir in dir_plus): l = maxima.sr_limit(ex, v, a, 'plus') elif (dir in dir_minus): l = maxima.sr_limit(ex, v, a, 'minus') elif (algorithm == 'maxima_taylor'): if (dir is None): l = maxima.sr_tlimit(ex, v, a) elif (dir in dir_plus): l = maxima.sr_tlimit(ex, v, a, 'plus') elif (dir in dir_minus): l = maxima.sr_tlimit(ex, v, a, 'minus') elif (algorithm == 'sympy'): import sympy if (dir is None): l = sympy.limit(ex._sympy_(), v._sympy_(), a._sympy_()) elif (dir in dir_plus): l = sympy.limit(ex._sympy_(), v._sympy_(), a._sympy_(), dir='+') elif (dir in dir_minus): l = sympy.limit(ex._sympy_(), v._sympy_(), a._sympy_(), dir='-') elif (algorithm == 'fricas'): from sage.interfaces.fricas import fricas eq = fricas.equation(v._fricas_(), a._fricas_()) f = ex._fricas_() if (dir is None): l = fricas.limit(f, eq).sage() if isinstance(l, dict): l = maxima('und') elif (dir in dir_plus): l = fricas.limit(f, eq, '"right"').sage() elif (dir in dir_minus): l = fricas.limit(f, eq, '"left"').sage() elif (algorithm == 'giac'): from sage.libs.giac.giac import libgiac v = v._giac_init_() a = a._giac_init_() if (dir is None): l = libgiac.limit(ex, v, a).sage() elif (dir in dir_plus): l = libgiac.limit(ex, v, a, 1).sage() elif (dir in dir_minus): l = libgiac.limit(ex, v, a, (- 1)).sage() elif (algorithm == 'mathematica_free'): return mma_free_limit(ex, v, a, dir) else: raise ValueError(('Unknown algorithm: %s' % algorithm)) return ex.parent()(l)
def mma_free_limit(expression, v, a, dir=None): "\n Limit using Mathematica's online interface.\n\n INPUT:\n\n - ``expression`` -- symbolic expression\n - ``v`` -- variable\n - ``a`` -- value where the variable goes to\n - ``dir`` -- ``'+'``, ``'-'`` or ``None`` (optional, default: ``None``)\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import mma_free_limit\n sage: mma_free_limit(sin(x)/x, x, a=0) # optional - internet\n 1\n\n Another simple limit::\n\n sage: mma_free_limit(e^(-x), x, a=oo) # optional - internet\n 0\n " from sage.interfaces.mathematica import request_wolfram_alpha, parse_moutput_from_json, symbolic_expression_from_mathematica_string dir_plus = ['plus', '+', 'above', 'right'] dir_minus = ['minus', '-', 'below', 'left'] math_expr = expression._mathematica_init_() variable = v._mathematica_init_() a = a._mathematica_init_() if (dir is None): input = 'Limit[{},{} -> {}]'.format(math_expr, variable, a) elif (dir in dir_plus): dir = 'Direction -> "FromAbove"' input = 'Limit[{}, {} -> {}, {}]'.format(math_expr, variable, a, dir) elif (dir in dir_minus): dir = 'Direction -> "FromBelow"' input = 'Limit[{}, {} -> {}, {}]'.format(math_expr, variable, a, dir) else: raise ValueError('wrong input for limit') json_page_data = request_wolfram_alpha(input) all_outputs = parse_moutput_from_json(json_page_data) if (not all_outputs): raise ValueError('no outputs found in the answer from Wolfram Alpha') first_output = all_outputs[0] return symbolic_expression_from_mathematica_string(first_output)
def laplace(ex, t, s, algorithm='maxima'): '\n Return the Laplace transform with respect to the variable `t` and\n transform parameter `s`, if possible.\n\n If this function cannot find a solution, a formal function is returned.\n The function that is returned may be viewed as a function of `s`.\n\n DEFINITION:\n\n The Laplace transform of a function `f(t)`, defined for all real numbers\n `t \\geq 0`, is the function `F(s)` defined by\n\n .. MATH::\n\n F(s) = \\int_{0}^{\\infty} e^{-st} f(t) dt.\n\n INPUT:\n\n - ``ex`` -- a symbolic expression\n\n - ``t`` -- independent variable\n\n - ``s`` -- transform parameter\n\n - ``algorithm`` -- (default: ``\'maxima\'``) one of\n\n - ``\'maxima\'`` -- use Maxima (the default)\n\n - ``\'sympy\'`` -- use SymPy\n\n - ``\'giac\'`` -- use Giac\n\n .. NOTE::\n\n The ``\'sympy\'`` algorithm returns the tuple (`F`, `a`, ``cond``)\n where `F` is the Laplace transform of `f(t)`,\n `Re(s)>a` is the half-plane of convergence, and ``cond`` are\n auxiliary convergence conditions.\n\n .. SEEALSO::\n\n :func:`inverse_laplace`\n\n EXAMPLES:\n\n We compute a few Laplace transforms::\n\n sage: var(\'x, s, z, t, t0\')\n (x, s, z, t, t0)\n sage: sin(x).laplace(x, s)\n 1/(s^2 + 1)\n sage: (z + exp(x)).laplace(x, s)\n z/s + 1/(s - 1)\n sage: log(t/t0).laplace(t, s)\n -(euler_gamma + log(s) + log(t0))/s\n\n We do a formal calculation::\n\n sage: f = function(\'f\')(x)\n sage: g = f.diff(x); g\n diff(f(x), x)\n sage: g.laplace(x, s)\n s*laplace(f(x), x, s) - f(0)\n\n A BATTLE BETWEEN the X-women and the Y-men (by David\n Joyner): Solve\n\n .. MATH::\n\n x\' = -16y, x(0)=270, y\' = -x + 1, y(0) = 90.\n\n This models a fight between two sides, the "X-women" and the\n "Y-men", where the X-women have 270 initially and the Y-men have\n 90, but the Y-men are better at fighting, because of the higher\n factor of "-16" vs "-1", and also get an occasional reinforcement,\n because of the "+1" term.\n\n ::\n\n sage: var(\'t\')\n t\n sage: t = var(\'t\')\n sage: x = function(\'x\')(t)\n sage: y = function(\'y\')(t)\n sage: de1 = x.diff(t) + 16*y\n sage: de2 = y.diff(t) + x - 1\n sage: de1.laplace(t, s)\n s*laplace(x(t), t, s) + 16*laplace(y(t), t, s) - x(0)\n sage: de2.laplace(t, s)\n s*laplace(y(t), t, s) - 1/s + laplace(x(t), t, s) - y(0)\n\n Next we form the augmented matrix of the above system::\n\n sage: A = matrix([[s, 16, 270], [1, s, 90+1/s]])\n sage: E = A.echelon_form()\n sage: xt = E[0,2].inverse_laplace(s,t)\n sage: yt = E[1,2].inverse_laplace(s,t)\n sage: xt\n -91/2*e^(4*t) + 629/2*e^(-4*t) + 1\n sage: yt\n 91/8*e^(4*t) + 629/8*e^(-4*t)\n sage: p1 = plot(xt, 0, 1/2, rgbcolor=(1,0,0)) # needs sage.plot\n sage: p2 = plot(yt, 0, 1/2, rgbcolor=(0,1,0)) # needs sage.plot\n sage: import tempfile\n sage: with tempfile.NamedTemporaryFile(suffix=".png") as f: # needs sage.plot\n ....: (p1 + p2).save(f.name)\n\n Another example::\n\n sage: var(\'a,s,t\')\n (a, s, t)\n sage: f = exp (2*t + a) * sin(t) * t; f\n t*e^(a + 2*t)*sin(t)\n sage: L = laplace(f, t, s); L\n 2*(s - 2)*e^a/(s^2 - 4*s + 5)^2\n sage: inverse_laplace(L, s, t)\n t*e^(a + 2*t)*sin(t)\n\n The Laplace transform of the exponential function::\n\n sage: laplace(exp(x), x, s)\n 1/(s - 1)\n\n Dirac\'s delta distribution is handled (the output of SymPy is\n related to a choice that has to be made when defining Laplace\n transforms of distributions)::\n\n sage: laplace(dirac_delta(t), t, s)\n 1\n sage: F, a, cond = laplace(dirac_delta(t), t, s, algorithm=\'sympy\')\n sage: a, cond # random - sympy <1.10 gives (-oo, True)\n (0, True)\n sage: F # random - sympy <1.9 includes undefined heaviside(0) in answer\n 1\n sage: laplace(dirac_delta(t), t, s, algorithm=\'giac\')\n 1\n\n Heaviside step function can be handled with different interfaces.\n Try with Maxima::\n\n sage: laplace(heaviside(t-1), t, s)\n e^(-s)/s\n\n Try with giac::\n\n sage: laplace(heaviside(t-1), t, s, algorithm=\'giac\')\n e^(-s)/s\n\n Try with SymPy::\n\n sage: laplace(heaviside(t-1), t, s, algorithm=\'sympy\')\n (e^(-s)/s, 0, True)\n\n TESTS:\n\n Testing Giac::\n\n sage: var(\'t, s\')\n (t, s)\n sage: laplace(5*cos(3*t-2)*heaviside(t-2), t, s, algorithm=\'giac\')\n 5*(s*cos(4)*e^(-2*s) - 3*e^(-2*s)*sin(4))/(s^2 + 9)\n\n Check unevaluated expression from Giac (it is locale-dependent, see\n :trac:`22833`)::\n\n sage: var(\'n\')\n n\n sage: laplace(t^n, t, s, algorithm=\'giac\')\n laplace(t^n, t, s)\n\n Testing SymPy::\n\n sage: F, a, cond = laplace(t^n, t, s, algorithm=\'sympy\')\n sage: a, cond\n (0, re(n) > -1)\n sage: F.simplify()\n s^(-n - 1)*gamma(n + 1)\n\n Testing Maxima::\n\n sage: laplace(t^n, t, s, algorithm=\'maxima\')\n s^(-n - 1)*gamma(n + 1)\n\n Check that :trac:`24212` is fixed::\n\n sage: F, a, cond = laplace(cos(t^2), t, s, algorithm=\'sympy\')\n sage: a, cond\n (0, True)\n sage: F._sympy_().simplify()\n sqrt(pi)*(sqrt(2)*sin(s**2/4)*fresnelc(sqrt(2)*s/(2*sqrt(pi))) -\n sqrt(2)*cos(s**2/4)*fresnels(sqrt(2)*s/(2*sqrt(pi))) + cos(s**2/4 + pi/4))/2\n\n Testing result from SymPy that Sage doesn\'t know how to handle::\n\n sage: laplace(cos(-1/t), t, s, algorithm=\'sympy\')\n Traceback (most recent call last):\n ...\n AttributeError: Unable to convert SymPy result (=meijerg(((), ()), ((-1/2, 0, 1/2), (0,)), ...)/4) into Sage\n ' if (not isinstance(ex, (Expression, Function))): ex = SR(ex) if (algorithm == 'maxima'): return ex.parent()(ex._maxima_().laplace(var(t), var(s))) elif (algorithm == 'sympy'): (ex_sy, t, s) = (expr._sympy_() for expr in (ex, t, s)) from sympy import laplace_transform from sage.interfaces.sympy import sympy_init sympy_init() result = laplace_transform(ex_sy, t, s) if isinstance(result, tuple): try: (result, a, cond) = result return (result._sage_(), a, cond) except AttributeError: raise AttributeError('Unable to convert SymPy result (={}) into Sage'.format(result)) elif ('LaplaceTransform' in format(result)): return dummy_laplace(ex, t, s) else: return result elif (algorithm == 'giac'): from sage.interfaces.giac import giac try: result = giac.laplace(ex, t, s) except TypeError: raise ValueError(('Giac cannot make sense of: %s' % ex)) if (('integrate' in format(result)) or ('integration' in format(result))): return dummy_laplace(ex, t, s) else: return result.sage() else: raise ValueError(('Unknown algorithm: %s' % algorithm))
def inverse_laplace(ex, s, t, algorithm='maxima'): "\n Return the inverse Laplace transform with respect to the variable `t` and\n transform parameter `s`, if possible.\n\n If this function cannot find a solution, a formal function is returned.\n The function that is returned may be viewed as a function of `t`.\n\n DEFINITION:\n\n The inverse Laplace transform of a function `F(s)` is the function\n `f(t)`, defined by\n\n .. MATH::\n\n f(t) = \\frac{1}{2\\pi i} \\int_{\\gamma-i\\infty}^{\\gamma + i\\infty} e^{st} F(s) ds,\n\n where `\\gamma` is chosen so that the contour path of\n integration is in the region of convergence of `F(s)`.\n\n INPUT:\n\n - ``ex`` -- a symbolic expression\n\n - ``s`` -- transform parameter\n\n - ``t`` -- independent variable\n\n - ``algorithm`` -- (default: ``'maxima'``) one of\n\n - ``'maxima'`` -- use Maxima (the default)\n\n - ``'sympy'`` -- use SymPy\n\n - ``'giac'`` -- use Giac\n\n .. SEEALSO::\n\n :func:`laplace`\n\n EXAMPLES::\n\n sage: var('w, m')\n (w, m)\n sage: f = (1/(w^2+10)).inverse_laplace(w, m); f\n 1/10*sqrt(10)*sin(sqrt(10)*m)\n sage: laplace(f, m, w)\n 1/(w^2 + 10)\n\n sage: f(t) = t*cos(t)\n sage: s = var('s')\n sage: L = laplace(f, t, s); L\n t |--> 2*s^2/(s^2 + 1)^2 - 1/(s^2 + 1)\n sage: inverse_laplace(L, s, t)\n t |--> t*cos(t)\n sage: inverse_laplace(1/(s^3+1), s, t)\n 1/3*(sqrt(3)*sin(1/2*sqrt(3)*t) - cos(1/2*sqrt(3)*t))*e^(1/2*t) + 1/3*e^(-t)\n\n No explicit inverse Laplace transform, so one is returned formally a\n function ``ilt``::\n\n sage: inverse_laplace(cos(s), s, t)\n ilt(cos(s), s, t)\n\n Transform an expression involving a time-shift, via SymPy::\n\n sage: inverse_laplace(1/s^2*exp(-s), s, t, algorithm='sympy').simplify()\n (t - 1)*heaviside(t - 1)\n\n The same instance with Giac::\n\n sage: inverse_laplace(1/s^2*exp(-s), s, t, algorithm='giac')\n (t - 1)*heaviside(t - 1)\n\n Transform a rational expression::\n\n sage: inverse_laplace((2*s^2*exp(-2*s) - exp(-s))/(s^3+1), s, t,\n ....: algorithm='giac')\n -1/3*(sqrt(3)*e^(1/2*t - 1/2)*sin(1/2*sqrt(3)*(t - 1))\n - cos(1/2*sqrt(3)*(t - 1))*e^(1/2*t - 1/2) + e^(-t + 1))*heaviside(t - 1)\n + 2/3*(2*cos(1/2*sqrt(3)*(t - 2))*e^(1/2*t - 1) + e^(-t + 2))*heaviside(t - 2)\n\n sage: inverse_laplace(1/(s - 1), s, x)\n e^x\n\n The inverse Laplace transform of a constant is a delta\n distribution::\n\n sage: inverse_laplace(1, s, t)\n dirac_delta(t)\n sage: inverse_laplace(1, s, t, algorithm='sympy')\n dirac_delta(t)\n sage: inverse_laplace(1, s, t, algorithm='giac')\n dirac_delta(t)\n\n TESTS:\n\n Testing unevaluated expression from Maxima::\n\n sage: var('t, s')\n (t, s)\n sage: inverse_laplace(exp(-s)/s, s, t)\n ilt(e^(-s)/s, s, t)\n\n Testing Giac::\n\n sage: inverse_laplace(exp(-s)/s, s, t, algorithm='giac')\n heaviside(t - 1)\n\n Testing SymPy::\n\n sage: inverse_laplace(exp(-s)/s, s, t, algorithm='sympy')\n heaviside(t - 1)\n\n Testing unevaluated expression from Giac::\n\n sage: n = var('n')\n sage: inverse_laplace(1/s^n, s, t, algorithm='giac')\n ilt(1/(s^n), t, s)\n\n Try with Maxima::\n\n sage: inverse_laplace(1/s^n, s, t, algorithm='maxima')\n ilt(1/(s^n), s, t)\n\n Try with SymPy::\n\n sage: inverse_laplace(1/s^n, s, t, algorithm='sympy')\n t^(n - 1)*heaviside(t)/gamma(n)\n\n Testing unevaluated expression from SymPy::\n\n sage: inverse_laplace(cos(s), s, t, algorithm='sympy')\n ilt(cos(s), t, s)\n\n Testing the same with Giac::\n\n sage: inverse_laplace(cos(s), s, t, algorithm='giac')\n ilt(cos(s), t, s)\n " if (not isinstance(ex, Expression)): ex = SR(ex) if (algorithm == 'maxima'): return ex.parent()(ex._maxima_().ilt(var(s), var(t))) elif (algorithm == 'sympy'): (ex_sy, s, t) = (expr._sympy_() for expr in (ex, s, t)) from sympy import inverse_laplace_transform from sage.interfaces.sympy import sympy_init sympy_init() result = inverse_laplace_transform(ex_sy, s, t) try: return result._sage_() except AttributeError: if ('InverseLaplaceTransform' in format(result)): return dummy_inverse_laplace(ex, t, s) else: raise AttributeError('Unable to convert SymPy result (={}) into Sage'.format(result)) elif (algorithm == 'giac'): from sage.interfaces.giac import giac try: result = giac.invlaplace(ex, s, t) except TypeError: raise ValueError(('Giac cannot make sense of: %s' % ex)) if ('ilaplace' in format(result)): return dummy_inverse_laplace(ex, t, s) else: return result.sage() else: raise ValueError(('Unknown algorithm: %s' % algorithm))
def at(ex, *args, **kwds): "\n Parses ``at`` formulations from other systems, such as Maxima.\n Replaces evaluation 'at' a point with substitution method of\n a symbolic expression.\n\n EXAMPLES:\n\n We do not import ``at`` at the top level, but we can use it\n as a synonym for substitution if we import it::\n\n sage: g = x^3 - 3\n sage: from sage.calculus.calculus import at\n sage: at(g, x=1)\n -2\n sage: g.subs(x=1)\n -2\n\n We find a formal Taylor expansion::\n\n sage: h,x = var('h,x')\n sage: u = function('u')\n sage: u(x + h)\n u(h + x)\n sage: diff(u(x+h), x)\n D[0](u)(h + x)\n sage: taylor(u(x+h), h, 0, 4)\n 1/24*h^4*diff(u(x), x, x, x, x) + 1/6*h^3*diff(u(x), x, x, x)\n + 1/2*h^2*diff(u(x), x, x) + h*diff(u(x), x) + u(x)\n\n We compute a Laplace transform::\n\n sage: var('s,t')\n (s, t)\n sage: f = function('f')(t)\n sage: f.diff(t, 2)\n diff(f(t), t, t)\n sage: f.diff(t,2).laplace(t,s)\n s^2*laplace(f(t), t, s) - s*f(0) - D[0](f)(0)\n\n We can also accept a non-keyword list of expression substitutions,\n like Maxima does (:trac:`12796`)::\n\n sage: from sage.calculus.calculus import at\n sage: f = function('f')\n sage: at(f(x), [x == 1])\n f(1)\n\n TESTS:\n\n Our one non-keyword argument must be a list::\n\n sage: from sage.calculus.calculus import at\n sage: f = function('f')\n sage: at(f(x), x == 1)\n Traceback (most recent call last):\n ...\n TypeError: at can take at most one argument, which must be a list\n\n We should convert our first argument to a symbolic expression::\n\n sage: from sage.calculus.calculus import at\n sage: at(int(1), x=1)\n 1\n\n " if (not isinstance(ex, (Expression, Function))): ex = SR(ex) kwds = {(k[10:] if (k[:10] == '_SAGE_VAR_') else k): v for (k, v) in kwds.items()} if ((len(args) == 1) and isinstance(args[0], list)): for c in args[0]: kwds[str(c.lhs())] = c.rhs() elif args: raise TypeError('at can take at most one argument, which must be a list') return ex.subs(**kwds)
def dummy_diff(*args): "\n This function is called when 'diff' appears in a Maxima string.\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import dummy_diff\n sage: x,y = var('x,y')\n sage: dummy_diff(sin(x*y), x, SR(2), y, SR(1))\n -x*y^2*cos(x*y) - 2*y*sin(x*y)\n\n Here the function is used implicitly::\n\n sage: a = var('a')\n sage: f = function('cr')(a)\n sage: g = f.diff(a); g\n diff(cr(a), a)\n " f = args[0] args = list(args[1:]) for i in range(1, len(args), 2): args[i] = Integer(args[i]) return f.diff(*args)
def dummy_integrate(*args): "\n This function is called to create formal wrappers of integrals that\n Maxima can't compute:\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import dummy_integrate\n sage: f = function('f')\n sage: dummy_integrate(f(x), x)\n integrate(f(x), x)\n sage: a,b = var('a,b')\n sage: dummy_integrate(f(x), x, a, b)\n integrate(f(x), x, a, b)\n " if (len(args) == 4): return definite_integral(*args, hold=True) else: return indefinite_integral(*args, hold=True)
def dummy_laplace(*args): "\n This function is called to create formal wrappers of laplace transforms\n that Maxima can't compute:\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import dummy_laplace\n sage: s,t = var('s,t')\n sage: f = function('f')\n sage: dummy_laplace(f(t), t, s)\n laplace(f(t), t, s)\n " return _laplace(args[0], var(repr(args[1])), var(repr(args[2])))
def dummy_inverse_laplace(*args): "\n This function is called to create formal wrappers of inverse Laplace\n transforms that Maxima can't compute:\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import dummy_inverse_laplace\n sage: s,t = var('s,t')\n sage: F = function('F')\n sage: dummy_inverse_laplace(F(s), s, t)\n ilt(F(s), s, t)\n " return _inverse_laplace(args[0], var(repr(args[1])), var(repr(args[2])))
def dummy_pochhammer(*args): "\n This function is called to create formal wrappers of Pochhammer symbols\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import dummy_pochhammer\n sage: s,t = var('s,t')\n sage: dummy_pochhammer(s, t)\n gamma(s + t)/gamma(s)\n " (x, y) = args from sage.functions.gamma import gamma return (gamma((x + y)) / gamma(x))
def _laplace_latex_(self, *args): "\n Return LaTeX expression for Laplace transform of a symbolic function.\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import _laplace_latex_\n sage: var('s,t')\n (s, t)\n sage: f = function('f')(t)\n sage: _laplace_latex_(0,f,t,s)\n '\\\\mathcal{L}\\\\left(f\\\\left(t\\\\right), t, s\\\\right)'\n sage: latex(laplace(f, t, s))\n \\mathcal{L}\\left(f\\left(t\\right), t, s\\right)\n\n " return ('\\mathcal{L}\\left(%s\\right)' % ', '.join((latex(x) for x in args)))
def _inverse_laplace_latex_(self, *args): "\n Return LaTeX expression for inverse Laplace transform\n of a symbolic function.\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import _inverse_laplace_latex_\n sage: var('s,t')\n (s, t)\n sage: F = function('F')(s)\n sage: _inverse_laplace_latex_(0,F,s,t)\n '\\\\mathcal{L}^{-1}\\\\left(F\\\\left(s\\\\right), s, t\\\\right)'\n sage: latex(inverse_laplace(F,s,t))\n \\mathcal{L}^{-1}\\left(F\\left(s\\right), s, t\\right)\n " return ('\\mathcal{L}^{-1}\\left(%s\\right)' % ', '.join((latex(x) for x in args)))
def _is_function(v): "\n Return whether a symbolic element is a function, not a variable.\n\n TESTS::\n\n sage: from sage.calculus.calculus import _is_function\n sage: _is_function(x)\n False\n sage: _is_function(sin)\n True\n\n Check that :trac:`31756` is fixed::\n\n sage: from sage.symbolic.expression import symbol_table\n sage: _is_function(symbol_table['mathematica'][('Gamma', 1)])\n True\n\n sage: from sage.symbolic.expression import register_symbol\n sage: foo = lambda x: x^2 + 1\n sage: register_symbol(foo, dict(mathematica='Foo')) # optional - mathematica\n sage: mathematica('Foo[x]').sage() # optional - mathematica\n x^2 + 1\n " return (isinstance(v, Function) or isinstance(v, FunctionType))
def symbolic_expression_from_maxima_string(x, equals_sub=False, maxima=maxima): '\n Given a string representation of a Maxima expression, parse it and\n return the corresponding Sage symbolic expression.\n\n INPUT:\n\n - ``x`` -- a string\n\n - ``equals_sub`` -- (default: ``False``) if ``True``, replace\n \'=\' by \'==\' in self\n\n - ``maxima`` -- (default: the calculus package\'s copy of\n Maxima) the Maxima interpreter to use.\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms\n sage: sefms(\'x^%e + %e^%pi + %i + sin(0)\')\n x^e + e^pi + I\n sage: f = function(\'f\')(x)\n sage: sefms(\'?%at(f(x),x=2)#1\')\n f(2) != 1\n sage: a = sage.calculus.calculus.maxima("x#0"); a\n x # 0\n sage: a.sage()\n x != 0\n\n TESTS:\n\n :trac:`8459` fixed::\n\n sage: maxima(\'3*li[2](u)+8*li[33](exp(u))\').sage()\n 3*dilog(u) + 8*polylog(33, e^u)\n\n Check if :trac:`8345` is fixed::\n\n sage: assume(x,\'complex\')\n sage: t = x.conjugate()\n sage: latex(t)\n \\overline{x}\n sage: latex(t._maxima_()._sage_())\n \\overline{x}\n\n Check that we can understand maxima\'s not-equals (:trac:`8969`)::\n\n sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms\n sage: sefms("x!=3") == (factorial(x) == 3)\n True\n sage: sefms("x # 3") == SR(x != 3)\n True\n sage: solve([x != 5], x) in [[[x - 5 != 0]], [[x < 5], [5 < x]]]\n True\n sage: solve([2*x==3, x != 5], x)\n [[x == (3/2)...\n\n Make sure that we don\'t accidentally pick up variables in the maxima namespace (:trac:`8734`)::\n\n sage: sage.calculus.calculus.maxima(\'my_new_var : 2\')\n 2\n sage: var(\'my_new_var\').full_simplify()\n my_new_var\n\n ODE solution constants are treated differently (:trac:`16007`)::\n\n sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms\n sage: sefms(\'%k1*x + %k2*y + %c\')\n _K1*x + _K2*y + _C\n\n Check that some hypothetical variables don\'t end up as special constants (:trac:`6882`)::\n\n sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms\n sage: sefms(\'%i\')^2\n -1\n sage: ln(sefms(\'%e\'))\n 1\n sage: sefms(\'i\')^2\n _i^2\n sage: sefms(\'I\')^2\n _I^2\n sage: sefms(\'ln(e)\')\n ln(_e)\n sage: sefms(\'%inf\')\n +Infinity\n ' var_syms = {k[0]: v for (k, v) in symbol_table.get('maxima', {}).items() if (not _is_function(v))} function_syms = {k[0]: v for (k, v) in symbol_table.get('maxima', {}).items() if _is_function(v)} if (not x): raise RuntimeError("invalid symbolic expression -- ''") maxima.set('_tmp_', x) s = maxima._eval_line('_tmp_;') s = s.replace("'", '') delayed_functions = maxima_qp.findall(s) if len(delayed_functions): for X in delayed_functions: if (X == '?%at'): pass else: function_syms[X[2:]] = function_factory(X[2:]) s = s.replace('?%', '') s = maxima_hyper.sub('hypergeometric', s) cursor = 0 l = [] for m in maxima_var.finditer(s): if (m.group(0) in symtable): l.append(s[cursor:m.start()]) l.append(symtable.get(m.group(0))) cursor = m.end() if (cursor > 0): l.append(s[cursor:]) s = ''.join(l) s = s.replace('%', '') s = s.replace('#', '!=') while True: olds = s s = polylog_ex.sub('polylog(\\1,', s) s = maxima_polygamma.sub('psi(\\g<1>,', s) if (s == olds): break if equals_sub: s = s.replace('=', '==') s = s.replace('!==', '!=') if (s[0:5] == 'union'): s = s[5:] s = s[(s.find('(') + 1):s.rfind(')')] s = (('[' + s) + ']') if (s[0:5] == 'solve'): s = s[5:] s = s[(s.find('(') + 1):(s.find(']') + 1)] search = sci_not.search(s) while (search is not None): (start, end) = search.span() r = create_RealNumber(s[start:end]).str(no_sci=2, truncate=True) s = s.replace(s[start:end], r) search = sci_not.search(s) function_syms['diff'] = dummy_diff function_syms['integrate'] = dummy_integrate function_syms['laplace'] = dummy_laplace function_syms['ilt'] = dummy_inverse_laplace function_syms['at'] = at function_syms['pochhammer'] = dummy_pochhammer global is_simplified try: is_simplified = True SRM_parser._variable_constructor().set_names(var_syms) SRM_parser._callable_constructor().set_names(function_syms) return SRM_parser.parse_sequence(s) except SyntaxError: raise TypeError(("unable to make sense of Maxima expression '%s' in Sage" % s)) finally: is_simplified = False
def mapped_opts(v): "\n Used internally when creating a string of options to pass to\n Maxima.\n\n INPUT:\n\n - ``v`` -- an object\n\n OUTPUT: a string.\n\n The main use of this is to turn Python bools into lower case\n strings.\n\n EXAMPLES::\n\n sage: sage.calculus.calculus.mapped_opts(True)\n 'true'\n sage: sage.calculus.calculus.mapped_opts(False)\n 'false'\n sage: sage.calculus.calculus.mapped_opts('bar')\n 'bar'\n " if isinstance(v, bool): return str(v).lower() return str(v)
def maxima_options(**kwds): "\n Used internally to create a string of options to pass to Maxima.\n\n EXAMPLES::\n\n sage: sage.calculus.calculus.maxima_options(an_option=True, another=False, foo='bar')\n 'an_option=true,another=false,foo=bar'\n " return ','.join((('%s=%s' % (key, mapped_opts(val))) for (key, val) in sorted(kwds.items())))
def _find_var(name, interface=None): "\n Function to pass to Parser for constructing\n variables from strings. For internal use.\n\n EXAMPLES::\n\n sage: y = var('y')\n sage: sage.calculus.calculus._find_var('y')\n y\n sage: sage.calculus.calculus._find_var('I')\n I\n sage: sage.calculus.calculus._find_var(repr(maxima(y)), interface='maxima')\n y\n sage: sage.calculus.calculus._find_var(repr(giac(y)), interface='giac')\n y\n " if (interface == 'maxima'): if name.startswith('_SAGE_VAR_'): return var(name[10:]) elif (interface == 'giac'): if name.startswith('sageVAR'): return var(name[7:]) else: v = SR.symbols.get(name) if (v is not None): return v import sage.all try: return SR(sage.all.__dict__[name]) except (KeyError, TypeError): return var(name)
def _find_func(name, create_when_missing=True): "\n Function to pass to Parser for constructing\n functions from strings. For internal use.\n\n EXAMPLES::\n\n sage: sage.calculus.calculus._find_func('limit')\n limit\n sage: sage.calculus.calculus._find_func('zeta_zeros')\n zeta_zeros\n sage: f(x)=sin(x)\n sage: sage.calculus.calculus._find_func('f')\n f\n sage: sage.calculus.calculus._find_func('g', create_when_missing=False)\n sage: s = sage.calculus.calculus._find_func('sin')\n sage: s(0)\n 0\n " f = symbol_table['functions'].get(name) if (f is not None): return f import sage.all try: f = SR(sage.all.__dict__[name]) if (not isinstance(f, Expression)): return f except (KeyError, TypeError): if create_when_missing: return function_factory(name) else: return None
def symbolic_expression_from_string(s, syms=None, accept_sequence=False, *, parser=None): "\n Given a string, (attempt to) parse it and return the\n corresponding Sage symbolic expression. Normally used\n to return Maxima output to the user.\n\n INPUT:\n\n - ``s`` -- a string\n\n - ``syms`` -- (default: ``{}``) dictionary of\n strings to be regarded as symbols or functions;\n keys are pairs (string, number of arguments)\n\n - ``accept_sequence`` -- (default: ``False``) controls whether\n to allow a (possibly nested) set of lists and tuples\n as input\n\n - ``parser`` -- (default: ``SR_parser``) parser for internal use\n\n EXAMPLES::\n\n sage: from sage.calculus.calculus import symbolic_expression_from_string\n sage: y = var('y')\n sage: symbolic_expression_from_string('[sin(0)*x^2,3*spam+e^pi]',\n ....: syms={('spam',0): y}, accept_sequence=True)\n [0, 3*y + e^pi]\n\n TESTS:\n\n Check that the precision is preserved (:trac:`28814`)::\n\n sage: symbolic_expression_from_string(str(RealField(100)(1/3)))\n 0.3333333333333333333333333333\n sage: symbolic_expression_from_string(str(RealField(100)(10^-500/3)))\n 3.333333333333333333333333333e-501\n\n The Giac interface uses a different parser (:trac:`30133`)::\n\n sage: from sage.calculus.calculus import SR_parser_giac\n sage: symbolic_expression_from_string(repr(giac(SR.var('e'))), parser=SR_parser_giac)\n e\n " if (syms is None): syms = {} if (parser is None): parser = SR_parser parse_func = (parser.parse_sequence if accept_sequence else parser.parse_expression) parser._variable_constructor().set_names({k[0]: v for (k, v) in syms.items() if (not _is_function(v))}) parser._callable_constructor().set_names({k[0]: v for (k, v) in syms.items() if _is_function(v)}) return parse_func(s)
def fricas_desolve(de, dvar, ics, ivar): '\n Solve an ODE using FriCAS.\n\n EXAMPLES::\n\n sage: x = var(\'x\')\n sage: y = function(\'y\')(x)\n sage: desolve(diff(y,x) + y - 1, y, algorithm="fricas") # optional - fricas\n _C0*e^(-x) + 1\n\n sage: desolve(diff(y, x) + y == y^3*sin(x), y, algorithm="fricas") # optional - fricas\n -1/5*(2*cos(x)*y(x)^2 + 4*sin(x)*y(x)^2 - 5)*e^(-2*x)/y(x)^2\n\n TESTS::\n\n sage: from sage.calculus.desolvers import fricas_desolve\n sage: Y = fricas_desolve(diff(y,x) + y - 1, y, [42,1783], x) # optional - fricas\n sage: Y.subs(x=42) # optional - fricas\n 1783\n ' from sage.interfaces.fricas import fricas from sage.symbolic.ring import SR if (ics is None): y = fricas(de).solve(dvar.operator(), ivar).sage() else: eq = fricas.equation(ivar, ics[0]) y = fricas(de).solve(dvar.operator(), eq, ics[1:]).sage() if isinstance(y, dict): basis = y['basis'] particular = y['particular'] return (particular + sum(((SR.var(('_C' + str(i))) * v) for (i, v) in enumerate(basis)))) return y
def fricas_desolve_system(des, dvars, ics, ivar): '\n Solve a system of first order ODEs using FriCAS.\n\n EXAMPLES::\n\n sage: t = var(\'t\')\n sage: x = function(\'x\')(t)\n sage: y = function(\'y\')(t)\n sage: de1 = diff(x,t) + y - 1 == 0\n sage: de2 = diff(y,t) - x + 1 == 0\n sage: desolve_system([de1, de2], [x, y], algorithm="fricas") # optional - fricas\n [x(t) == _C0*cos(t) + cos(t)^2 + _C1*sin(t) + sin(t)^2,\n y(t) == -_C1*cos(t) + _C0*sin(t) + 1]\n\n sage: desolve_system([de1, de2], [x,y], [0,1,2], algorithm="fricas") # optional - fricas\n [x(t) == cos(t)^2 + sin(t)^2 - sin(t), y(t) == cos(t) + 1]\n\n TESTS::\n\n sage: from sage.calculus.desolvers import fricas_desolve_system\n sage: t = var(\'t\')\n sage: x = function(\'x\')(t)\n sage: fricas_desolve_system([diff(x,t) + 1 == 0], [x], None, t) # optional - fricas\n [x(t) == _C0 - t]\n\n sage: y = function(\'y\')(t)\n sage: de1 = diff(x,t) + y - 1 == 0\n sage: de2 = diff(y,t) - x + 1 == 0\n sage: sol = fricas_desolve_system([de1,de2], [x,y], [0,1,-1], t) # optional - fricas\n sage: sol # optional - fricas\n [x(t) == cos(t)^2 + sin(t)^2 + 2*sin(t), y(t) == -2*cos(t) + 1]\n\n ' from sage.interfaces.fricas import fricas from sage.symbolic.ring import SR from sage.symbolic.relation import solve ops = [dvar.operator() for dvar in dvars] y = fricas(des).solve(ops, ivar).sage() basis = y['basis'] particular = y['particular'] pars = [SR.var(('_C' + str(i))) for i in range(len(basis))] solv = (particular + sum(((p * v) for (p, v) in zip(pars, basis)))) if (ics is None): sols = solv else: ics0 = ics[0] eqs = [(val == sol.subs({ivar: ics0})) for (val, sol) in zip(ics[1:], solv)] pars_values = solve(eqs, pars, solution_dict=True) sols = [sol.subs(pars_values[0]) for sol in solv] return [(dvar == sol) for (dvar, sol) in zip(dvars, sols)]
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False, algorithm='maxima'): '\n Solve a 1st or 2nd order linear ODE, including IVP and BVP.\n\n INPUT:\n\n - ``de`` -- an expression or equation representing the ODE\n\n - ``dvar`` -- the dependent variable (hereafter called `y`)\n\n - ``ics`` -- (optional) the initial or boundary conditions\n\n - for a first-order equation, specify the initial `x` and `y`\n\n - for a second-order equation, specify the initial `x`, `y`,\n and `dy/dx`, i.e. write `[x_0, y(x_0), y\'(x_0)]`\n\n - for a second-order boundary solution, specify initial and\n final `x` and `y` boundary conditions, i.e. write `[x_0, y(x_0), x_1, y(x_1)]`.\n\n - gives an error if the solution is not SymbolicEquation (as happens for\n example for a Clairaut equation)\n\n - ``ivar`` -- (optional) the independent variable (hereafter called\n `x`), which must be specified if there is more than one\n independent variable in the equation\n\n - ``show_method`` -- (optional) if ``True``, then Sage returns pair\n ``[solution, method]``, where method is the string describing\n the method which has been used to get a solution (Maxima uses the\n following order for first order equations: linear, separable,\n exact (including exact with integrating factor), homogeneous,\n bernoulli, generalized homogeneous) - use carefully in class,\n see below the example of an equation which is separable but\n this property is not recognized by Maxima and the equation is solved\n as exact.\n\n - ``contrib_ode`` -- (optional) if ``True``, ``desolve`` allows to solve\n Clairaut, Lagrange, Riccati and some other equations. This may take\n a long time and is thus turned off by default. Initial conditions\n can be used only if the result is one SymbolicEquation (does not\n contain a singular solution, for example).\n\n - ``algorithm`` -- (default: ``\'maxima\'``) one of\n\n * ``\'maxima\'`` - use maxima\n * ``\'fricas\'`` - use FriCAS (the optional fricas spkg has to be installed)\n\n OUTPUT:\n\n In most cases return a SymbolicEquation which defines the solution\n implicitly. If the result is in the form `y(x)=\\ldots` (happens for\n linear eqs.), return the right-hand side only. The possible\n constant solutions of separable ODEs are omitted.\n\n .. NOTE::\n\n Use ``desolve? <tab>`` if the output in the Sage notebook is truncated.\n\n EXAMPLES::\n\n sage: x = var(\'x\')\n sage: y = function(\'y\')(x)\n sage: desolve(diff(y,x) + y - 1, y)\n (_C + e^x)*e^(-x)\n\n ::\n\n sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f\n (e^10 + e^x)*e^(-x)\n\n ::\n\n sage: plot(f)\n Graphics object consisting of 1 graphics primitive\n\n We can also solve second-order differential equations::\n\n sage: x = var(\'x\')\n sage: y = function(\'y\')(x)\n sage: de = diff(y,x,2) - y == x\n sage: desolve(de, y)\n _K2*e^(-x) + _K1*e^x - x\n\n ::\n\n sage: f = desolve(de, y, [10,2,1]); f\n -x + 7*e^(x - 10) + 5*e^(-x + 10)\n\n ::\n\n sage: f(x=10)\n 2\n\n ::\n\n sage: diff(f,x)(x=10)\n 1\n\n ::\n\n sage: de = diff(y,x,2) + y == 0\n sage: desolve(de, y)\n _K2*cos(x) + _K1*sin(x)\n\n ::\n\n sage: desolve(de, y, [0,1,pi/2,4])\n cos(x) + 4*sin(x)\n\n ::\n\n sage: desolve(y*diff(y,x)+sin(x)==0,y)\n -1/2*y(x)^2 == _C - cos(x)\n\n Clairaut equation: general and singular solutions::\n\n sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True)\n [[y(x) == _C^2 + _C*x, y(x) == -1/4*x^2], \'clairau...\']\n\n For equations involving more variables we specify an independent variable::\n\n sage: a,b,c,n=var(\'a b c n\')\n sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True)\n [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]]\n\n ::\n\n 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)\n [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], \'riccati\']\n\n\n Higher order equations, not involving independent variable::\n\n sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand()\n 1/6*y(x)^3 + _K1*y(x) == _K2 + x\n\n ::\n\n sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand()\n 1/6*y(x)^3 - 5/3*y(x) == x - 3/2\n\n ::\n\n sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True)\n [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, \'freeofx\']\n\n Separable equations - Sage returns solution in implicit form::\n\n sage: desolve(diff(y,x)*sin(y) == cos(x),y)\n -cos(y(x)) == _C + sin(x)\n\n ::\n\n sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True)\n [-cos(y(x)) == _C + sin(x), \'separable\']\n\n ::\n\n sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1])\n -cos(y(x)) == -cos(1) + sin(x) - 1\n\n Linear equation - Sage returns the expression on the right hand side only::\n\n sage: desolve(diff(y,x)+(y) == cos(x),y)\n 1/2*((cos(x) + sin(x))*e^x + 2*_C)*e^(-x)\n\n ::\n\n sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True)\n [1/2*((cos(x) + sin(x))*e^x + 2*_C)*e^(-x), \'linear\']\n\n ::\n\n sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1])\n 1/2*(cos(x)*e^x + e^x*sin(x) + 1)*e^(-x)\n\n This ODE with separated variables is solved as\n exact. Explanation - factor does not split `e^{x-y}` in Maxima\n into `e^{x}e^{y}`::\n\n sage: desolve(diff(y,x)==exp(x-y),y,show_method=True)\n [-e^x + e^y(x) == _C, \'exact\']\n\n You can solve Bessel equations, also using initial\n conditions, but you cannot put (sometimes desired) the initial\n condition at `x=0`, since this point is a singular point of the\n equation. Anyway, if the solution should be bounded at `x=0`, then\n ``_K2=0``. ::\n\n sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y)\n _K1*bessel_J(2, x) + _K2*bessel_Y(2, x)\n\n Example of difficult ODE producing an error::\n\n sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested\n Traceback (click to the left for traceback)\n ...\n NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True."\n\n Another difficult ODE with error - moreover, it takes a long time::\n\n sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested\n\n Some more types of ODEs::\n\n sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True)\n [[y(x) == _C + log(x), y(x) == _C*e^x], \'factor\']\n\n ::\n\n sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True)\n [[[x == _C - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == _C + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], \'lagrange\']\n\n These two examples produce an error (as expected, Maxima 5.18 cannot\n solve equations from initial conditions). Maxima 5.18\n returns false answer in this case! ::\n\n sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested\n Traceback (click to the left for traceback)\n ...\n NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True."\n\n ::\n\n sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested\n Traceback (click to the left for traceback)\n ...\n NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True."\n\n Second order linear ODE::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y)\n (_K2*x + _K1)*e^(-x) + 1/2*sin(x)\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True)\n [(_K2*x + _K1)*e^(-x) + 1/2*sin(x), \'variationofparameters\']\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1])\n 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x)\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True)\n [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), \'variationofparameters\']\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2])\n 3*(x*(e^(1/2*pi) - 2)/pi + 1)*e^(-x) + 1/2*sin(x)\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True)\n [3*(x*(e^(1/2*pi) - 2)/pi + 1)*e^(-x) + 1/2*sin(x), \'variationofparameters\']\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y)\n (_K2*x + _K1)*e^(-x)\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True)\n [(_K2*x + _K1)*e^(-x), \'constcoeff\']\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1])\n (4*x + 3)*e^(-x)\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True)\n [(4*x + 3)*e^(-x), \'constcoeff\']\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2])\n (2*x*(2*e^(1/2*pi) - 3)/pi + 3)*e^(-x)\n\n ::\n\n sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True)\n [(2*x*(2*e^(1/2*pi) - 3)/pi + 3)*e^(-x), \'constcoeff\']\n\n Using ``algorithm=\'fricas\'`` we can invoke the differential\n equation solver from FriCAS. For example, it can solve higher\n order linear equations::\n\n sage: de = x^3*diff(y, x, 3) + x^2*diff(y, x, 2) - 2*x*diff(y, x) + 2*y - 2*x^4\n sage: Y = desolve(de, y, algorithm="fricas"); Y # optional - fricas\n (2*x^3 - 3*x^2 + 1)*_C0/x + (x^3 - 1)*_C1/x\n + (x^3 - 3*x^2 - 1)*_C2/x + 1/15*(x^5 - 10*x^3 + 20*x^2 + 4)/x\n\n The initial conditions are then interpreted as `[x_0, y(x_0),\n y\'(x_0), \\ldots, y^(n)(x_0)]`::\n\n sage: Y = desolve(de, y, ics=[1,3,7], algorithm="fricas"); Y # optional - fricas\n 1/15*(x^5 + 15*x^3 + 50*x^2 - 21)/x\n\n FriCAS can also solve some non-linear equations::\n\n sage: de = diff(y, x) == y / (x+y*log(y))\n sage: Y = desolve(de, y, algorithm="fricas"); Y # optional - fricas\n 1/2*(log(y(x))^2*y(x) - 2*x)/y(x)\n\n TESTS:\n\n :trac:`9961` fixed (allow assumptions on the dependent variable in desolve)::\n\n sage: y=function(\'y\')(x); assume(x>0); assume(y>0)\n sage: sage.calculus.calculus.maxima(\'domain:real\') # needed since Maxima 5.26.0 to get the answer as below\n real\n sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y == 0, y, contrib_ode=True)\n [x - arcsinh(y(x)/x) == _C]\n\n :trac:`10682` updated Maxima to 5.26, and it started to show a different\n solution in the complex domain for the ODE above::\n\n sage: forget()\n sage: sage.calculus.calculus.maxima(\'domain:complex\') # back to the default complex domain\n complex\n sage: assume(x>0)\n sage: assume(y>0)\n sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y == 0, y, contrib_ode=True)\n [x - arcsinh(y(x)^2/(x*sqrt(y(x)^2))) - arcsinh(y(x)/x) + 1/2*log(4*(x^2 + 2*y(x)^2 + 2*sqrt(x^2*y(x)^2 + y(x)^4))/x^2) == _C]\n\n :trac:`6479` fixed::\n\n sage: x = var(\'x\')\n sage: y = function(\'y\')(x)\n sage: desolve( diff(y,x,x) == 0, y, [0,0,1])\n x\n\n ::\n\n sage: desolve( diff(y,x,x) == 0, y, [0,1,1])\n x + 1\n\n :trac:`9835` fixed::\n\n sage: x = var(\'x\')\n sage: y = function(\'y\')(x)\n sage: desolve(diff(y,x,2)+y*(1-y^2)==0,y,[0,-1,1,1])\n Traceback (most recent call last):\n ...\n NotImplementedError: Unable to use initial condition for this equation (freeofx).\n\n :trac:`8931` fixed::\n\n sage: x=var(\'x\'); f=function(\'f\')(x); k=var(\'k\'); assume(k>0)\n sage: desolve(diff(f,x,2)/f==k,f,ivar=x)\n _K1*e^(sqrt(k)*x) + _K2*e^(-sqrt(k)*x)\n\n :trac:`15775` fixed::\n\n sage: forget()\n sage: y = function(\'y\')(x)\n sage: desolve(diff(y, x) == sqrt(abs(y)), dvar=y, ivar=x)\n integrate(1/sqrt(abs(y(x))), y(x)) == _C + x\n\n AUTHORS:\n\n - David Joyner (1-2006)\n - Robert Bradshaw (10-2008)\n - Robert Marik (10-2009)\n ' if (isinstance(de, Expression) and de.is_relational()): de = (de.lhs() - de.rhs()) if (isinstance(dvar, Expression) and dvar.is_symbol()): raise ValueError("You have to declare dependent variable as a function evaluated at the independent variable, eg. y=function('y')(x)") 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] if (algorithm == 'fricas'): return fricas_desolve(de, dvar, ics, ivar) elif (algorithm != 'maxima'): raise ValueError(('unknown algorithm %s' % algorithm)) de00 = de._maxima_() P = de00.parent() dvar_str = P(dvar.operator()).str() ivar_str = P(ivar).str() de00 = de00.str() def sanitize_var(exprs): return exprs.replace((((("'" + dvar_str) + '(') + ivar_str) + ')'), dvar_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)) soln = P(cmd) if (str(soln).strip() == 'false'): if contrib_ode: ode_solver = 'contrib_ode' P("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)) soln = P(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 = P('method') if (ics is not None): if (not (isinstance(soln.sage(), Expression) and soln.sage().is_relational())): if (not show_method): maxima_method = P('method') raise NotImplementedError(('Unable to use initial condition for this equation (%s).' % str(maxima_method).strip())) 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) soln = P(cmd) if (len(ics) == 3): P("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 = P((ivar == ics[0])).str() tempic += (',' + P((dvar == ics[1])).str()) tempic += (((((",'diff(" + dvar_str) + ',') + ivar_str) + ')=') + P(ics[2]).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) soln = P(cmd) if (str(soln).strip() == 'false'): raise NotImplementedError('Maxima was unable to solve this IVP. Remove the initial condition to get the general solution.') if (len(ics) == 4): P("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, P((ivar == ics[0])).str(), dvar_str, P(ics[1]).str(), P((ivar == ics[2])).str(), dvar_str, P(ics[3]).str())) cmd = ('(TEMP:%s,substitute(%s=%s(%s),TEMP))' % (cmd, dvar_str, dvar_str, ivar_str)) cmd = sanitize_var(cmd) soln = P(cmd) if (str(soln).strip() == 'false'): raise NotImplementedError('Maxima was unable to solve this BVP. Remove the initial condition to get the general solution.') soln = soln.sage() if (isinstance(soln, Expression) and soln.is_relational() and (soln.lhs() == dvar)): soln = soln.rhs() if show_method: return [soln, maxima_method.str()] return soln
def desolve_laplace(de, dvar, ics=None, ivar=None): "\n Solve an ODE using Laplace transforms. Initial conditions are optional.\n\n INPUT:\n\n - ``de`` - a lambda expression representing the ODE (e.g. ``de =\n diff(y,x,2) == diff(y,x)+sin(x)``)\n\n - ``dvar`` - the dependent variable (e.g. ``y``)\n\n - ``ivar`` - (optional) the independent variable (hereafter called\n `x`), which must be specified if there is more than one\n independent variable in the equation.\n\n - ``ics`` - a list of numbers representing initial conditions, (e.g.\n ``f(0)=1``, ``f'(0)=2`` corresponds to ``ics = [0,1,2]``)\n\n OUTPUT:\n\n Solution of the ODE as symbolic expression\n\n EXAMPLES::\n\n sage: u=function('u')(x)\n sage: eq = diff(u,x) - exp(-x) - u == 0\n sage: desolve_laplace(eq,u)\n 1/2*(2*u(0) + 1)*e^x - 1/2*e^(-x)\n\n We can use initial conditions::\n\n sage: desolve_laplace(eq,u,ics=[0,3])\n -1/2*e^(-x) + 7/2*e^x\n\n The initial conditions do not persist in the system (as they persisted\n in previous versions)::\n\n sage: desolve_laplace(eq,u)\n 1/2*(2*u(0) + 1)*e^x - 1/2*e^(-x)\n\n ::\n\n sage: f=function('f')(x)\n sage: eq = diff(f,x) + f == 0\n sage: desolve_laplace(eq,f,[0,1])\n e^(-x)\n\n ::\n\n sage: x = var('x')\n sage: f = function('f')(x)\n sage: de = diff(f,x,x) - 2*diff(f,x) + f\n sage: desolve_laplace(de,f)\n -x*e^x*f(0) + x*e^x*D[0](f)(0) + e^x*f(0)\n\n ::\n\n sage: desolve_laplace(de,f,ics=[0,1,2])\n x*e^x + e^x\n\n TESTS:\n\n Check that :trac:`4839` is fixed::\n\n sage: t = var('t')\n sage: x = function('x')(t)\n sage: soln = desolve_laplace(diff(x,t)+x==1, x, ics=[0,2])\n sage: soln\n e^(-t) + 1\n\n ::\n\n sage: soln(t=3)\n e^(-3) + 1\n\n AUTHORS:\n\n - David Joyner (1-2006,8-2007)\n\n - Robert Marik (10-2009)\n " if (isinstance(de, Expression) and de.is_relational()): de = (de.lhs() - de.rhs()) if (isinstance(dvar, Expression) and dvar.is_symbol()): raise ValueError("You have to declare dependent variable as a function evaluated at the independent variable, eg. y=function('y')(x)") 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] dvar_str = str(dvar) def sanitize_var(exprs): return exprs.replace(("'" + dvar_str), dvar_str) de0 = de._maxima_() P = de0.parent() i = dvar_str.find('(') dvar_str = ((dvar_str[:(i + 1)] + '_SAGE_VAR_') + dvar_str[(i + 1):]) cmd = sanitize_var((((('desolve(' + de0.str()) + ',') + dvar_str) + ')')) soln = P(cmd).rhs() if (str(soln).strip() == 'false'): raise NotImplementedError('Maxima was unable to solve this ODE.') soln = soln.sage() if (ics is not None): d = len(ics) for i in range((d - 1)): soln = eval((('soln.substitute(diff(dvar,ivar,i)(' + str(ivar)) + '=ics[0])==ics[i+1])')) return soln
def desolve_system(des, vars, ics=None, ivar=None, algorithm='maxima'): '\n Solve a system of any size of 1st order ODEs. Initial conditions\n are optional.\n\n One dimensional systems are passed to :meth:`desolve_laplace`.\n\n INPUT:\n\n - ``des`` -- list of ODEs\n\n - ``vars`` -- list of dependent variables\n\n - ``ics`` -- (optional) list of initial values for ``ivar`` and ``vars``;\n if ``ics`` is defined, it should provide initial conditions for each\n variable, otherwise an exception would be raised\n\n - ``ivar`` -- (optional) the independent variable, which must be\n specified if there is more than one independent variable in the\n equation\n\n - ``algorithm`` -- (default: ``\'maxima\'``) one of\n\n * ``\'maxima\'`` - use maxima\n * ``\'fricas\'`` - use FriCAS (the optional fricas spkg has to be installed)\n\n EXAMPLES::\n\n sage: t = var(\'t\')\n sage: x = function(\'x\')(t)\n sage: y = function(\'y\')(t)\n sage: de1 = diff(x,t) + y - 1 == 0\n sage: de2 = diff(y,t) - x + 1 == 0\n sage: desolve_system([de1, de2], [x,y])\n [x(t) == (x(0) - 1)*cos(t) - (y(0) - 1)*sin(t) + 1,\n y(t) == (y(0) - 1)*cos(t) + (x(0) - 1)*sin(t) + 1]\n\n The same system solved using FriCAS::\n\n sage: desolve_system([de1, de2], [x,y], algorithm=\'fricas\') # optional - fricas\n [x(t) == _C0*cos(t) + cos(t)^2 + _C1*sin(t) + sin(t)^2,\n y(t) == -_C1*cos(t) + _C0*sin(t) + 1]\n\n Now we give some initial conditions::\n\n sage: sol = desolve_system([de1, de2], [x,y], ics=[0,1,2]); sol\n [x(t) == -sin(t) + 1, y(t) == cos(t) + 1]\n\n ::\n\n sage: solnx, solny = sol[0].rhs(), sol[1].rhs()\n sage: plot([solnx,solny],(0,1)) # not tested\n sage: parametric_plot((solnx,solny),(0,1)) # not tested\n\n TESTS:\n\n Check that :trac:`9823` is fixed::\n\n sage: t = var(\'t\')\n sage: x = function(\'x\')(t)\n sage: de1 = diff(x,t) + 1 == 0\n sage: desolve_system([de1], [x])\n -t + x(0)\n\n Check that :trac:`16568` is fixed::\n\n sage: t = var(\'t\')\n sage: x = function(\'x\')(t)\n sage: y = function(\'y\')(t)\n sage: de1 = diff(x,t) + y - 1 == 0\n sage: de2 = diff(y,t) - x + 1 == 0\n sage: des = [de1,de2]\n sage: ics = [0,1,-1]\n sage: vars = [x,y]\n sage: sol = desolve_system(des, vars, ics); sol\n [x(t) == 2*sin(t) + 1, y(t) == -2*cos(t) + 1]\n\n ::\n\n sage: solx, soly = sol[0].rhs(), sol[1].rhs()\n sage: RR(solx(t=3))\n 1.28224001611973\n\n ::\n\n sage: P1 = plot([solx,soly], (0,1)) # needs sage.plot\n sage: P2 = parametric_plot((solx,soly), (0,1)) # needs sage.plot\n\n Now type ``show(P1)``, ``show(P2)`` to view these plots.\n\n Check that :trac:`9824` is fixed::\n\n sage: t = var(\'t\')\n sage: epsilon = var(\'epsilon\')\n sage: x1 = function(\'x1\')(t)\n sage: x2 = function(\'x2\')(t)\n sage: de1 = diff(x1,t) == epsilon\n sage: de2 = diff(x2,t) == -2\n sage: desolve_system([de1, de2], [x1, x2], ivar=t)\n [x1(t) == epsilon*t + x1(0), x2(t) == -2*t + x2(0)]\n sage: desolve_system([de1, de2], [x1, x2], ics=[1,1], ivar=t)\n Traceback (most recent call last):\n ...\n ValueError: Initial conditions aren\'t complete: number of vars is different\n from number of dependent variables. Got ics = [1, 1], vars = [x1(t), x2(t)]\n\n Check that :trac:`9825` is fixed::\n\n sage: t = var(\'t\')\n sage: x1, x2=function("x1, x2")\n sage: de1=x1(t).diff(t)==-3*(x2(t)-1)\n sage: de2=x2(t).diff(t)==1\n sage: Sol=desolve_system([de1, de2],[x1(t),x2(t)],ivar=t) ; Sol\n [x1(t) == -3/2*t^2 - 3*t*x2(0) + 3*t + x1(0), x2(t) == t + x2(0)]\n\n\n AUTHORS:\n\n - Robert Bradshaw (10-2008)\n - Sergey Bykov (10-2014)\n ' if (ics is not None): if (len(ics) != (len(vars) + 1)): raise ValueError("Initial conditions aren't complete: number of vars is different from number of dependent variables. Got ics = {0}, vars = {1}".format(ics, vars)) if ((len(des) == 1) and (algorithm == 'maxima')): return desolve_laplace(des[0], vars[0], ics=ics, ivar=ivar) ivars = set([]) for (i, de) in enumerate(des): if (not (isinstance(de, Expression) and de.is_relational())): des[i] = (de == 0) ivars = ivars.union(set(de.variables())) if (ivar is None): ivars = (ivars - set(vars)) if (len(ivars) != 1): raise ValueError('Unable to determine independent variable, please specify.') ivar = list(ivars)[0] if (algorithm == 'fricas'): return fricas_desolve_system(des, vars, ics, ivar) elif (algorithm != 'maxima'): raise ValueError(('unknown algorithm %s' % algorithm)) dvars = [v._maxima_() for v in vars] if (ics is not None): ivar_ic = ics[0] for (dvar, ic) in zip(dvars, ics[1:]): dvar.atvalue((ivar == ivar_ic), ic) soln = dvars[0].parent().desolve(des, dvars) if (str(soln).strip() == 'false'): raise NotImplementedError('Maxima was unable to solve this system.') soln = list(soln) for (i, sol) in enumerate(soln): soln[i] = sol.sage() if (ics is not None): ivar_ic = ics[0] for (dvar, ic) in zip(dvars, ics[:1]): dvar.atvalue((ivar == ivar_ic), dvar) return soln