Question: Ordinal arithmetic It would be nice if SymPy would have provided ordinal arithmetic. That would require either definining a new object called , that will either inherit from or from (option 1), or new assumption(s) that will allow the current symbols to be ordinals. How can it work with assumptions? Roughly as follows: and arithmetic should be defined: addition, multiplication and exponentiation (all are not commutative in general), and some other useful methods, such as: relationals supporting ordinals cantor normal form prime ordinals (perhaps also with the assumption) limits of sequences of ordinals cardinals (related to ) some "known" ordinals such as omega, omega_1, ..., epsilon numbers, etc. you can find a python implementation of non-symbolic ordinal arithmetic. I can be up to the task of defining a symbolic variation, but I don't think I can implement it in SymPy.

<ins>from sympy.core import Basic, Integerfrom sympy.core.compatibility import with_metaclassfrom sympy.core.singleton import Singleton, Simport operatorclass OmegaPower(Basic):    """    Represents ordinal exponential and multiplication terms one of the    building blocks of the Ordinal class.    In OmegaPower(a, b) a represents exponent and b represents multiplicity.    """    def __new__(cls, a, b):        if isinstance(b, int):            b = Integer(b)        if not isinstance(b, Integer) or b <= 0:            raise TypeError("multiplicity must be a positive integer")        if not isinstance(a, Ordinal):            a = Ordinal.convert(a)        return Basic.__new__(cls, a, b)    @property    def exp(self):        return self.args[0]    @property    def mult(self):        return self.args[1]    def _compare_term(self, other, op):        if self.exp == other.exp:            return op(self.mult, other.mult)        else:            return op(self.exp, other.exp)    def __eq__(self, other):        if not isinstance(other, OmegaPower):            try:                other = OmegaPower(0, other)            except TypeError:                return NotImplemented        return self.args == other.args    __hash__ = Basic.__hash__    def __lt__(self, other):        if not isinstance(other, OmegaPower):            try:                other = OmegaPower(0, other)            except TypeError:                return NotImplemented        return self._compare_term(other, operator.lt)class Ordinal(Basic):    """    Represents ordinals in Cantor normal form.    Internally, this class is just a list of instances of OmegaPower    Examples    ========    >>> from sympy.sets import Ordinal, ord0, OmegaPower    >>> from sympy.sets.ordinals import omega    >>> w = omega    >>> w.is_limit_ordinal    True    >>> Ordinal(OmegaPower(w + 1 ,1), OmegaPower(3, 2))    w**(w + 1) + w**3*2    >>> 3 + w    w    >>> (w + 1) * w    w**2    References    ==========    .. [1] https://en.wikipedia.org/wiki/Ordinal_arithmetic    """    def __new__(cls, *terms):        obj = super(Ordinal, cls).__new__(cls, *terms)        powers = [i.exp for i in obj.args]        if not all(powers[i] >= powers[i+1] for i in range(len(powers) - 1)):            raise ValueError("powers must be in decreasing order")        return obj    @property    def leading_term(self):        if self == ord0:            raise ValueError("ordinal zero has no leading term")        return self.args[0]    @property    def trailing_term(self):        if self == ord0:            raise ValueError("ordinal zero has no trailing term")        return self.args[-1]    @property    def is_successor_ordinal(self):        try:            return self.trailing_term.exp == ord0        except ValueError:            return False    @property    def is_limit_ordinal(self):        try:            return not self.trailing_term.exp == ord0        except ValueError:            return False    @property    def degree(self):        return self.leading_term.exp    @classmethod    def convert(cls, integer_value):        if integer_value == 0:            return ord0        return Ordinal(OmegaPower(0, integer_value))    def __eq__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        return self.args == other.args    def __hash__(self):        return hash(self.args)    def __lt__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        for term_self, term_other in zip(self.args, other.args):            if term_self != term_other:                return term_self < term_other        return len(self.args) < len(other.args)    def __le__(self, other):        return (self == other or self < other)    def __gt__(self, other):        return not self <= other    def __ge__(self, other):        return not self < other    def __str__(self):        net_str = ""        plus_count = 0        if self == ord0:            return 'ord0'        for i in self.args:            if plus_count:                net_str += " + "            if i.exp == ord0:                net_str += str(i.mult)            elif i.exp == 1:                net_str += 'w'            elif len(i.exp.args) > 1 or i.exp.is_limit_ordinal:                net_str += 'w**(%s)'%i.exp            else:                net_str += 'w**%s'%i.exp            if not i.mult == 1 and not i.exp == ord0:                net_str += '*%s'%i.mult            plus_count += 1        return(net_str)    __repr__ = __str__    def __add__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        if other == ord0:            return self        a_terms = list(self.args)        b_terms = list(other.args)        r = len(a_terms) - 1        b_exp = other.degree        while r >= 0 and a_terms[r].exp < b_exp:            r -= 1        if r < 0:            terms = b_terms        elif a_terms[r].exp == b_exp:            sum_term = OmegaPower(b_exp, a_terms[r].mult + other.leading_term.mult)            terms = a_terms[:r] + [sum_term] + b_terms[1:]        else:            terms = a_terms[:r+1] + b_terms        return Ordinal(*terms)    def __radd__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        return other + self    def __mul__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        if ord0 in (self, other):            return ord0        a_exp = self.degree        a_mult = self.leading_term.mult        sum = []        if other.is_limit_ordinal:            for arg in other.args:                sum.append(OmegaPower(a_exp + arg.exp, arg.mult))        else:            for arg in other.args[:-1]:                sum.append(OmegaPower(a_exp + arg.exp, arg.mult))            b_mult = other.trailing_term.mult            sum.append(OmegaPower(a_exp, a_mult*b_mult))            sum += list(self.args[1:])        return Ordinal(*sum)    def __rmul__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        return other * self    def __pow__(self, other):        if not self == omega:            return NotImplemented        return Ordinal(OmegaPower(other, 1))class OrdinalZero(with_metaclass(Singleton, Ordinal)):    """The ordinal zero.    OrdinalZero is a singleton, and can be accessed by ``S.OrdinalZero``    or can be imported as ``ord0``.    Examples    ========    >>> from sympy import ord0, S    >>> ord0 is S.OrdinalZero    True    """    passclass OrdinalOmega(with_metaclass(Singleton, Ordinal)):    """The ordinal omega which forms the base of all ordinals in cantor normal form.    OrdinalOmega is a singleton, and can be accessed by ``S.OrdinalOmega``    or can be imported as ``omega``.    Examples    ========    >>> from sympy.sets.ordinals import omega    >>> from sympy import S    >>> omega is S.OrdinalOmega    True    """    def __new__(cls):        return Ordinal.__new__(cls, OmegaPower(1, 1))ord0 = S.OrdinalZeroomega = S.OrdinalOmega</ins>


Question: coset_table doctest failure (Fatal Python error: Cannot recover from stack overflow.) See https://travis- Here is the test header

def zero_mul_simp(l, index):     """Used to combine two reduced words."""    while index >=0 and index < len(l) - 1 and l[index][0] is l[index + 1][0]:    while index >=0 and index < len(l) - 1 and l[index][0] == l[index + 1][0]:         exp = l[index][1] + l[index + 1][1]         base = l[index][0]         l[index] = (base, exp)diff --git a/sympy/combinatorics/rewritingsystem.py b/sympy/combinatorics/rewritingsystem.py-- a/sympy/combinatorics/rewritingsystem.py++ b/sympy/combinatorics/rewritingsystem.py


Question: coset_table doctest failure (Fatal Python error: Cannot recover from stack overflow.) See https://travis- Here is the test header

s1 = s1.subword(0, len(s1)-1)             s2 = s2*g**-1             if len(s1) - len(s2) < 0:<del>                #print("this", len(s1)-len(s2))</del>                 if s2 not in self.rules:                     if not check:                         self._add_rule(s2, s1)


Question: Multiplying an expression by a Poly does not evaluate when the expression is on the left side of the multiplication Tested in Python 3.4 64-bit and 3.6 64-bit Version: 1.1.2.dev0

is_commutative = True     is_Poly = True<ins>    _op_priority = 10.001</ins>      def __new__(cls, rep, *gens, **args):         """Create a new polynomial instance out of something useful. """


Question: Cannot simplify x + csch(sinc(1)) from sympy import * x = Symbol('x') print(simplify(x + csch(sinc(1)))) ... File "C:\Users\E\Desktop\sympy-master\sympy\simplify\", line 433, in f rv = fmap KeyError: sinc (I should have said: cannot apply the simplification function, since I'm not expecting any simplification to actually take place).

bernoulli(2*k)*x**(2*k - 1)/factorial(2*k))  class sinc(TrigonometricFunction):class sinc(Function):     r"""Represents unnormalized sinc function      Examples


Question: fix the dimension mismatches when using (dot) the dimension mismatched when using A.dot(B) where A is matrix B is 1 x m or n x 1 matrix before fixing it, if we used B as m x n matrix where n or m != 1 it gives a strange answer, but after fixing it raises error if m or n not equal 1

from sympy.core.compatibility import (is_sequence, default_sort_key, range,     NotIterable) <ins>from sympy.utilities.exceptions import SymPyDeprecationWarning</ins>  from types import FunctionType


Question: fix the dimension mismatches when using (dot) the dimension mismatched when using A.dot(B) where A is matrix B is 1 x m or n x 1 matrix before fixing it, if we used B as m x n matrix where n or m != 1 it gives a strange answer, but after fixing it raises error if m or n not equal 1

# https://github.com/sympy/sympy/pull/12854 class MatrixDeprecated(MatrixCommon):     """A class to house deprecated matrix methods."""<ins>    def _legacy_array_dot(self, b):        """Compatibility function for deprecated behavior of ``matrix.dot(vector)``        """        from .dense import Matrix        if not isinstance(b, MatrixBase):            if is_sequence(b):                if len(b) != self.cols and len(b) != self.rows:                    raise ShapeError(                        "Dimensions incorrect for dot product: %s, %s" % (                            self.shape, len(b)))                return self.dot(Matrix(b))            else:                raise TypeError(                    "`b` must be an ordered iterable or Matrix, not %s." %                    type(b))        mat = self        if mat.cols == b.rows:            if b.cols != 1:                mat = mat.T                b = b.T            prod = flatten((mat * b).tolist())            return prod        if mat.cols == b.cols:            return mat.dot(b.T)        elif mat.rows == b.rows:            return mat.T.dot(b)        else:            raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (                self.shape, b.shape))</ins>      def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify):         return self.charpoly(x=x)


Question: fix the dimension mismatches when using (dot) the dimension mismatched when using A.dot(B) where A is matrix B is 1 x m or n x 1 matrix before fixing it, if we used B as m x n matrix where n or m != 1 it gives a strange answer, but after fixing it raises error if m or n not equal 1

return self._diagonal_solve(rhs)      def dot(self, b):        """Return the dot product of Matrix self and b relaxing the condition        of compatible dimensions: if either the number of rows or columns are        the same as the length of b then the dot product is returned. If self        is a row or column vector, a scalar is returned. Otherwise, a list        of results is returned (and in that case the number of columns in self        must match the length of b).        """Return the dot product of two vectors of equal length. ``self`` must        be a ``Matrix`` of size 1 x n or n x 1, and ``b`` must be either a        matrix of size 1 x n, n x 1, or a list/tuple of length n. A scalar is returned.          Examples         ========          >>> from sympy import Matrix         >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])        >>> v = [1, 1, 1]        >>> v = Matrix([1, 1, 1])         >>> M.row(0).dot(v)         6         >>> M.col(0).dot(v)         12        >>> M.dot(v)        [6, 15, 24]        >>> v = [3, 2, 1]        >>> M.row(0).dot(v)        10          See Also         ========


Question: fix the dimension mismatches when using (dot) the dimension mismatched when using A.dot(B) where A is matrix B is 1 x m or n x 1 matrix before fixing it, if we used B as m x n matrix where n or m != 1 it gives a strange answer, but after fixing it raises error if m or n not equal 1

type(b))          mat = self        if mat.cols == b.rows:            if b.cols != 1:                mat = mat.T                b = b.T            prod = flatten((mat * b).tolist())            if len(prod) == 1:                return prod[0]            return prod        if mat.cols == b.cols:            return mat.dot(b.T)        elif mat.rows == b.rows:            return mat.T.dot(b)        else:            raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (                self.shape, b.shape))        if (1 not in mat.shape) or (1 not in b.shape) :            SymPyDeprecationWarning(                feature="Dot product of non row/column vectors",                issue=13815,                deprecated_since_version="1.2").warn()            return mat._legacy_array_dot(b)        if len(mat) != len(b):            raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (self.shape, b.shape))        n = len(mat)        if mat.shape != (1, n):            mat = mat.reshape(1, n)        if b.shape != (n, 1):            b = b.reshape(n, 1)        # Now ``mat`` is a row vector and ``b`` is a column vector.        return (mat * b)[0]      def dual(self):         """Returns the dual of a matrix, which is:


Question: @ (matmul) should fail if one argument is not a matrix Right now () just copies , but it should actually only work if the multiplication is actually a matrix multiplication. This is also how NumPy works

@call_highest_priority('__rmatmul__')     def __matmul__(self, other):<ins>        other = _matrixify(other)        if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):            return NotImplemented</ins>         return self.__mul__(other)      @call_highest_priority('__rmul__')


Question: @ (matmul) should fail if one argument is not a matrix Right now () just copies , but it should actually only work if the multiplication is actually a matrix multiplication. This is also how NumPy works

@call_highest_priority('__matmul__')     def __rmatmul__(self, other):<ins>        other = _matrixify(other)        if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):            return NotImplemented</ins>         return self.__rmul__(other)      @call_highest_priority('__mul__')


Question: latex() and mulsymbol The pretty-printing function accepts a kwarg that must be one of four choices. I would like to be able to supply my own choice which is not in the list. Specifically, I want the multiplication symbol to be (i.e., a thin space). This is what I mean Thin spaces are used by sympy to separate differentials from integrands in integrals. Is there a reason why the user cannot supply the of their choosing? Or are the 4 choices a historical artifact? I'm willing to attempt making a PR to allow to be arbitrary (and backwards-compatible) if such a PR would be considered.

"dot": r" \cdot ",             "times": r" \times "         }        self._settings['mul_symbol_latex'] = \            mul_symbol_table[self._settings['mul_symbol']]        self._settings['mul_symbol_latex_numbers'] = \            mul_symbol_table[self._settings['mul_symbol'] or 'dot']        try:            self._settings['mul_symbol_latex'] = \                mul_symbol_table[self._settings['mul_symbol']]        except KeyError:            self._settings['mul_symbol_latex'] = \                self._settings['mul_symbol']        try:            self._settings['mul_symbol_latex_numbers'] = \                mul_symbol_table[self._settings['mul_symbol'] or 'dot']        except KeyError:            if (self._settings['mul_symbol'].strip() in                    ['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']):                self._settings['mul_symbol_latex_numbers'] = \                    mul_symbol_table['dot']            else:                self._settings['mul_symbol_latex_numbers'] = \                    self._settings['mul_symbol']          self._delim_dict = {'(': ')', '[': ']'}


Question: No support for [{90^^\circ }] I have latex [{90^^\circ }], which means angle ninety degree, for example (cos(90 degree)) = 0, please add support for that? I appreate your reply.

def _print_Mul(self, expr):         from sympy.core.power import Pow<ins>        from sympy.physics.units import Quantity</ins>         include_parens = False         if _coeff_isneg(expr):             expr = -expr


Question: No support for [{90^^\circ }] I have latex [{90^^\circ }], which means angle ninety degree, for example (cos(90 degree)) = 0, please add support for that? I appreate your reply.

if self.order not in ('old', 'none'):                     args = expr.as_ordered_factors()                 else:                    args = expr.args                    args = list(expr.args)                # If quantities are present append them at the back                args = sorted(args, key=lambda x: isinstance(x, Quantity) or                             (isinstance(x, Pow) and isinstance(x.base, Quantity)))                  for i, term in enumerate(args):                     term_tex = self._print(term)


Question: No support for [{90^^\circ }] I have latex [{90^^\circ }], which means angle ninety degree, for example (cos(90 degree)) = 0, please add support for that? I appreate your reply.

self._print(exp))         return r'\Omega\left(%s\right)' % self._print(expr.args[0])     def _print_Quantity(self, expr):        if expr.name.name == 'degree':            return r"^\circ"        return r"%s" % expr  def translate(s):     r'''diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py


Question: No support for [{90^^\circ }] I have latex [{90^^\circ }], which means angle ninety degree, for example (cos(90 degree)) = 0, please add support for that? I appreate your reply.

return prettyForm.__add__(*pforms)      def _print_Mul(self, product):        from sympy.physics.units import Quantity         a = []  # items in the numerator         b = []  # items that are in the denominator (if any)          if self.order not in ('old', 'none'):             args = product.as_ordered_factors()         else:            args = product.args            args = list(product.args)        # If quantities are present append them at the back        args = sorted(args, key=lambda x: isinstance(x, Quantity) or                     (isinstance(x, Pow) and isinstance(x.base, Quantity)))          # Gather terms for numerator/denominator         for item in args:


Question: No support for [{90^^\circ }] I have latex [{90^^\circ }], which means angle ninety degree, for example (cos(90 degree)) = 0, please add support for that? I appreate your reply.

pform = prettyForm(*pform.left('Omega'))         return pform     def _print_Quantity(self, e):        if e.name.name == 'degree':            pform = self._print(u"\N{DEGREE SIGN}")            return pform        else:            return self.emptyPrinter(e)  def pretty(expr, **settings):     """Returns a string containing the prettified form of expr.diff --git a/sympy/printing/pretty/stringpict.py b/sympy/printing/pretty/stringpict.py-- a/sympy/printing/pretty/stringpict.py++ b/sympy/printing/pretty/stringpict.py


Question: No support for [{90^^\circ }] I have latex [{90^^\circ }], which means angle ninety degree, for example (cos(90 degree)) = 0, please add support for that? I appreate your reply.

"""Make a pretty multiplication.         Parentheses are needed around +, - and neg.         """        quantity = {            'degree': u"\N{DEGREE SIGN}"        }         if len(others) == 0:             return self # We aren't actually multiplying... So nothing to do here.         args = self         if args.binding > prettyForm.MUL:             arg = stringPict(*args.parens())         result = [args]         for arg in others:            result.append(xsym('*'))            if arg.picture[0] not in quantity.values():                result.append(xsym('*'))             #add parentheses for weak binders             if arg.binding > prettyForm.MUL:                 arg = stringPict(*arg.parens())


Question: integrate(1/(2-cos(theta)),(theta,0,pi)) Sympy produces NaN. Actually for integrate(1/(a-cos(theta)),(theta,0,pi)) for a 1 should be pi/sqrt((a-1)*(a+1)). So, the right answer should be pi/sqrt(3). However sympy seems to use the subtitution like t = tan(x/2) which is infinite when x = pi. When I try integrate(1/(2-cos(theta)),theta) , I get "sqrt(3)I(-log(tan(x/2) - sqrt(3)I/3) + log(tan(x/2) + sqrt(3)I/3))/3". Simplify() or trigsimp() doesn't work. And I don't understand why imaginary number appears.

from sympy.core.expr import Expr from sympy.core.function import diff from sympy.core.mul import Mulfrom sympy.core.numbers import oofrom sympy.core.numbers import oo, pi from sympy.core.relational import Eq, Ne from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild)


Question: integrate(1/(2-cos(theta)),(theta,0,pi)) Sympy produces NaN. Actually for integrate(1/(a-cos(theta)),(theta,0,pi)) for a 1 should be pi/sqrt((a-1)*(a+1)). So, the right answer should be pi/sqrt(3). However sympy seems to use the subtitution like t = tan(x/2) which is infinite when x = pi. When I try integrate(1/(2-cos(theta)),theta) , I get "sqrt(3)I(-log(tan(x/2) - sqrt(3)I/3) + log(tan(x/2) + sqrt(3)I/3))/3". Simplify() or trigsimp() doesn't work. And I don't understand why imaginary number appears.

from sympy.matrices import MatrixBase from sympy.utilities.misc import filldedent from sympy.polys import Poly, PolynomialErrorfrom sympy.functions import Piecewise, sqrt, sign, piecewise_foldfrom sympy.functions.elementary.complexes import Abs, signfrom sympy.functions import Piecewise, sqrt, sign, piecewise_fold, tan, cot, atan from sympy.functions.elementary.exponential import logfrom sympy.functions.elementary.integers import floorfrom sympy.functions.elementary.complexes import Abs, sign from sympy.functions.elementary.miscellaneous import Min, Max from sympy.series import limit from sympy.series.order import Order


Question: integrate(1/(2-cos(theta)),(theta,0,pi)) Sympy produces NaN. Actually for integrate(1/(a-cos(theta)),(theta,0,pi)) for a 1 should be pi/sqrt((a-1)*(a+1)). So, the right answer should be pi/sqrt(3). However sympy seems to use the subtitution like t = tan(x/2) which is infinite when x = pi. When I try integrate(1/(2-cos(theta)),theta) , I get "sqrt(3)I(-log(tan(x/2) - sqrt(3)I/3) + log(tan(x/2) + sqrt(3)I/3))/3". Simplify() or trigsimp() doesn't work. And I don't understand why imaginary number appears.

function = ret                             continue <ins>            if not isinstance(antideriv, Integral) and antideriv is not None:                sym = xab[0]                for atan_term in antideriv.atoms(atan):                    atan_arg = atan_term.args[0]                    # Checking `atan_arg` to be linear combination of `tan` or `cot`                    for tan_part in atan_arg.atoms(tan):                        x1 = Dummy('x1')                        tan_exp1 = atan_arg.subs(tan_part, x1)                        # The coefficient of `tan` should be constant                        coeff = tan_exp1.diff(x1)                        if x1 not in coeff.free_symbols:                            a = tan_part.args[0]                            antideriv = antideriv.subs(atan_term, Add(atan_term,                                sign(coeff)*pi*floor((a-pi/2)/pi)))                    for cot_part in atan_arg.atoms(cot):                        x1 = Dummy('x1')                        cot_exp1 = atan_arg.subs(cot_part, x1)                        # The coefficient of `cot` should be constant                        coeff = cot_exp1.diff(x1)                        if x1 not in coeff.free_symbols:                            a = cot_part.args[0]                            antideriv = antideriv.subs(atan_term, Add(atan_term,                                sign(coeff)*pi*floor((a)/pi)))</ins>             if antideriv is None:                 undone_limits.append(xab)                 function = self.func(*([function] + [xab])).factor()


Question: Max & Min converting using SymPy Why many languages likes js and R cannot be converted from Max & Min? !

known_functions = {     #"Abs": [(lambda x: not x.is_integer, "fabs")],     "Abs": "abs",<del>    "gamma": "gamma",</del>     "sin": "sin",     "cos": "cos",     "tan": "tan",


Question: Max & Min converting using SymPy Why many languages likes js and R cannot be converted from Max & Min? !

"floor": "floor",     "ceiling": "ceiling",     "sign": "sign",<ins>    "Max": "max",    "Min": "min",    "factorial": "factorial",    "gamma": "gamma",    "digamma": "digamma",    "trigamma": "trigamma",    "beta": "beta",</ins> }  # These are the core reserved words in the R language. Taken from:


Question: Add evaluation for polylog Original issue for : Original author: Why does the expansion of polylog(1, z) have exppolar(-Ipi)? I don't see a reason for exppolar here: To my understanding, and are exactly the same function for all purposes. They agree for <1 by their power series definition. Both are branched at 1 in the same way. The mpmath evaluation implements their branch cuts consistently: when z is real and greater than 1, the imaginary part of both functions is -pi. I tested the evaluation at thousands of random points, real and complex: both return the same values. SymPy also agrees they have the same derivative, which is z/(1-z): But with the current implementation of , it would seem that expandfunc changes the derivative of the function: returns which doesn't simplify to 0. In general, I think that having exppolar in expressions like is just not meaningful. The additional information contained in "polar" is the winding number of some path about 0. Here, because of + 1, this ends up being the winding number about 1, which is irrelevant because log is not branched at 1.

""" Riemann zeta and related function. """ from __future__ import print_function, division from sympy.core import Function, S, sympify, pifrom sympy.core import Function, S, sympify, pi, I from sympy.core.function import ArgumentIndexError from sympy.core.compatibility import range from sympy.functions.combinatorial.numbers import bernoulli, factorial, harmonic from sympy.functions.elementary.exponential import logfrom sympy.functions.elementary.miscellaneous import sqrt  ############################################################################### ###################### LERCH TRANSCENDENT #####################################


Question: Add evaluation for polylog Original issue for : Original author: Why does the expansion of polylog(1, z) have exppolar(-Ipi)? I don't see a reason for exppolar here: To my understanding, and are exactly the same function for all purposes. They agree for <1 by their power series definition. Both are branched at 1 in the same way. The mpmath evaluation implements their branch cuts consistently: when z is real and greater than 1, the imaginary part of both functions is -pi. I tested the evaluation at thousands of random points, real and complex: both return the same values. SymPy also agrees they have the same derivative, which is z/(1-z): But with the current implementation of , it would seem that expandfunc changes the derivative of the function: returns which doesn't simplify to 0. In general, I think that having exppolar in expressions like is just not meaningful. The additional information contained in "polar" is the winding number of some path about 0. Here, because of + 1, this ends up being the winding number about 1, which is irrelevant because log is not branched at 1.

>>> from sympy import expand_func     >>> from sympy.abc import z     >>> expand_func(polylog(1, z))    -log(z*exp_polar(-I*pi) + 1)    -log(-z + 1)     >>> expand_func(polylog(0, z))     z/(-z + 1)


Question: Add evaluation for polylog Original issue for : Original author: Why does the expansion of polylog(1, z) have exppolar(-Ipi)? I don't see a reason for exppolar here: To my understanding, and are exactly the same function for all purposes. They agree for <1 by their power series definition. Both are branched at 1 in the same way. The mpmath evaluation implements their branch cuts consistently: when z is real and greater than 1, the imaginary part of both functions is -pi. I tested the evaluation at thousands of random points, real and complex: both return the same values. SymPy also agrees they have the same derivative, which is z/(1-z): But with the current implementation of , it would seem that expandfunc changes the derivative of the function: returns which doesn't simplify to 0. In general, I think that having exppolar in expressions like is just not meaningful. The additional information contained in "polar" is the winding number of some path about 0. Here, because of + 1, this ends up being the winding number about 1, which is irrelevant because log is not branched at 1.

elif z == -1:             return -dirichlet_eta(s)         elif z == 0:            return 0            return S.Zero        elif s == 2:            if z == S.Half:                return pi**2/12 - log(2)**2/2            elif z == 2:                return pi**2/4 - I*pi*log(2)            elif z == -(sqrt(5) - 1)/2:                return -pi**2/15 + log((sqrt(5)-1)/2)**2/2            elif z == -(sqrt(5) + 1)/2:                return -pi**2/10 - log((sqrt(5)+1)/2)**2            elif z == (3 - sqrt(5))/2:                return pi**2/15 - log((sqrt(5)-1)/2)**2            elif z == (sqrt(5) - 1)/2:                return pi**2/10 - log((sqrt(5)-1)/2)**2        # For s = 0 or -1 use explicit formulas to evaluate, but        # automatically expanding polylog(1, z) to -log(1-z) seems undesirable        # for summation methods based on hypergeometric functions        elif s == 0:            return z/(1 - z)        elif s == -1:            return z/(1 - z)**2      def fdiff(self, argindex=1):         s, z = self.args


Question: Add evaluation for polylog Original issue for : Original author: Why does the expansion of polylog(1, z) have exppolar(-Ipi)? I don't see a reason for exppolar here: To my understanding, and are exactly the same function for all purposes. They agree for <1 by their power series definition. Both are branched at 1 in the same way. The mpmath evaluation implements their branch cuts consistently: when z is real and greater than 1, the imaginary part of both functions is -pi. I tested the evaluation at thousands of random points, real and complex: both return the same values. SymPy also agrees they have the same derivative, which is z/(1-z): But with the current implementation of , it would seem that expandfunc changes the derivative of the function: returns which doesn't simplify to 0. In general, I think that having exppolar in expressions like is just not meaningful. The additional information contained in "polar" is the winding number of some path about 0. Here, because of + 1, this ends up being the winding number about 1, which is irrelevant because log is not branched at 1.

from sympy import log, expand_mul, Dummy, exp_polar, I         s, z = self.args         if s == 1:            return -log(1 + exp_polar(-I*pi)*z)            return -log(1 - z)         if s.is_Integer and s <= 0:             u = Dummy('u')             start = u/(1 - u)


Question: ODE incorrectly classified as Bernoulli A bug reported on returns . This is clearly due to only excluding f(x); it should also exclude x and dx.

d = Wild('d', exclude=[df, f(x).diff(x, 2)])     e = Wild('e', exclude=[df])     k = Wild('k', exclude=[df])    n = Wild('n', exclude=[f(x)])    n = Wild('n', exclude=[x, f(x), df])     c1 = Wild('c1', exclude=[x])     a2 = Wild('a2', exclude=[x, f(x), df])     b2 = Wild('b2', exclude=[x, f(x), df])


Question: Matrix determinant raises Invalid NaN comparison with particular symbolic entries from sympy import from import a f = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) f(1) 0 f(2) -a f(3) 2a(a + 2) + 2a(2a + 1) - 3a(2a + 2) f(4) 0 f(5) nan f(6) Traceback (most recent call last): File "<pyshell", line 1, in <modulef(6) File "<pyshell", line 1, in <lambdaf = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 53, in det return Determinant(matexpr).doit() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 37, in doit return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 270, in evaldeterminant return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 416, in det return self.evaldetbareiss() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 213, in evaldetbareiss return cancel(bareiss(self)) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) [Previous line repeated 1 more times] File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 55, in new rows, cols, flatlist = cls.handlecreationinputs(args, kwargs) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in handlecreationinputs for j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in <listcompfor j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 208, in entry cancel(ret) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\polys\", line 6423, in cancel f = factorterms(f, radical=True) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1193, in factorterms return do(expr) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in do [do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in <listcomp*[do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in do if all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in <genexprif all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 323, in lt raise TypeError("Invalid NaN comparison") TypeError: Invalid NaN comparison Correct me if I'm wrong but isn't the Bareiss algorithm only valid for integer matrices, which cannot be assumed here?

from sympy.core.add import Add from sympy.core.basic import Basic, Atom from sympy.core.expr import Expr<ins>from sympy.core.function import expand_mul</ins> from sympy.core.power import Pow from sympy.core.symbol import (Symbol, Dummy, symbols,     _uniquely_named_symbol)


Question: Matrix determinant raises Invalid NaN comparison with particular symbolic entries from sympy import from import a f = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) f(1) 0 f(2) -a f(3) 2a(a + 2) + 2a(2a + 1) - 3a(2a + 2) f(4) 0 f(5) nan f(6) Traceback (most recent call last): File "<pyshell", line 1, in <modulef(6) File "<pyshell", line 1, in <lambdaf = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 53, in det return Determinant(matexpr).doit() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 37, in doit return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 270, in evaldeterminant return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 416, in det return self.evaldetbareiss() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 213, in evaldetbareiss return cancel(bareiss(self)) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) [Previous line repeated 1 more times] File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 55, in new rows, cols, flatlist = cls.handlecreationinputs(args, kwargs) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in handlecreationinputs for j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in <listcompfor j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 208, in entry cancel(ret) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\polys\", line 6423, in cancel f = factorterms(f, radical=True) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1193, in factorterms return do(expr) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in do [do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in <listcomp*[do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in do if all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in <genexprif all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 323, in lt raise TypeError("Invalid NaN comparison") TypeError: Invalid NaN comparison Correct me if I'm wrong but isn't the Bareiss algorithm only valid for integer matrices, which cannot be assumed here?

from sympy.utilities.iterables import flatten, numbered_symbols from sympy.core.decorators import call_highest_priorityfrom sympy.core.compatibility import is_sequence, default_sort_key, range, \    NotIterablefrom sympy.core.compatibility import (is_sequence, default_sort_key, range,    NotIterable)   from types import FunctionType


Question: Matrix determinant raises Invalid NaN comparison with particular symbolic entries from sympy import from import a f = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) f(1) 0 f(2) -a f(3) 2a(a + 2) + 2a(2a + 1) - 3a(2a + 2) f(4) 0 f(5) nan f(6) Traceback (most recent call last): File "<pyshell", line 1, in <modulef(6) File "<pyshell", line 1, in <lambdaf = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 53, in det return Determinant(matexpr).doit() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 37, in doit return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 270, in evaldeterminant return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 416, in det return self.evaldetbareiss() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 213, in evaldetbareiss return cancel(bareiss(self)) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) [Previous line repeated 1 more times] File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 55, in new rows, cols, flatlist = cls.handlecreationinputs(args, kwargs) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in handlecreationinputs for j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in <listcompfor j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 208, in entry cancel(ret) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\polys\", line 6423, in cancel f = factorterms(f, radical=True) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1193, in factorterms return do(expr) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in do [do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in <listcomp*[do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in do if all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in <genexprif all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 323, in lt raise TypeError("Invalid NaN comparison") TypeError: Invalid NaN comparison Correct me if I'm wrong but isn't the Bareiss algorithm only valid for integer matrices, which cannot be assumed here?

return None  <ins>def _is_zero_after_expand_mul(x):    """Tests by expand_mul only, suitable for polynomials and rational    functions."""    return expand_mul(x) == 0</ins> class DeferredVector(Symbol, NotIterable):     """A vector whose components are deferred (e.g. for use with lambdify)


Question: Matrix determinant raises Invalid NaN comparison with particular symbolic entries from sympy import from import a f = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) f(1) 0 f(2) -a f(3) 2a(a + 2) + 2a(2a + 1) - 3a(2a + 2) f(4) 0 f(5) nan f(6) Traceback (most recent call last): File "<pyshell", line 1, in <modulef(6) File "<pyshell", line 1, in <lambdaf = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 53, in det return Determinant(matexpr).doit() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 37, in doit return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 270, in evaldeterminant return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 416, in det return self.evaldetbareiss() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 213, in evaldetbareiss return cancel(bareiss(self)) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) [Previous line repeated 1 more times] File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 55, in new rows, cols, flatlist = cls.handlecreationinputs(args, kwargs) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in handlecreationinputs for j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in <listcompfor j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 208, in entry cancel(ret) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\polys\", line 6423, in cancel f = factorterms(f, radical=True) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1193, in factorterms return do(expr) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in do [do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in <listcomp*[do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in do if all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in <genexprif all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 323, in lt raise TypeError("Invalid NaN comparison") TypeError: Invalid NaN comparison Correct me if I'm wrong but isn't the Bareiss algorithm only valid for integer matrices, which cannot be assumed here?

http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.         """ <del>        # XXX included as a workaround for issue #12362.  Should use `_find_reasonable_pivot` instead        def _find_pivot(l):            for pos,val in enumerate(l):                if val:                    return (pos, val, None, None)            return (None, None, None, None)</del>         # Recursively implemented Bareiss' algorithm as per Deanna Richelle Leggett's         # thesis http://www.math.usm.edu/perry/Research/Thesis_DRL.pdf         def bareiss(mat, cumm=1):


Question: Matrix determinant raises Invalid NaN comparison with particular symbolic entries from sympy import from import a f = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) f(1) 0 f(2) -a f(3) 2a(a + 2) + 2a(2a + 1) - 3a(2a + 2) f(4) 0 f(5) nan f(6) Traceback (most recent call last): File "<pyshell", line 1, in <modulef(6) File "<pyshell", line 1, in <lambdaf = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 53, in det return Determinant(matexpr).doit() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 37, in doit return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 270, in evaldeterminant return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 416, in det return self.evaldetbareiss() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 213, in evaldetbareiss return cancel(bareiss(self)) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) [Previous line repeated 1 more times] File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 55, in new rows, cols, flatlist = cls.handlecreationinputs(args, kwargs) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in handlecreationinputs for j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in <listcompfor j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 208, in entry cancel(ret) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\polys\", line 6423, in cancel f = factorterms(f, radical=True) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1193, in factorterms return do(expr) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in do [do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in <listcomp*[do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in do if all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in <genexprif all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 323, in lt raise TypeError("Invalid NaN comparison") TypeError: Invalid NaN comparison Correct me if I'm wrong but isn't the Bareiss algorithm only valid for integer matrices, which cannot be assumed here?

return mat[0, 0]              # find a pivot and extract the remaining matrix            # XXX should use `_find_reasonable_pivot`.  Blocked by issue #12362            pivot_pos, pivot_val, _, _ = _find_pivot(mat[:, 0])            # With the default iszerofunc, _find_reasonable_pivot slows down            # the computation by the factor of 2.5 in one test.            # Relevant issues: #10279 and #13877.            pivot_pos, pivot_val, _, _ = _find_reasonable_pivot(mat[:, 0],                                         iszerofunc=_is_zero_after_expand_mul)             if pivot_pos == None:                 return S.Zero diff --git a/sympy/utilities/randtest.py b/sympy/utilities/randtest.py-- a/sympy/utilities/randtest.py++ b/sympy/utilities/randtest.py


Question: Matrix determinant raises Invalid NaN comparison with particular symbolic entries from sympy import from import a f = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) f(1) 0 f(2) -a f(3) 2a(a + 2) + 2a(2a + 1) - 3a(2a + 2) f(4) 0 f(5) nan f(6) Traceback (most recent call last): File "<pyshell", line 1, in <modulef(6) File "<pyshell", line 1, in <lambdaf = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 53, in det return Determinant(matexpr).doit() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 37, in doit return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 270, in evaldeterminant return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 416, in det return self.evaldetbareiss() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 213, in evaldetbareiss return cancel(bareiss(self)) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) [Previous line repeated 1 more times] File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 55, in new rows, cols, flatlist = cls.handlecreationinputs(args, kwargs) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in handlecreationinputs for j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in <listcompfor j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 208, in entry cancel(ret) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\polys\", line 6423, in cancel f = factorterms(f, radical=True) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1193, in factorterms return do(expr) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in do [do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in <listcomp*[do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in do if all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in <genexprif all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 323, in lt raise TypeError("Invalid NaN comparison") TypeError: Invalid NaN comparison Correct me if I'm wrong but isn't the Bareiss algorithm only valid for integer matrices, which cannot be assumed here?

from sympy.core.compatibility import is_sequence, as_int  def random_complex_number(a=2, b=-1, c=3, d=1, rational=False):def random_complex_number(a=2, b=-1, c=3, d=1, rational=False, tolerance=None):     """     Return a random complex number.      To reduce chance of hitting branch cuts or anything, we guarantee     b <= Im z <= d, a <= Re z <= c    When rational is True, a rational approximation to a random number    is obtained within specified tolerance, if any.     """     A, B = uniform(a, c), uniform(b, d)     if not rational:         return A + I*B    return nsimplify(A, rational=True) + I*nsimplify(B, rational=True)    return (nsimplify(A, rational=True, tolerance=tolerance) +        I*nsimplify(B, rational=True, tolerance=tolerance))   def verify_numerically(f, g, z=None, tol=1.0e-6, a=2, b=-1, c=3, d=1):


Question: (-x/4 - S(1)/12)x - 1 simplifies to an inequivalent expression from sympy import x = Symbol('x') e = (-x/4 - S(1)/12)x - 1 e (-x/4 - 1/12)x - 1 f = simplify(e) f 12(-x)(-12x + (-3x - 1)x) a = S(9)/5 simplify(e.subs(x,a)) -1 - 3215(1/5)2(2/5)/225 simplify(f.subs(x,a)) -1 - 32(-1)(4/5)60(1/5)/225 N(e.subs(x,a)) -1. N(f.subs(x,a)) -0. - 0.189590423018741I

if p is not False:             dict = {p[0]: p[1]}         else:            dict = Integer(self).factors(limit=2**15)            dict = Integer(b_pos).factors(limit=2**15)          # now process the dict of factors        if self.is_negative:            dict[-1] = 1         out_int = 1  # integer part         out_rad = 1  # extracted radicals         sqr_int = 1


Question: (-x/4 - S(1)/12)x - 1 simplifies to an inequivalent expression from sympy import x = Symbol('x') e = (-x/4 - S(1)/12)x - 1 e (-x/4 - 1/12)x - 1 f = simplify(e) f 12(-x)(-12x + (-3x - 1)x) a = S(9)/5 simplify(e.subs(x,a)) -1 - 3215(1/5)2(2/5)/225 simplify(f.subs(x,a)) -1 - 32(-1)(4/5)60(1/5)/225 N(e.subs(x,a)) -1. N(f.subs(x,a)) -0. - 0.189590423018741I

break         for k, v in sqr_dict.items():             sqr_int *= k**(v//sqr_gcd)        if sqr_int == self and out_int == 1 and out_rad == 1:        if sqr_int == b_pos and out_int == 1 and out_rad == 1:             result = None         else:             result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q))            if self.is_negative:                result *= Pow(S.NegativeOne, expt)         return result      def _eval_is_prime(self):


Question: max & min i found most language cannot be converted into max & min like octave,Fortran and others (js and R have been fix , thx ;) )

"exp": "exp",     "erf": "erf",     "Abs": "abs",    "conjugate": "conjg"    "conjugate": "conjg",    "Max": "max",    "Min": "min" }  diff --git a/sympy/printing/octave.py b/sympy/printing/octave.py-- a/sympy/printing/octave.py++ b/sympy/printing/octave.py


Question: max & min i found most language cannot be converted into max & min like octave,Fortran and others (js and R have been fix , thx ;) )

"laguerre": "laguerreL",     "li": "logint",     "loggamma": "gammaln",<ins>    "Max": "max",    "Min": "min",</ins>     "polygamma": "psi",     "Shi": "sinhint",     "Si": "sinint",


Question: max & min i found most language cannot be converted into max & min like octave,Fortran and others (js and R have been fix , thx ;) )

# assignment (if False).  FIXME: this should be looked a more carefully     # for Octave. <ins></ins>     def __init__(self, settings={}):         super(OctaveCodePrinter, self).__init__(settings)         self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))


Question: max & min i found most language cannot be converted into max & min like octave,Fortran and others (js and R have been fix , thx ;) )

return "lambertw(" + args + ")"  <ins>    def _nested_binary_math_func(self, expr):        return '{name}({arg1}, {arg2})'.format(            name=self.known_functions[expr.__class__.__name__],            arg1=self._print(expr.args[0]),            arg2=self._print(expr.func(*expr.args[1:]))            )    _print_Max = _print_Min = _nested_binary_math_func</ins>     def _print_Piecewise(self, expr):         if expr.args[-1].cond != True:             # We need the last conditional to be a True, otherwise the resulting


Question: Issue with a substitution that leads to an undefined expression If b is substituted by a, r is undefined. It is possible to calculate the limit But whenever a subexpression of r is undefined, r itself is undefined.

changed = False             for b, e in c_powers:                 if e.is_zero:<ins>                    # canceling out infinities yields NaN                    if (b.is_Add or b.is_Mul) and any(infty in b.args                        for infty in (S.ComplexInfinity, S.Infinity,                                      S.NegativeInfinity)):                        return [S.NaN], [], None</ins>                     continue                 if e is S.One:                     if b.is_Number:


Question: Printing should use short representation of quantities. There is a test that explicitly expects that printing does not use but : Is there a reason behind this? I find it quite user-unfriendly to look at instead of . It would be very easy to change here: But then, the above test would fail. Is anyone emotionally attached to the current verbose display of units and quantities? Use abbreviated form of quantities when printing Currently, the abbreviation used in the definition of quantities, e.g. in the definition of , is hardly used anywhere. For example: returns: This PR modifies printing of quantities to use the abbreviation if one was provided. Example: now returns: NOTE: I changed an existing test that explicitly expected the non-abbreviated name to be printed. I just do not see the point of such behaviour, but I am happy to be educated otherwise.

"order": None,         "full_prec": "auto",         "sympy_integers": False,<ins>        "abbrev": False,</ins>     }      _relationals = dict()


Question: Printing should use short representation of quantities. There is a test that explicitly expects that printing does not use but : Is there a reason behind this? I find it quite user-unfriendly to look at instead of . It would be very easy to change here: But then, the above test would fail. Is anyone emotionally attached to the current verbose display of units and quantities? Use abbreviated form of quantities when printing Currently, the abbreviation used in the definition of quantities, e.g. in the definition of , is hardly used anywhere. For example: returns: This PR modifies printing of quantities to use the abbreviation if one was provided. Example: now returns: NOTE: I changed an existing test that explicitly expected the non-abbreviated name to be printed. I just do not see the point of such behaviour, but I am happy to be educated otherwise.

return r' \ '.join(self._print(set) for set in expr.args)      def _print_Quantity(self, expr):<ins>        if self._settings.get("abbrev", False):            return "%s" % expr.abbrev</ins>         return "%s" % expr.name      def _print_Quaternion(self, expr):


Question: Printing should use short representation of quantities. There is a test that explicitly expects that printing does not use but : Is there a reason behind this? I find it quite user-unfriendly to look at instead of . It would be very easy to change here: But then, the above test would fail. Is anyone emotionally attached to the current verbose display of units and quantities? Use abbreviated form of quantities when printing Currently, the abbreviation used in the definition of quantities, e.g. in the definition of , is hardly used anywhere. For example: returns: This PR modifies printing of quantities to use the abbreviation if one was provided. Example: now returns: NOTE: I changed an existing test that explicitly expected the non-abbreviated name to be printed. I just do not see the point of such behaviour, but I am happy to be educated otherwise.

"""Returns the expression as a string.      For large expressions where speed is a concern, use the setting    order='none'.    order='none'. If abbrev=True setting is used then units are printed in    abbreviated form.      Examples     ========


Question: Display of SeqFormula() The Jupyter rendering of this command backslash-escapes the brackets producing: Copying this output to a markdown cell this does not render properly. Whereas: does render just fine. So - sequence output should not backslash-escape square brackets, or, should instead render?

else:             printset = tuple(s)         return (r"\left\["        return (r"\left["               + r", ".join(self._print(el) for el in printset)              + r"\right\]")              + r"\right]")      _print_SeqPer = _print_SeqFormula     _print_SeqAdd = _print_SeqFormula


Question: Evaluating powers of Powers of tensor product expressions are not possible to evaluate with either method nor the function. This is an example session showing the issue where and shows expected result for and respectively.

matrix_tensor_product ) <ins></ins> __all__ = [     'TensorProduct',     'tensor_product_simp'


Question: Evaluating powers of Powers of tensor product expressions are not possible to evaluate with either method nor the function. This is an example session showing the issue where and shows expected result for and respectively.

"""     # TODO: This won't work with Muls that have other composites of    # TensorProducts, like an Add, Pow, Commutator, etc.    # TensorProducts, like an Add, Commutator, etc.     # TODO: This only works for the equivalent of single Qbit gates.     if not isinstance(e, Mul):         return e     c_part, nc_part = e.args_cnc()     n_nc = len(nc_part)    if n_nc == 0 or n_nc == 1:    if n_nc == 0:        return e    elif n_nc == 1:        if isinstance(nc_part[0], Pow):            return  Mul(*c_part) * tensor_product_simp_Pow(nc_part[0])         return e     elif e.has(TensorProduct):         current = nc_part[0]         if not isinstance(current, TensorProduct):            raise TypeError('TensorProduct expected, got: %r' % current)            if isinstance(current, Pow):                if isinstance(current.base, TensorProduct):                    current = tensor_product_simp_Pow(current)            else:                raise TypeError('TensorProduct expected, got: %r' % current)         n_terms = len(current.args)         new_args = list(current.args)         for next in nc_part[1:]:


Question: Evaluating powers of Powers of tensor product expressions are not possible to evaluate with either method nor the function. This is an example session showing the issue where and shows expected result for and respectively.

for i in range(len(new_args)):                     new_args[i] = new_args[i] * next.args[i]             else:                # this won't quite work as we don't want next in the                # TensorProduct                for i in range(len(new_args)):                    new_args[i] = new_args[i] * next                if isinstance(next, Pow):                    if isinstance(next.base, TensorProduct):                        new_tp = tensor_product_simp_Pow(next)                        for i in range(len(new_args)):                            new_args[i] = new_args[i] * new_tp.args[i]                    else:                        raise TypeError('TensorProduct expected, got: %r' % next)                else:                    raise TypeError('TensorProduct expected, got: %r' % next)             current = next         return Mul(*c_part) * TensorProduct(*new_args)    elif e.has(Pow):        new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ]        return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args))     else:         return e def tensor_product_simp_Pow(e):    """Evaluates ``Pow`` expressions whose base is ``TensorProduct``"""    if not isinstance(e, Pow):        return e    if isinstance(e.base, TensorProduct):        return TensorProduct(*[ b**e.exp for b in e.base.args])    else:        return e  def tensor_product_simp(e, **hints):     """Try to simplify and combine TensorProducts.


Question: Evaluating powers of Powers of tensor product expressions are not possible to evaluate with either method nor the function. This is an example session showing the issue where and shows expected result for and respectively.

if isinstance(e, Add):         return Add(*[tensor_product_simp(arg) for arg in e.args])     elif isinstance(e, Pow):        return tensor_product_simp(e.base) ** e.exp        if isinstance(e.base, TensorProduct):            return tensor_product_simp_Pow(e)        else:            return tensor_product_simp(e.base) ** e.exp     elif isinstance(e, Mul):         return tensor_product_simp_Mul(e)     elif isinstance(e, Commutator):


Question: Generation of wrong octave code for imaginary number representation Hi, sympy generates code like which gives an error in Octave 4.0. Would it be better to substitute it with ?

def _print_Mul(self, expr):         # print complex numbers nicely in Octave         if (expr.is_number and expr.is_imaginary and                expr.as_coeff_Mul()[0].is_integer):                (S.ImaginaryUnit*expr).is_Integer):             return "%si" % self._print(-S.ImaginaryUnit*expr)          # cribbed from str.py


Question: () should output a Sum() object Currently, () outputs an evaluated summation instead of an unevaluated expression: For large n this takes a long time to compute. It seems like this should output an unevaluated sum and if the user wants to expand the sum they'd call on the result. It may not be worth deprecating this behavior, but maybe we need to have a method.

break         return integrate(leading_term, *self.args[1:])     def as_sum(self, n, method="midpoint"):    def as_sum(self, n=None, method="midpoint", evaluate=True):         """        Approximates the definite integral by a sum.        Approximates a definite integral by a sum.         method ... one of: left, right, midpoint, trapezoid        Arguments        ---------        n            The number of subintervals to use, optional.        method            One of: 'left', 'right', 'midpoint', 'trapezoid'.        evaluate            If False, returns an unevaluated Sum expression. The default            is True, evaluate the sum.         These are all basically the rectangle method [1], the only difference        is where the function value is taken in each interval to define the        rectangle.        These methods of approximate integration are described in [1].         [1] http://en.wikipedia.org/wiki/Rectangle_method        [1] https://en.wikipedia.org/wiki/Riemann_sum#Methods          Examples         ========          >>> from sympy import sin, sqrt        >>> from sympy.abc import x        >>> from sympy.abc import x, n         >>> from sympy.integrals import Integral         >>> e = Integral(sin(x), (x, 3, 7))         >>> e


Question: () should output a Sum() object Currently, () outputs an evaluated summation instead of an unevaluated expression: For large n this takes a long time to compute. It seems like this should output an unevaluated sum and if the user wants to expand the sum they'd call on the result. It may not be worth deprecating this behavior, but maybe we need to have a method.

>>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == _         True         All but the trapexoid method may be used when dealing with a function        with a discontinuity. Here, the discontinuity at x = 0 can be avoided        by using the midpoint or right-hand method:        Here, the discontinuity at x = 0 can be avoided by using the        midpoint or right-hand method:          >>> e = Integral(1/sqrt(x), (x, 0, 1))         >>> e.as_sum(5).n(4)


Question: () should output a Sum() object Currently, () outputs an evaluated summation instead of an unevaluated expression: For large n this takes a long time to compute. It seems like this should output an unevaluated sum and if the user wants to expand the sum they'd call on the result. It may not be worth deprecating this behavior, but maybe we need to have a method.

2.000          The left- or trapezoid method will encounter the discontinuity and        return oo:        return infinity:          >>> e.as_sum(5, 'left')        oo        >>> e.as_sum(5, 'trapezoid')        oo        zoo        The number of intervals can be symbolic. If omitted, a dummy symbol        will be used for it.        >>> e = Integral(x**2, (x, 0, 2))        >>> e.as_sum(n, 'right').expand()        8/3 + 4/n + 4/(3*n**2)        This shows that the midpoint rule is more accurate, as its error        term decays as the square of n:        >>> e.as_sum(method='midpoint').expand()        8/3 - 2/(3*_n**2)        A symbolic sum is returned with evaluate=False:        >>> e.as_sum(n, 'midpoint', evaluate=False)        2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n          See Also         ========


Question: () should output a Sum() object Currently, () outputs an evaluated summation instead of an unevaluated expression: For large n this takes a long time to compute. It seems like this should output an unevaluated sum and if the user wants to expand the sum they'd call on the result. It may not be worth deprecating this behavior, but maybe we need to have a method.

Integral.doit : Perform the integration using any hints         """         from sympy.concrete.summations import Sum         limits = self.limits         if len(limits) > 1:             raise NotImplementedError(                 "Multidimensional midpoint rule not implemented yet")         else:             limit = limits[0]            if len(limit) != 3:                raise ValueError("Expecting a definite integral.")        if n <= 0:            raise ValueError("n must be > 0")        if n == oo:            raise NotImplementedError("Infinite summation not yet implemented")        sym, lower_limit, upper_limit = limit        dx = (upper_limit - lower_limit)/n        if method == 'trapezoid':            l = self.function.limit(sym, lower_limit)            r = self.function.limit(sym, upper_limit, "-")            result = (l + r)/2            for i in range(1, n):                x = lower_limit + i*dx                result += self.function.subs(sym, x)            return result*dx        elif method not in ('left', 'right', 'midpoint'):            raise NotImplementedError("Unknown method %s" % method)        result = 0        for i in range(n):            if method == "midpoint":                xi = lower_limit + i*dx + dx/2            elif method == "left":                xi = lower_limit + i*dx                if i == 0:                    result = self.function.limit(sym, lower_limit)                    continue            elif method == "right":                xi = lower_limit + i*dx + dx                if i == n:                    result += self.function.limit(sym, upper_limit, "-")                    continue            result += self.function.subs(sym, xi)        return result*dx            if (len(limit) != 3 or limit[1].is_finite is False or                limit[2].is_finite is False):                raise ValueError("Expecting a definite integral over "                                  "a finite interval.")        if n is None:            n = Dummy('n', integer=True, positive=True)        else:            n = sympify(n)        if (n.is_positive is False or n.is_integer is False or            n.is_finite is False):            raise ValueError("n must be a positive integer, got %s" % n)        x, a, b = limit        dx = (b - a)/n        k = Dummy('k', integer=True, positive=True)        f = self.function        if method == "left":            result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n))        elif method == "right":            result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n))        elif method == "midpoint":            result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n))        elif method == "trapezoid":            result = dx*((f.subs(x, a) + f.subs(x, b))/2 +                Sum(f.subs(x, a + k*dx), (k, 1, n - 1)))        else:            raise ValueError("Unknown method %s" % method)        return result.doit() if evaluate else result      def _sage_(self):         import sage.all as sage


Question: Inconsistency when simplifying (-a)x * a(-x), a a positive integer Compare: vs

if (ne is S.One):                     return Rational(self.q, self.p)                 if self.is_negative:                    if expt.q != 1:                        return -(S.NegativeOne)**((expt.p % expt.q) /                               S(expt.q))*Rational(self.q, -self.p)**ne                    else:                        return S.NegativeOne**ne*Rational(self.q, -self.p)**ne                    return S.NegativeOne**expt*Rational(self.q, -self.p)**ne                 else:                     return Rational(self.q, self.p)**ne             if expt is S.Infinity:  # -oo already caught by test for negative


Question: Inconsistency when simplifying (-a)x * a(-x), a a positive integer Compare: vs

# invert base and change sign on exponent             ne = -expt             if self.is_negative:                if expt.q != 1:                    return -(S.NegativeOne)**((expt.p % expt.q) /                            S(expt.q))*Rational(1, -self)**ne                else:                    return (S.NegativeOne)**ne*Rational(1, -self)**ne                    return S.NegativeOne**expt*Rational(1, -self)**ne             else:                 return Rational(1, self.p)**ne         # see if base is a perfect root, sqrt(4) --> 2


Question: Failed coercion of an expression with E and exp to a field element throws This is the same kind of an issue that dealt with, apparently there is more to be done.

from sympy.core.compatibility import is_sequence, reduce, string_types from sympy.core.expr import Expr from sympy.core.mod import Mod<ins>from sympy.core.numbers import Exp1from sympy.core.singleton import S</ins> from sympy.core.symbol import Symbol from sympy.core.sympify import CantSympify, sympify from sympy.functions.elementary.exponential import ExpBase


Question: Failed coercion of an expression with E and exp to a field element throws This is the same kind of an issue that dealt with, apparently there is more to be done.

return reduce(add, list(map(_rebuild, expr.args)))             elif expr.is_Mul:                 return reduce(mul, list(map(_rebuild, expr.args)))            elif expr.is_Pow or isinstance(expr, ExpBase):            elif expr.is_Pow or isinstance(expr, (ExpBase, Exp1)):                 b, e = expr.as_base_exp()                 # look for bg**eg whose integer power may be b**e                choices = tuple((gen, bg, eg) for gen, (bg, eg) in powers                    if bg == b and Mod(e, eg) == 0)                if choices:                    gen, bg, eg = choices[0]                    return mapping.get(gen)**(e/eg)                elif e.is_Integer:                    return _rebuild(expr.base)**int(expr.exp)                for gen, (bg, eg) in powers:                    if bg == b and Mod(e, eg) == 0:                        return mapping.get(gen)**int(e/eg)                if e.is_Integer and e is not S.One:                    return _rebuild(b)**int(e)              try:                 return domain.convert(expr)


Question: product(1 - a2 / (n*pi)2, [n, 1, oo]) should not evaluate to 0 (if the product is evaluated the correct result is )

from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.concrete.expr_with_intlimits import ExprWithIntLimits<ins>from sympy.core.exprtools import factor_terms</ins> from sympy.functions.elementary.exponential import exp, log from sympy.polys import quo, roots from sympy.simplify import powsimp


Question: product(1 - a2 / (n*pi)2, [n, 1, oo]) should not evaluate to 0 (if the product is evaluated the correct result is )

return poly.LC()**(n - a + 1) * A * B          elif term.is_Add:            p, q = term.as_numer_denom()            q = self._eval_product(q, (k, a, n))            if q.is_Number:                # There is expression, which couldn't change by                # as_numer_denom(). E.g. n**(2/3) + 1 --> (n**(2/3) + 1, 1).                # We have to catch this case.                from sympy.concrete.summations import Sum                p = exp(Sum(log(p), (k, a, n)))            else:                p = self._eval_product(p, (k, a, n))            return p / q            factored = factor_terms(term, fraction=True)            if factored.is_Mul:                return self._eval_product(factored, (k, a, n))          elif term.is_Mul:             exclude, include = [], []


Question: logcombine(log(3) - log(2)) does nothing Original issue for : Original author:

for k in list(log1.keys()):             log1[Mul(*k)] = log(logcombine(Mul(*[                 l.args[0]**Mul(*c) for c, l in log1.pop(k)]),                force=force))                force=force), evaluate=False)          # logs that have oppositely signed coefficients can divide         for k in ordered(list(log1.keys())):


Question: logcombine(log(3) - log(2)) does nothing Original issue for : Original author:

num, den = k, -k                 if num.count_ops() > den.count_ops():                     num, den = den, num                other.append(num*log(log1.pop(num).args[0]/log1.pop(den).args[0]))                other.append(                    num*log(log1.pop(num).args[0]/log1.pop(den).args[0],                            evaluate=False))             else:                 other.append(k*log1.pop(k))


Question: Integrate(1/(x2 + y2), x) returns a wrong result The correct result is . It seems similar to .

if len(R_v) != C.count_roots():             return None         R_v_paired = [] # take one from each pair of conjugate roots         for r_v in R_v:            if not r_v.is_positive:                continue            if r_v not in R_v_paired and -r_v not in R_v_paired:                if r_v.is_negative or r_v.could_extract_minus_sign():                    R_v_paired.append(-r_v)                elif not r_v.is_zero:                    R_v_paired.append(r_v)        for r_v in R_v_paired:              D = d.subs({u: r_u, v: r_v})


Question: sympify(u"α") does not work Original issue for : Original author: Original owner:

from __future__ import print_function, division from .sympy_tokenize import \    generate_tokens, untokenize, TokenError, \    NUMBER, STRING, NAME, OP, ENDMARKERfrom tokenize import (generate_tokens, untokenize, TokenError,    NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN)  from keyword import iskeyword  import astimport re import unicodedata  import sympy from sympy.core.compatibility import exec_, StringIO from sympy.core.basic import Basic _re_repeated = re.compile(r"^(\d*)\.(\d*)\[(\d+)\]$") def _token_splittable(token):     """     Predicate for whether a token name can be split into multiple tokens.


Question: sympify(u"α") does not work Original issue for : Original author: Original owner:

def factorial_notation(tokens, local_dict, global_dict):     """Allows standard notation for factorial."""     result = []    prevtoken = ''    nfactorial = 0     for toknum, tokval in tokens:        if toknum == OP:        if toknum == ERRORTOKEN:             op = tokval            if op == '!!':                if prevtoken == '!' or prevtoken == '!!':                    raise TokenError                result = _add_factorial_tokens('factorial2', result)            elif op == '!':                if prevtoken == '!' or prevtoken == '!!':                    raise TokenError                result = _add_factorial_tokens('factorial', result)            if op == '!':                nfactorial += 1             else:                nfactorial = 0                 result.append((OP, op))         else:            if nfactorial == 1:                result = _add_factorial_tokens('factorial', result)            elif nfactorial == 2:                result = _add_factorial_tokens('factorial2', result)            elif nfactorial > 2:                raise TokenError            nfactorial = 0             result.append((toknum, tokval))        prevtoken = tokval     return result


Question: sympify(u"α") does not work Original issue for : Original author: Original owner:

return result def repeated_decimals(tokens, local_dict, global_dict):    """    Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90)    Run this before auto_number.    """    result = []    def is_digit(s):        return all(i in '0123456789_' for i in s)    # num will running match any DECIMAL [ INTEGER ]    num = []    for toknum, tokval in tokens:        if toknum == NUMBER:            if (not num and '.' in tokval and 'e' not in tokval.lower() and                'j' not in tokval.lower()):                num.append((toknum, tokval))            elif is_digit(tokval)and  len(num) == 2:                num.append((toknum, tokval))            elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]):                # Python 2 tokenizes 00123 as '00', '123'                # Python 3 tokenizes 01289 as '012', '89'                num.append((toknum, tokval))            else:                num = []        elif toknum == OP:            if tokval == '[' and len(num) == 1:                num.append((OP, tokval))            elif tokval == ']' and len(num) >= 3:                num.append((OP, tokval))            elif tokval == '.' and not num:                # handle .[1]                num.append((NUMBER, '0.'))            else:                num = []        else:            num = []        result.append((toknum, tokval))        if num and num[-1][1] == ']':            # pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post,            # and d/e = repetend            result = result[:-len(num)]            pre, post = num[0][1].split('.')            repetend = num[2][1]            if len(num) == 5:                repetend += num[3][1]            pre = pre.replace('_', '')            post = post.replace('_', '')            repetend = repetend.replace('_', '')            zeros = '0'*len(post)            post, repetends = [w.lstrip('0') for w in [post, repetend]]                                        # or else interpreted as octal            a = pre or '0'            b, c = post or '0', '1' + zeros            d, e = repetends, ('9'*len(repetend)) + zeros            seq = [                (OP, '('),                    (NAME, 'Integer'),                    (OP, '('),                        (NUMBER, a),                    (OP, ')'),                    (OP, '+'),                    (NAME, 'Rational'),                    (OP, '('),                        (NUMBER, b),                        (OP, ','),                        (NUMBER, c),                    (OP, ')'),                    (OP, '+'),                    (NAME, 'Rational'),                    (OP, '('),                        (NUMBER, d),                        (OP, ','),                        (NUMBER, e),                    (OP, ')'),                (OP, ')'),            ]            result.extend(seq)            num = []    return result  def auto_number(tokens, local_dict, global_dict):    """Converts numeric literals to use SymPy equivalents.    """    Converts numeric literals to use SymPy equivalents.     Complex numbers use ``I``; integer literals use ``Integer``, float    literals use ``Float``, and repeating decimals use ``Rational``.    Complex numbers use ``I``, integer literals use ``Integer``, and float    literals use ``Float``.      """     result = []    prevtoken = ''      for toknum, tokval in tokens:         if toknum == NUMBER:


Question: sympify(u"α") does not work Original issue for : Original author: Original owner:

if '.' in number or (('e' in number or 'E' in number) and                     not (number.startswith('0x') or number.startswith('0X'))):                match = _re_repeated.match(number)                if match is not None:                    # Clear repeating decimals, e.g. 3.4[31] -> (3 + 4/10 + 31/990)                    pre, post, repetend = match.groups()                    zeros = '0'*len(post)                    post, repetends = [w.lstrip('0') for w in [post, repetend]]                                                # or else interpreted as octal                    a = pre or '0'                    b, c = post or '0', '1' + zeros                    d, e = repetends, ('9'*len(repetend)) + zeros                    seq = [                        (OP, '('),                        (NAME,                         'Integer'), (OP, '('), (NUMBER, a), (OP, ')'),                        (OP, '+'),                        (NAME, 'Rational'), (OP, '('), (                            NUMBER, b), (OP, ','), (NUMBER, c), (OP, ')'),                        (OP, '+'),                        (NAME, 'Rational'), (OP, '('), (                            NUMBER, d), (OP, ','), (NUMBER, e), (OP, ')'),                        (OP, ')'),                    ]                else:                    seq = [(NAME, 'Float'), (OP, '('),                           (NUMBER, repr(str(number))), (OP, ')')]                seq = [(NAME, 'Float'), (OP, '('),                    (NUMBER, repr(str(number))), (OP, ')')]             else:                 seq = [(NAME, 'Integer'), (OP, '('), (                     NUMBER, number), (OP, ')')]


Question: sympify(u"α") does not work Original issue for : Original author: Original owner:

return result <del></del> def rationalize(tokens, local_dict, global_dict):     """Converts floats into ``Rational``. Run AFTER ``auto_number``."""     result = []


Question: sympify(u"α") does not work Original issue for : Original author: Original owner:

#: Standard transformations for :func:`parse_expr`. #: Inserts calls to :class:`Symbol`, :class:`Integer`, and other SymPy #: datatypes and allows the use of standard factorial notation (e.g. ``x!``).standard_transformations = (lambda_notation, auto_symbol, auto_number, factorial_notation)standard_transformations = (lambda_notation, auto_symbol, repeated_decimals, auto_number,    factorial_notation)   def stringify_expr(s, local_dict, global_dict, transformations):diff --git a/sympy/parsing/sympy_tokenize.py b/sympy/parsing/sympy_tokenize.pydeleted file mode 100644-- a/sympy/parsing/sympy_tokenize.py++ /dev/null