Question: if q.is_Number:                 if p.is_Number:                    return (p % q)                    return p%q                 if q == 2:                     if p.is_even:                         return S.Zero


Question: except TypeError:                 pass             else:                if type(d) is int:                if isinstance(d, integer_types):                     rv = p - d*q                     if (rv*q < 0) == True:                         rv += q

Mod(3i, 2) unchanged should reduce to (as reported in ) and will do so with a change something like this: Returns correct result to Mod(3i, 2). modified the to return correct answer to Mod(3i, 2). a test (All as suggested by ) Earlier sympify(3k%2) Mod(3k,2) Now sympify(3k%2) Mod(k,2) Release Notes <!-- BEGIN RELEASE NOTES --functions fixed a bug in mod a test <!-- END RELEASE NOTES --


Question: net = prod_mod1*prod_mod                 return prod_non_mod*cls(net, q) <ins>            if q.is_Integer and q is not S.One:                _ = []                for i in non_mod_l:                    if i.is_Integer and (i % q is not S.Zero):                        _.append(i%q)                    else:                        _.append(i)                non_mod_l = _            p = Mul(*(non_mod_l + mod_l))</ins>         # XXX other possibilities?          # extract gcd; any further simplification should be done by the user


Question: def _print_MatrixElement(self, expr):         return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \            + '_{%s, %s}' % (expr.i, expr.j)            + '_{%s, %s}' % (            self._print(expr.i),            self._print(expr.j)        )      def _print_MatrixSlice(self, expr):         def latexslice(x):

Indexed matrix-expression LaTeX printer is not compilable The LaTeX string produced by the last command is: LaTeX complains about a double subscript . This expression won't render in MathJax either.


Question: def _print_Integer(self, expr):         return 'Integer(%i)' % expr.p <ins>    def _print_Integers(self, expr):        return 'Integers'    def _print_Naturals(self, expr):        return 'Naturals'    def _print_Naturals0(self, expr):        return 'Naturals0'    def _print_Reals(self, expr):        return 'Reals'</ins>     def _print_list(self, expr):         return "[%s]" % self.reprify(expr, ", ")

Sets printing issues Some issues with str and srepr printing in sets. Some notes: The printer should always generate valid Python, which recreates the expression (but may require some variables to be defined). The printer should generate an expression that recreates the expression exactly, using only the names from (or other relevant imports for other submodules, but that isn't relevant for the sets). Fancy printing should be relegated to the pretty printers ( and ). Here are the issues I found: The former creates a list, not an interval. The latter isn't even valid Python. (and probably others) isn't a name that is imported from . It should print as . The printers should probably do the same. It's not valid Python. It should print as . Printing as is fine when gets merged. There are likely others. I didn't check too much. An audit of the printing in the sets module would be worthwhile.


Question: y = y[0]     elif isinstance(y, Symbol):         dep = {y}    elif isinstance(y, Function):        pass     else:        raise ValueError("expecting x-dependent symbol(s) but got: %s" % y)        raise ValueError("expecting x-dependent symbol(s) or function(s) but got: %s" % y)      f = dict([(s, Function(         s.name)(x)) for s in eq.free_symbols if s != x and s in dep])    dydx = Function(y.name)(x).diff(x)    if isinstance(y, Symbol):        dydx = Function(y.name)(x).diff(x)    else:        dydx = y.diff(x)     eq = eq.subs(f)     derivs = {}     for i in range(n):

Some issues with idiff idiff doesn't support Eq, and it also doesn't support f(x) instead of y. Both should be easy to correct.


Question: meter.set_dimension(length) meter.set_scale_factor(One) # gram; used to define its prefixed unitsg = gram = grams = Quantity("gram", abbrev="g")gram.set_dimension(mass)gram.set_scale_factor(One)# NOTE: the `kilogram` has scale factor 1000. In SI, kg is a base unit, but# nonetheless we are trying to be compatible with the `kilo` prefix. In a# similar manner, people using CGS or gaussian units could argue that the# `centimeter` rather than `meter` is the fundamental unit for length, but the# scale factor of `centimeter` will be kept as 1/100 to be compatible with the# `centi` prefix.  The current state of the code assumes SI unit dimensions, in# NOTE: the `kilogram` has scale factor of 1 in SI.# The current state of the code assumes SI unit dimensions, in # the future this module will be modified in order to be unit system-neutral # (that is, support all kinds of unit systems). kg = kilogram = kilograms = Quantity("kilogram", abbrev="kg") kilogram.set_dimension(mass)kilogram.set_scale_factor(kilo*gram)kilogram.set_scale_factor(One)  s = second = seconds = Quantity("second", abbrev="s") second.set_dimension(time)

Make .scalefactor private in the units module sympy version: 1.3 Python version: 3.6.6 Operating System: Win10 Dividing a Quantity with dimension voltage by a Quantity with dimension current yields ohm/1000 when I expected ohm. In the SI system, 1 V/ 1 A = 1 Ω. The problem is related to the kilogram workaround and the property . The default scalefactor for a Quantity is 1. The docstring for `scalefactor' states: But, the scale factor for ohm is 1000. ohm.scalefactor 1000 This value of 1000 conflicts with the definition. is a user facing property and should be consistent with the unit system definition, in this case the SI. The kilogram workaround should be an internal implementation factor and not exposed to the user.


Question: candela.set_dimension(luminous_intensity) candela.set_scale_factor(One) <ins>g = gram = grams = Quantity("gram", abbrev="g")gram.set_dimension(mass)gram.set_scale_factor(kilogram/kilo)</ins>  mg = milligram = milligrams = Quantity("milligram", abbrev="mg") milligram.set_dimension(mass)


Question: class MinMaxBase(Expr, LatticeOp):     def __new__(cls, *args, **assumptions):<del>        if not args:            raise ValueError("The Max/Min functions must have arguments.")</del>          args = (sympify(arg) for arg in args)

Zero-argument Min() and Max() Right now and with no arguments raise . It might be mathematically more convenient to have them return and , respectively. See for why these are valid answers mathematically.


Question: return         if z == len(self.args):             return True        if len(nz) == len(self.args):        if len(nz) == 0 or len(nz) == len(self.args):             return None         b = self.func(*nz)         if b.is_zero:

iszero is incorrect on complex integer should return if it cannot decide, but should never give the wrong answer. However: This is causing errors in determining the rank of a matrix. See issue Fixing iszero for complex numbers while Add References to other Issues or PRs Other comments: <!-- BEGIN RELEASE NOTES --- core Fix becoming on some expressions with . <!-- END RELEASE NOTES --


Question: def demo_vgate_app(v):     for i in range(2**v.nqubits):         print('qapply(v*IntQubit(%i, %r))' % (i, v.nqubits))        pprint(qapply(v*IntQubit(i, v.nqubits)))        qapply(v*IntQubit(i, v.nqubits))        pprint(qapply(v*IntQubit(i, nqubits=v.nqubits)))        qapply(v*IntQubit(i, nqubits=v.nqubits))   def black_box(qubits):    return True if qubits == IntQubit(1, qubits.nqubits) else False    return True if qubits == IntQubit(1, nqubits=qubits.nqubits) else False   def main():diff --git a/sympy/physics/quantum/grover.py b/sympy/physics/quantum/grover.py-- a/sympy/physics/quantum/grover.py++ b/sympy/physics/quantum/grover.py

Wrong measurement for one qubit state. Hi, sympy developers. measure_all(qapply(Qubit('0'))) returns [(0, 1)] best, Vladimir.


Question: """      amp = 1/sqrt(2**nqubits)    return sum([amp*IntQubit(n, nqubits) for n in range(2**nqubits)])    return sum([amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits)])   class OracleGate(Gate):


Question: matrixOracle = eye(nbasis)         # Flip the sign given the output of the oracle function         for i in range(nbasis):            if self.search_function(IntQubit(i, self.nqubits)):            if self.search_function(IntQubit(i, nqubits=self.nqubits)):                 matrixOracle[i, i] = NegativeOne()         return matrixOracle diff --git a/sympy/physics/quantum/qexpr.py b/sympy/physics/quantum/qexpr.py-- a/sympy/physics/quantum/qexpr.py++ b/sympy/physics/quantum/qexpr.py


Question: def free_symbols(self):         return {self}     def __new__(cls, *args, **old_assumptions):    def __new__(cls, *args, **kwargs):         """Construct a new quantum object.          Parameters


Question: """          # First compute args and call Expr.__new__ to create the instance        args = cls._eval_args(args)        args = cls._eval_args(args, **kwargs)         if len(args) == 0:            args = cls._eval_args(tuple(cls.default_args()))        inst = Expr.__new__(cls, *args, **old_assumptions)            args = cls._eval_args(tuple(cls.default_args()), **kwargs)        inst = Expr.__new__(cls, *args)         # Now set the slots on the instance         inst.hilbert_space = cls._eval_hilbert_space(args)         return instdiff --git a/sympy/physics/quantum/qubit.py b/sympy/physics/quantum/qubit.py-- a/sympy/physics/quantum/qubit.py++ b/sympy/physics/quantum/qubit.py


Question: """A base class for qubits that work with binary representations."""      @classmethod    def _eval_args(cls, args):    def _eval_args(cls, args, nqubits=None):         # The case of a QubitState instance         if len(args) == 1 and isinstance(args[0], QubitState):             return QubitState._eval_args(args)        # otherwise, args should be integer        elif not all((isinstance(a, (int, Integer)) for a in args)):            raise ValueError('values must be integers, got (%s)' % (tuple(type(a) for a in args),))        # use nqubits if specified        if nqubits is not None:            if not isinstance(nqubits, (int, Integer)):                raise ValueError('nqubits must be an integer, got (%s)' % type(nqubits))            if len(args) != 1:                raise ValueError(                    'too many positional arguments (%s). should be (number, nqubits=n)' % (args,))            return cls._eval_args_with_nqubits(args[0], nqubits)         # For a single argument, we construct the binary representation of         # that integer with the minimal number of bits.         if len(args) == 1 and args[0] > 1:


Question: # For two numbers, the second number is the number of bits         # on which it is expressed, so IntQubit(0,5) == |00000>.         elif len(args) == 2 and args[1] > 1:            need = bitcount(abs(args[0]))            if args[1] < need:                raise ValueError(                    'cannot represent %s with %s bits' % (args[0], args[1]))            qubit_values = [(args[0] >> i) & 1 for i in reversed(range(args[1]))]            return QubitState._eval_args(qubit_values)            return cls._eval_args_with_nqubits(args[0], args[1])         else:             return QubitState._eval_args(args)     @classmethod    def _eval_args_with_nqubits(cls, number, nqubits):        need = bitcount(abs(number))        if nqubits < need:            raise ValueError(                'cannot represent %s with %s bits' % (number, nqubits))        qubit_values = [(number >> i) & 1 for i in reversed(range(nqubits))]        return QubitState._eval_args(qubit_values)     def as_int(self):         """Return the numerical value of the qubit."""         number = 0


Question: values : int, tuple         If a single argument, the integer we want to represent in the qubit         values. This integer will be represented using the fewest possible        number of qubits. If a pair of integers, the first integer gives the        integer to represent in binary form and the second integer gives        the number of qubits to use.        number of qubits.        If a pair of integers and the second value is more than one, the first        integer gives the integer to represent in binary form and the second        integer gives the number of qubits to use.        List of zeros and ones is also accepted to generate qubit by bit pattern.    nqubits : int        The integer that represents the number of qubits.        This number should be passed with keyword ``nqubits=N``.        You can use this in order to avoid ambiguity of Qubit-style tuple of bits.        Please see the example below for more details.      Examples     ========


Question: >>> Qubit(q)         |101><ins>    Please note that ``IntQubit`` also accepts a ``Qubit``-style list of bits.    So, the code below yields qubits 3, not a single bit ``1``.        >>> IntQubit(1, 1)        |3>    To avoid ambiguity, use ``nqubits`` parameter.    Use of this keyword is recommended especially when you provide the values by variables.        >>> IntQubit(1, nqubits=1)        |1>        >>> a = 1        >>> IntQubit(a, nqubits=1)        |1></ins>     """     @classmethod     def dual_class(self):


Question: for i in range(size):             if m[i] != 0.0:                 results.append(                    (Qubit(IntQubit(i, nqubits)), m[i]*conjugate(m[i]))                    (Qubit(IntQubit(i, nqubits=nqubits)), m[i]*conjugate(m[i]))                 )         return results     else:


Question: def _print_tuple(self, expr):         return r"\left( %s\right)" % \            r", \quad ".join([ self._print(i) for i in expr ])            r", \  ".join([ self._print(i) for i in expr ])      def _print_TensorProduct(self, expr):         elements = [self._print(a) for a in expr.args]

Use '\ ' instead of '\quad' for latex of lists, tuples, and dicts See Twitter discussion.


Question: def _print_list(self, expr):         return r"\left[ %s\right]" % \            r", \quad ".join([ self._print(i) for i in expr ])            r", \  ".join([ self._print(i) for i in expr ])      def _print_dict(self, d):         keys = sorted(d.keys(), key=default_sort_key)


Question: val = d[key]             items.append("%s : %s" % (self._print(key), self._print(val)))         return r"\left\{ %s\right\}" % r", \quad ".join(items)        return r"\left\{ %s\right\}" % r", \  ".join(items)      def _print_Dict(self, expr):         return self._print_dict(expr)


Question: dictionary.      >>> print(latex([2/x, y], mode='inline'))    $\left[ 2 / x, \quad y\right]$    $\left[ 2 / x, \  y\right]$      """     if symbol_names is None:


Question: def _special_function_classes(self):         from sympy.functions.special.tensor_functions import KroneckerDelta         from sympy.functions.special.gamma_functions import gamma, lowergamma        from sympy.functions.special.zeta_functions import lerchphi         from sympy.functions.special.beta_functions import beta         from sympy.functions.special.delta_functions import DiracDelta         from sympy.functions.special.error_functions import Chi         return {KroneckerDelta: [greek_unicode['delta'], 'delta'],                 gamma: [greek_unicode['Gamma'], 'Gamma'],                lerchphi: [greek_unicode['Phi'], 'lerchphi'],                 lowergamma: [greek_unicode['gamma'], 'gamma'],                 beta: [greek_unicode['Beta'], 'B'],                 DiracDelta: [greek_unicode['delta'], 'delta'],

Add pretty printing functionality for lerchphi fuction <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. ". See .--Added functionality to pretty print lerchphi function in Fixes the lerchphi part of . <!-- Write the release notes for this release below. See for more information on how to write release notes. If there is no release notes entry for this PR, write "NO ENTRY". The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --NO ENTRY <!-- END RELEASE NOTES --


Question: # GeometryEntity is based on Tuple but should not print like a Tuple         return self.emptyPrinter(expr) <ins>    def _print_lerchphi(self, e):        func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi'        return self._print_Function(e, func_name=func_name)</ins>     def _print_Lambda(self, e):         vars, expr = e.args         if self._use_unicode:


Question: return mrow      def _print_Symbol(self, sym, style='plain'):<del>        x = self.dom.createElement('mi')        if style == 'bold':            x.setAttribute('mathvariant', 'bold')</del>         def join(items):             if len(items) > 1:                 mrow = self.dom.createElement('mrow')

A symbol ending with a number is made invisible when printing with MathML A variable with a number, such as x1, is made invisible when printing in a MathML format. import sympy from import mathml x2, y, z = sympy.symbols('x2 y z') y = x2z+x23 f = open('', 'w') f.write('\n') f.write('\n') f.write('\n') f.write('\n') f.write((y, printer='presentation')+'\n') f.write('\n') f.write('\n') f.write('\n') f.close() Viewing the output in Safari 12.0.2: <img width="93" alt="screen shot 2018-12-31 at 12 21 00 pm" src="https://user-"If 'x' is used instead of 'x2', it works as expected: x, y, z = sympy.symbols('x y z') y = xz+x3 <img width="78" alt="screen shot 2018-12-31 at 12 26 24 pm" src="https://user-"BTW, I'm on a MacBook Pro, OS 10.14.2, Sympy 1.3, in Eclipse 2018-19, and Python 3.7.


Question: mname.appendChild(self.dom.createTextNode(name))         if len(supers) == 0:             if len(subs) == 0:                x.appendChild(self.dom.createTextNode(name))                x = mname             else:                msub = self.dom.createElement('msub')                msub.appendChild(mname)                msub.appendChild(join(subs))                x.appendChild(msub)                x = self.dom.createElement('msub')                x.appendChild(mname)                x.appendChild(join(subs))         else:             if len(subs) == 0:                msup = self.dom.createElement('msup')                msup.appendChild(mname)                msup.appendChild(join(supers))                x.appendChild(msup)                x = self.dom.createElement('msup')                x.appendChild(mname)                x.appendChild(join(supers))             else:                msubsup = self.dom.createElement('msubsup')                msubsup.appendChild(mname)                msubsup.appendChild(join(subs))                msubsup.appendChild(join(supers))                x.appendChild(msubsup)                x = self.dom.createElement('msubsup')                x.appendChild(mname)                x.appendChild(join(subs))                x.appendChild(join(supers))        # Set bold font?        if style == 'bold':            x.setAttribute('mathvariant', 'bold')         return x      def _print_MatrixSymbol(self, sym):


Question: if requires_partial(e):             diff_symbol = 'partialdiff'         x.appendChild(self.dom.createElement(diff_symbol))         x_1 = self.dom.createElement('bvar')        for sym in e.variables:        for sym, times in reversed(e.variable_count):             x_1.appendChild(self._print(sym))            if times > 1:                degree = self.dom.createElement('degree')                degree.appendChild(self._print(sympify(times)))                x_1.appendChild(degree)          x.appendChild(x_1)         x.appendChild(self._print(e.expr))

MathML presentation printing of multiple derivatives messed up Currently, the MathML presentation printed version of the expression looks like: ! while a proper rending would be more along the lines of the LaTeX equivalent: ! Hence, the method should be improved, first and foremost to print all the derivative variables on a single line and to get the correct power in the numerator. It is also preferred if the actual function ends up on a separate line (not sure if there is some logic to tell when this should or should not happen). If possible, the logic to group adjacent identical terms can be applied, see the discussion and code in which gives an idea of how to implement it. [To be closed] Added printderivative2 methods from <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. ". See . Please also write a comment on that issue linking back to this pull request once it is open. -- As the attached diff in was pretty large due to line endings, I extracted the interesting parts, the methods for LaTex, pretty and MathML printers. Not sure what to do with it. It looked quite promising in the original PR. Maybe one should have a switch to select between these two methods of printing? I have not checked the code more than modifying it to work with current Python and sympy version, at least from a "no-static-warnings-in-Spyder"-perspective. <!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --NO ENTRY <!-- END RELEASE NOTES --MathML presentation printing of multiple derivatives messed up Currently, the MathML presentation printed version of the expression looks like: ! while a proper rending would be more along the lines of the LaTeX equivalent: ! Hence, the method should be improved, first and foremost to print all the derivative variables on a single line and to get the correct power in the numerator. It is also preferred if the actual function ends up on a separate line (not sure if there is some logic to tell when this should or should not happen).


Question: if requires_partial(e):             diff_symbol = 'partialdiff'         x.appendChild(self.dom.createElement(diff_symbol))         x_1 = self.dom.createElement('bvar')        for sym in e.variables:        for sym, times in reversed(e.variable_count):             x_1.appendChild(self._print(sym))            if times > 1:                degree = self.dom.createElement('degree')                degree.appendChild(self._print(sympify(times)))                x_1.appendChild(degree)          x.appendChild(x_1)         x.appendChild(self._print(e.expr))

If possible, the logic to group adjacent identical terms can be applied, see the discussion and code in which gives an idea of how to implement it.


Question: return x      def _print_Derivative(self, e):        mrow = self.dom.createElement('mrow')        x = self.dom.createElement('mo')         if requires_partial(e):            x.appendChild(self.dom.createTextNode('∂'))            y = self.dom.createElement('mo')            y.appendChild(self.dom.createTextNode('∂'))            d = '∂'         else:            x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))            y = self.dom.createElement('mo')            y.appendChild(self.dom.createTextNode(self.mathml_tag(e)))        brac = self.dom.createElement('mfenced')        brac.appendChild(self._print(e.expr))        mrow = self.dom.createElement('mrow')        mrow.appendChild(x)        mrow.appendChild(brac)        for sym in e.variables:            frac = self.dom.createElement('mfrac')            m = self.dom.createElement('mrow')            x = self.dom.createElement('mo')            if requires_partial(e):                x.appendChild(self.dom.createTextNode('∂'))            d = self.mathml_tag(e)        # Determine denominator        m = self.dom.createElement('mrow')        dim = 0 # Total diff dimension, for numerator        for sym, num in reversed(e.variable_count):            dim += num            if num >= 2:                x = self.dom.createElement('msup')                xx = self.dom.createElement('mo')                xx.appendChild(self.dom.createTextNode(d))                x.appendChild(xx)                x.appendChild(self._print(num))             else:                x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))            y = self._print(sym)                x = self.dom.createElement('mo')                x.appendChild(self.dom.createTextNode(d))             m.appendChild(x)            y = self._print(sym)             m.appendChild(y)            frac.appendChild(mrow)            frac.appendChild(m)            mrow = frac         return frac        mnum = self.dom.createElement('mrow')        if dim >= 2:            x = self.dom.createElement('msup')            xx = self.dom.createElement('mo')            xx.appendChild(self.dom.createTextNode(d))            x.appendChild(xx)            x.appendChild(self._print(dim))        else:            x = self.dom.createElement('mo')            x.appendChild(self.dom.createTextNode(d))        mnum.appendChild(x)        mrow = self.dom.createElement('mrow')        frac = self.dom.createElement('mfrac')        frac.appendChild(mnum)        frac.appendChild(m)        mrow.appendChild(frac)        # Print function        mrow.appendChild(self._print(e.expr))        return mrow      def _print_Function(self, e):         mrow = self.dom.createElement('mrow')


Question: return x      def _print_Derivative(self, e):        mrow = self.dom.createElement('mrow')        x = self.dom.createElement('mo')         if requires_partial(e):            x.appendChild(self.dom.createTextNode('∂'))            y = self.dom.createElement('mo')            y.appendChild(self.dom.createTextNode('∂'))            d = '∂'         else:            x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))            y = self.dom.createElement('mo')            y.appendChild(self.dom.createTextNode(self.mathml_tag(e)))        brac = self.dom.createElement('mfenced')        brac.appendChild(self._print(e.expr))        mrow = self.dom.createElement('mrow')        mrow.appendChild(x)        mrow.appendChild(brac)        for sym in e.variables:            frac = self.dom.createElement('mfrac')            m = self.dom.createElement('mrow')            x = self.dom.createElement('mo')            if requires_partial(e):                x.appendChild(self.dom.createTextNode('∂'))            d = self.mathml_tag(e)        # Determine denominator        m = self.dom.createElement('mrow')        dim = 0 # Total diff dimension, for numerator        for sym, num in reversed(e.variable_count):            dim += num            if num >= 2:                x = self.dom.createElement('msup')                xx = self.dom.createElement('mo')                xx.appendChild(self.dom.createTextNode(d))                x.appendChild(xx)                x.appendChild(self._print(num))             else:                x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))            y = self._print(sym)                x = self.dom.createElement('mo')                x.appendChild(self.dom.createTextNode(d))             m.appendChild(x)            y = self._print(sym)             m.appendChild(y)            frac.appendChild(mrow)            frac.appendChild(m)            mrow = frac         return frac        mnum = self.dom.createElement('mrow')        if dim >= 2:            x = self.dom.createElement('msup')            xx = self.dom.createElement('mo')            xx.appendChild(self.dom.createTextNode(d))            x.appendChild(xx)            x.appendChild(self._print(dim))        else:            x = self.dom.createElement('mo')            x.appendChild(self.dom.createTextNode(d))        mnum.appendChild(x)        mrow = self.dom.createElement('mrow')        frac = self.dom.createElement('mfrac')        frac.appendChild(mnum)        frac.appendChild(m)        mrow.appendChild(frac)        # Print function        mrow.appendChild(self._print(e.expr))        return mrow      def _print_Function(self, e):         mrow = self.dom.createElement('mrow')


Question: from .applyfunc import ElementwiseApplyFunction         return ElementwiseApplyFunction(func, self) <ins>    def _eval_Eq(self, other):        if not isinstance(other, MatrixExpr):            return False        if self.shape != other.shape:            return False        if (self - other).is_ZeroMatrix:            return True        return Eq(self, other, evaluate=False)</ins>  def _matrix_derivative(expr, x):     from sympy import Derivative

Fix Matrix Equality and MatrixExpr <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. -- <!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. ". See . Please also write a comment on that issue linking back to this pull request once it is open. --Test case for equality in matrices. <!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --matrices test for equality in matrices <!-- END RELEASE NOTES --


Question: from __future__ import print_function, division from sympy.core.assumptions import StdFactKB, _assume_defined from sympy.core import Expr, Tuple, Symbol, sympify, S from sympy.core.compatibility import (is_sequence, string_types, NotIterable,                                       Iterable)from sympy.core.logic import fuzzy_bool from sympy.core.sympify import _sympify from sympy.functions.special.tensor_functions import KroneckerDelta

Make assumptions about indexed symbols I think this should be possible to do: Without assumptions, it's hard to do algebra with indexed symbols, e.g., get to simplify to . I understand that the class Indexed inherits from Expr, not from Symbol, and there are no assumptions on Expr. Still, we already have some quasi-assumptions on Indexed and IndexedBase in the form of class property. And the objects of class Idx, which also inherits from Expr, have them in the form as . Could parse and use the that it accepts, instead of trying to pass them to ? Optionally, maybe even could do that, so an assumption can be to a particular indexed object? By the way, any attempt to pass to is a potential bug because this method, inherited from , does not accept any keyword arguments.


Question: >>> Indexed('A', i, j)     A[i, j]     It is recommended that ``Indexed`` objects be created via ``IndexedBase``:    It is recommended that ``Indexed`` objects be created by indexing ``IndexedBase``:    ``IndexedBase('A')[i, j]`` instead of ``Indexed(IndexedBase('A'), i, j)``.      >>> A = IndexedBase('A')    >>> Indexed('A', i, j) == A[i, j]    >>> a_ij = A[i, j]           # Prefer this,    >>> b_ij = Indexed(A, i, j)  # over this.    >>> a_ij == b_ij     True      """


Question: is_symbol = True     is_Atom = True <ins></ins>     def __new__(cls, base, *args, **kw_args):         from sympy.utilities.misc import filldedent         from sympy.tensor.array.ndim_array import NDimArray


Question: else:                 return base[args]         return Expr.__new__(cls, base, *args, **kw_args)        obj = Expr.__new__(cls, base, *args, **kw_args)        try:            IndexedBase._set_assumptions(obj, base.assumptions0)        except AttributeError:            IndexedBase._set_assumptions(obj, {})        return obj    def _hashable_content(self):        return super(Indexed, self)._hashable_content() + tuple(sorted(self.assumptions0.items()))      @property     def name(self):


Question: return S.NaN             return S.Zero <ins>    @property    def assumptions0(self):        return {k: v for k, v in self._assumptions.items() if v is not None}</ins>     @property     def base(self):         """Returns the ``IndexedBase`` of the ``Indexed`` object.


Question: >>> B[i, j].shape     (o, p)     Assumptions can be specified with keyword arguments the same way as for Symbol:    >>> A_real = IndexedBase('A', real=True)    >>> A_real.is_real    True    >>> A != A_real    True     """     is_commutative = True     is_symbol = True     is_Atom = True     @staticmethod    def _filter_assumptions(kw_args):        """Split the given dict into two parts: assumptions and not assumptions.           Keys are taken as assumptions if they correspond to an entry in ``_assume_defined``."""        assumptions = {k: v for k, v in kw_args.items() if k in _assume_defined}        Symbol._sanitize(assumptions)        # return assumptions, not assumptions        return assumptions, {k: v for k, v in kw_args.items() if k not in assumptions}    @staticmethod    def _set_assumptions(obj, assumptions):        """Set assumptions on obj, making sure to apply consistent values."""        tmp_asm_copy = assumptions.copy()        is_commutative = fuzzy_bool(assumptions.get('commutative', True))        assumptions['commutative'] = is_commutative        obj._assumptions = StdFactKB(assumptions)        obj._assumptions._generator = tmp_asm_copy  # Issue #8873     def __new__(cls, label, shape=None, **kw_args):         from sympy import MatrixBase, NDimArray


Question: obj._offset = offset         obj._strides = strides         obj._name = str(label)        assumptions, _ = IndexedBase._filter_assumptions(kw_args)        IndexedBase._set_assumptions(obj, assumptions)         return obj      @property     def name(self):         return self._name     def _hashable_content(self):        return super(IndexedBase, self)._hashable_content() + tuple(sorted(self.assumptions0.items()))    @property    def assumptions0(self):        return {k: v for k, v in self._assumptions.items() if v is not None}     def __getitem__(self, indices, **kw_args):         if is_sequence(indices):             # Special case needed because M[*my_tuple] is a syntax error.


Question: return x  <ins>    def _print_tuple(self, e):        x = self.dom.createElement('mfenced')        for i in e:            x.appendChild(self._print(i))        return x    def _print_IndexedBase(self, e):        return self._print(e.label)    def _print_Indexed(self, e):        x = self.dom.createElement('msub')        x.appendChild(self._print(e.base))        if len(e.indices) == 1:            x.appendChild(self._print(e.indices[0]))            return x        x.appendChild(self._print(e.indices))        return x</ins> def mathml(expr, printer='content', **settings):     """Returns the MathML representation of expr. If printer is presentation then      prints Presentation MathML else prints content MathML.

mathml printer for IndexedBase required Writing an object to MathML fails with a exception: : It also fails for more complex expressions where at least one element is Indexed.


Question: return 'SparseArray[{}, {}]'.format(print_data(), print_dims()) <ins>    def _print_ImmutableDenseNDimArray(self, expr):        return self.doprint(expr.tolist())    def _print_ImmutableSparseNDimArray(self, expr):        def print_string_list(string_list):            return '{' + ', '.join(a for a in string_list) + '}'        def to_mathematica_index(*args):            """Helper function to change Python style indexing to            Pathematica indexing.            Python indexing (0, 1 ... n-1)            -> Mathematica indexing (1, 2 ... n)            """            return tuple(i + 1 for i in args)        def print_rule(pos, val):            """Helper function to print a rule of Mathematica"""            return '{} -> {}'.format(self.doprint(pos), self.doprint(val))        def print_data():            """Helper function to print data part of Mathematica            sparse array.            It uses the fourth notation ``SparseArray[data,{d1,d2,…}]``            from            https://reference.wolfram.com/language/ref/SparseArray.html            ``data`` must be formatted with rule.            """            return print_string_list(                [print_rule(                    to_mathematica_index(*(expr._get_tuple_index(key))),                    value)                for key, value in sorted(expr._sparse_array.items())]            )        def print_dims():            """Helper function to print dimensions part of Mathematica            sparse array.            It uses the fourth notation ``SparseArray[data,{d1,d2,…}]``            from            https://reference.wolfram.com/language/ref/SparseArray.html            """            return self.doprint(expr.shape)        return 'SparseArray[{}, {}]'.format(print_data(), print_dims())</ins>     def _print_Function(self, expr):         if expr.func.__name__ in self.known_functions:             cond_mfunc = self.known_functions[expr.func.__name__]

Mathematica code: allow printing of matrices and arrays. Our printers for Wolfram Mathematica do not support matrices and arrays. We should add support for it.


Question: for lim in expr.limits:             width = (func_height + 2) * 5 // 3 - 2            sign_lines = []            sign_lines.append(corner_chr + (horizontal_chr*width) + corner_chr)            for i in range(func_height + 1):                sign_lines.append(vertical_chr + (' '*width) + vertical_chr)            sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr]            for _ in range(func_height + 1):                sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ')              pretty_sign = stringPict('')             pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines))

Product pretty print could be improved This is what the pretty printing for looks like: (if those don't look good in your browser copy paste them into the terminal) This could be improved: Why is there always an empty line at the bottom of the ∏? Keeping everything below the horizontal line is good, but the bottom looks asymmetric, and it makes the ∏ bigger than it needs to be. The ∏ is too fat IMO. It might look better if we extended the top bar. I'm unsure about this. Compare this That's still almost twice as wide as the equivalent Sum, but if you make it much skinnier it starts to look bad.


Question: local_decs = []             for arg, val in py_inf.items():                 proto = self._prototype_arg(arg)                mat, ind = val                mat, ind = [self._string_var(v) for v in val]                 local_decs.append("    cdef {0} = {1}.shape[{2}]".format(proto, mat, ind))             local_decs.extend(["    cdef {0}".format(self._declare_arg(a)) for a in py_loc])             declarations = "\n".join(local_decs)

Issue ufuncifying a two argument function with the Cython backend It works if the function just has one argument, or if you use a different backend. Issue ufuncifying a two argument function with the Cython backend It works if the function just has one argument, or if you use a different backend.


Question: # Function Body             args_c = ", ".join([self._call_arg(a) for a in routine.arguments])            rets = ", ".join([str(r.name) for r in py_rets])            rets = ", ".join([self._string_var(r.name) for r in py_rets])             if routine.results:                 body = '    return %s(%s)' % (routine.name, args_c)                 if rets:


Question: self._need_numpy = True             ndim = len(arg.dimensions)             mtype = np_types[t]            return mat_dec.format(mtype=mtype, ndim=ndim, name=arg.name)            return mat_dec.format(mtype=mtype, ndim=ndim, name=self._string_var(arg.name))         else:            return "%s %s" % (t, str(arg.name))            return "%s %s" % (t, self._string_var(arg.name))      def _declare_arg(self, arg):         proto = self._prototype_arg(arg)         if arg.dimensions:            shape = '(' + ','.join(str(i[1] + 1) for i in arg.dimensions) + ')'            shape = '(' + ','.join(self._string_var(i[1] + 1) for i in arg.dimensions) + ')'             return proto + " = np.empty({shape})".format(shape=shape)         else:             return proto + " = 0"


Question: def _call_arg(self, arg):         if arg.dimensions:             t = arg.get_datatype('c')            return "<{0}*> {1}.data".format(t, arg.name)            return "<{0}*> {1}.data".format(t, self._string_var(arg.name))         elif isinstance(arg, ResultBase):            return "&{0}".format(arg.name)            return "&{0}".format(self._string_var(arg.name))         else:            return str(arg.name)            return self._string_var(arg.name)    def _string_var(self, var):        printer = self.generator.printer.doprint        return printer(var)   class F2PyCodeWrapper(CodeWrapper):


Question: return True             if self.exp.is_odd:                 return False<ins>        elif self.base.is_zero:            if self.exp.is_real:                return self.exp.is_zero</ins>         elif self.base.is_nonpositive:             if self.exp.is_odd:                 return False

S(0)real(!=0) should be (0 or zoo) and hence non-positive. Consider the following code from master: Since (where a is real and non-zero) should always be (0 or ). Therefore, the result should have been .


Question: elif self.base.is_positive:             if self.exp.is_real:                 return False<ins>        elif self.base.is_zero:            if self.exp.is_real:                return False</ins>         elif self.base.is_nonnegative:             if self.exp.is_nonnegative:                 return False


Question: vector_names = list(vector_names)         latex_vects = [(r'\mathbf{\hat{%s}_{%s}}' % (x, name)) for                            x in vector_names]        pretty_vects = [(name + '_' + x) for x in vector_names]        pretty_vects = ['%s_%s' % (x, name) for x in vector_names]          obj._vector_names = vector_names

latex printing of BaseScalar It appears that the subscript and script are reversed here for the latex form of BaseScalar:


Question: variable_names = list(variable_names)         latex_scalars = [(r"\mathbf{{%s}_{%s}}" % (x, name)) for                          x in variable_names]        pretty_scalars = [(name + '_' + x) for x in variable_names]        pretty_scalars = ['%s_%s' % (x, name) for x in variable_names]          obj._variable_names = variable_names         obj._vector_names = vector_names


Question: 100.0      Float can automatically count significant figures if a null string    is sent for the precision; space are also allowed in the string. (Auto-    is sent for the precision; spaces or underscores are also allowed. (Auto-     counting is only allowed for strings, ints and longs).     >>> Float('123 456 789 . 123 456', '')    >>> Float('123 456 789.123_456', '')     123456789.123456     >>> Float('12e-3', '')     0.012

Float from string with underscores misplaces decimal point This is correct: None of these are: I think this is an upstream bug in mpmath:


Question: 'Supply only one. ')          if isinstance(num, string_types):            # Float already accepts spaces as digit separators; in Py 3.6            # underscores are allowed. In anticipation of that, we ignore            # legally placed underscores             num = num.replace(' ', '')            if '_' in num:                if num.startswith('_') or num.endswith('_') or any(                        i in num for i in ('__', '_.', '._')):                    # copy Py 3.6 error                    raise ValueError("could not convert string to float: '%s'" % num)                num = num.replace('_', '')             if num.startswith('.') and len(num) > 1:                 num = '0' + num             elif num.startswith('-.') and len(num) > 2:


Question: eq[i] = e.subs(reps)         return f(eq), {r: s for s, r in reps.items()}     reps = {s: Dummy(s.name, positive=True)    reps = {s: Dummy(s.name, positive=True, **s.assumptions0)                  for s in eq.free_symbols if s.is_positive is None}     eq = eq.subs(reps)     return eq, {r: s for s, r in reps.items()}

Posify ignores is_finite assmptions Posify removes a finite assumption from a symbol: I think that posify should preserve the finiteness assumption. Possibly other assumptions should be preserved as well (integer, rational, prime, even, odd...).


Question: return self._print(expr.base, exp=self._print(expr.exp))             else:                 tex = r"%s^{%s}"                exp = self._print(expr.exp)                # issue #12886: add parentheses around superscripts raised                # to powers                base = self.parenthesize(expr.base, PRECEDENCE['Pow'])                if '^' in base and expr.base.is_Symbol:                    base = r"\left(%s\right)" % base                elif (isinstance(expr.base, Derivative)                        and base.startswith(r'\left(')                        and re.match(r'\\left\(\\d?d?dot', base)                        and base.endswith(r'\right)')):                    # don't use parentheses around dotted derivative                    base = base[6: -7]  # remove outermost added parens                return tex % (base, exp)                return self._helper_print_standard_power(expr, tex)    def _helper_print_standard_power(self, expr, template):        exp = self._print(expr.exp)        # issue #12886: add parentheses around superscripts raised        # to powers        base = self.parenthesize(expr.base, PRECEDENCE['Pow'])        if '^' in base and expr.base.is_Symbol:            base = r"\left(%s\right)" % base        elif (isinstance(expr.base, Derivative)            and base.startswith(r'\left(')            and re.match(r'\\left\(\\d?d?dot', base)            and base.endswith(r'\right)')):            # don't use parentheses around dotted derivative            base = base[6: -7]  # remove outermost added parens        return template % (base, exp)      def _print_UnevaluatedExpr(self, expr):         return self._print(expr.args[0])

Add LaTeX and pretty printers for HadamardPower Furthermore, HadamardProduct may be extended to support the division symbol. [ ] Add latex printer [ ] Add mathml printer [ ] Add pretty printer


Question: if not isinstance(mat, MatrixSymbol):             return r"\left(%s\right)^{T}" % self._print(mat)         else:            return "%s^{T}" % self._print(mat)            return "%s^{T}" % self.parenthesize(mat, precedence_traditional(expr), True)      def _print_Trace(self, expr):         mat = expr.arg


Question: self._print(expr.args[1]))      def _print_HadamardProduct(self, expr):        from sympy import Add, MatAdd, MatMul        args = expr.args        prec = PRECEDENCE['Pow']        parens = self.parenthesize        return r' \circ '.join(            map(lambda arg: parens(arg, prec, strict=True), args))         def parens(x):            if isinstance(x, (Add, MatAdd, MatMul)):                return r"\left(%s\right)" % self._print(x)            return self._print(x)        return r' \circ '.join(map(parens, expr.args))    def _print_HadamardPower(self, expr):        template = r"%s^{\circ {%s}}"        return self._helper_print_standard_power(expr, template)      def _print_KroneckerProduct(self, expr):        from sympy import Add, MatAdd, MatMul        args = expr.args        prec = PRECEDENCE['Pow']        parens = self.parenthesize         def parens(x):            if isinstance(x, (Add, MatAdd, MatMul)):                return r"\left(%s\right)" % self._print(x)            return self._print(x)        return r' \otimes '.join(map(parens, expr.args))        return r' \otimes '.join(            map(lambda arg: parens(arg, prec, strict=True), args))      def _print_MatPow(self, expr):         base, exp = expr.base, expr.exp         from sympy.matrices import MatrixSymbol         if not isinstance(base, MatrixSymbol):            return r"\left(%s\right)^{%s}" % (self._print(base),            return "\\left(%s\\right)^{%s}" % (self._print(base),                                               self._print(exp))         else:             return "%s^{%s}" % (self._print(base), self._print(exp))diff --git a/sympy/printing/precedence.py b/sympy/printing/precedence.py-- a/sympy/printing/precedence.py++ b/sympy/printing/precedence.py


Question: # A dictionary assigning precedence values to certain classes. These values are # treated like they were inherited, so not every single class has to be named # here.<ins># Do not use this with printers other than StrPrinter</ins> PRECEDENCE_VALUES = {     "Equivalent": PRECEDENCE["Xor"],     "Xor": PRECEDENCE["Xor"],


Question: def precedence(item):    """    Returns the precedence of a given object.    """Returns the precedence of a given object.    This is the precedence for StrPrinter.     """     if hasattr(item, "precedence"):         return item.precedence


Question: def precedence_traditional(item):    """    Returns the precedence of a given object according to the traditional rules    of mathematics. This is the precedence for the LaTeX and pretty printer.    """Returns the precedence of a given object according to the    traditional rules of mathematics.    This is the precedence for the LaTeX and pretty printer.     """     # Integral, Sum, Product, Limit have the precedence of Mul in LaTeX,     # the precedence of Atom for other printers:    from sympy import Integral, Sum, Product, Limit, Derivative    from sympy import Integral, Sum, Product, Limit, Derivative, Transpose, Adjoint     from sympy.core.expr import UnevaluatedExpr     from sympy.tensor.functions import TensorProduct      if isinstance(item, (Integral, Sum, Product, Limit, Derivative, TensorProduct)):         return PRECEDENCE["Mul"]    if (item.__class__.__name__ in ("Dot", "Cross", "Gradient", "Divergence",    elif isinstance(item, (Transpose, Adjoint)):        return PRECEDENCE["Pow"]    elif (item.__class__.__name__ in ("Dot", "Cross", "Gradient", "Divergence",                                     "Curl", "Laplacian")):         return PRECEDENCE["Mul"]-1     elif isinstance(item, UnevaluatedExpr):


Question: for i in reversed(range(1, d)):                     lines.append('%s/%s' % (' '*i, ' '*(w - i)))                 lines.append("/" + "_"*(w - 1) + ',')                return d, h + more, lines, 0                return d, h + more, lines, more             else:                 w = w + more                 d = d + more

Bad centering for Sum pretty print The and the should be aligned. I'm not sure if the should be lower of if the should be higher.


Question: if first:                 # change F baseline so it centers on the sign                 prettyF.baseline -= d - (prettyF.height()//2 -                                         prettyF.baseline) - adjustment                                         prettyF.baseline)                 first = False              # put padding to the right


Question: # put the present prettyF to the right             prettyF = prettyForm(*prettySign.right(prettyF))         prettyF.baseline = max_upper + sign_height//2        # adjust baseline of ascii mode sigma with an odd height so that it is        # exactly through the center        ascii_adjustment = ascii_mode if not adjustment else 0        prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment         prettyF.binding = prettyForm.MUL         return prettyF


Question: """         if isinstance(factors, (SYMPY_INTS, float)):             factors = S(factors)<del></del>         if isinstance(factors, Factors):             factors = factors.factors.copy()         elif factors is None or factors is S.One:

collectconst() does cannot collect rationals does not seem to support the collecting of numeric rationals in SymPy 1.3. This is probably a duplicate of , but I've provided a description below. In [41]: var('a:d') In [42]: f = a + b + c / 2 + d / 2 In [43]: print(collect_const(f, Rational(1, 2), Numbers=True)) a + b + (c/2 + d/2) I'm expecting


Question: for _ in range(i):                 c.remove(I)             factors = dict(Mul._from_args(c).as_powers_dict())<ins>            # Handle all rational Coefficients            for f in list(factors.keys()):                if isinstance(f, Rational) and not isinstance(f, Integer):                    p, q = Integer(f.p), Integer(f.q)                    factors[p] = (factors[p] if p in factors else 0) + factors[f]                    factors[q] = (factors[q] if q in factors else 0) - factors[f]                    factors.pop(f)</ins>             if i:                 factors[I] = S.One*i             if nc:


Question: import ast import unicodedata from sympy.core.compatibility import exec_, StringIOfrom sympy.core.compatibility import exec_, StringIO, iterable from sympy.core.basic import Basic from sympy.core import Symbolfrom sympy.core.function import arityfrom sympy.utilities.misc import filldedent, func_name  def _token_splittable(token):     """

parsing expressions with powers from sympy.parsing.sympyparser import ( parseexpr, standardtransformations, implicitmultiplicationapplication, ) and if i will do something with expr1 and expr2 i will get wrong results: print(expr1 - expr2) --6n - 3n*2n # Not Zero!!! i have tried simplify, powsimp (force=True too), powdenest, also i have tried create var('n', positive=True, integer=True) and set parameter localdict into parseexpr and use another transformations in parsing, but i could not get 0. Maybe somebody tell me how i can get zero after expr1 - expr2? Thank you


Question: result = []         split = False         split_previous=False         for tok in tokens:             if split_previous:                 # throw out closing parenthesis of Symbol that was split                 split_previous=False                 continue             split_previous=False             if tok[0] == NAME and tok[1] in ['Symbol', 'Function']:                 split = True             elif split and tok[0] == NAME:                 symbol = tok[1][1:-1]                 if predicate(symbol):                     tok_type = result[-2][1]  # Symbol or Function                     del result[-2:]  # Get rid of the call to Symbol                    for char in symbol[:-1]:                    i = 0                    while i < len(symbol):                        char = symbol[i]                         if char in local_dict or char in global_dict:                             result.extend([(NAME, "%s" % char)])                        elif char.isdigit():                            char = [char]                            for i in range(i + 1, len(symbol)):                                if not symbol[i].isdigit():                                  i -= 1                                  break                                char.append(symbol[i])                            char = ''.join(char)                            result.extend([(NAME, 'Number'), (OP, '('),                                           (NAME, "'%s'" % char), (OP, ')')])                         else:                            result.extend([(NAME, 'Symbol'), (OP, '('),                            use = tok_type if i == len(symbol) else 'Symbol'                            result.extend([(NAME, use), (OP, '('),                                            (NAME, "'%s'" % char), (OP, ')')])                    char = symbol[-1]                    if char in local_dict or char in global_dict:                        result.extend([(NAME, "%s" % char)])                    else:                        result.extend([(NAME, tok_type), (OP, '('),                                       (NAME, "'%s'" % char), (OP, ')')])                        i += 1                      # Set split_previous=True so will skip                     # the closing parenthesis of the original Symbol                     split = False                     split_previous = True                     continue                 else:                     split = False             result.append(tok)         return result     return _split_symbols


Question: return result <ins></ins> def repeated_decimals(tokens, local_dict, global_dict):     """     Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90)


Question: return result <ins></ins> def auto_number(tokens, local_dict, global_dict):     """     Converts numeric literals to use SymPy equivalents.


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


Question: if local_dict is None:         local_dict = {}    elif not isinstance(local_dict, dict):        raise TypeError('expecting local_dict to be a dict')      if global_dict is None:         global_dict = {}         exec_('from sympy import *', global_dict)    elif not isinstance(global_dict, dict):        raise TypeError('expecting global_dict to be a dict')    transformations = transformations or ()    if transformations:        if not iterable(transformations):            raise TypeError(                '`transformations` should be a list of functions.')        for _ in transformations:            if not callable(_):                raise TypeError(filldedent('''                    expected a function in `transformations`,                    not %s''' % func_name(_)))            if arity(_) != 3:                raise TypeError(filldedent('''                    a transformation should be function that                    takes 3 arguments'''))     code = stringify_expr(s, local_dict, global_dict, transformations)      if not evaluate:


Question: if self.intersection(o) != []:             return S.Zero         if isinstance(o, Point3D):           x, y, z = map(Dummy, 'xyz')           k = self.equation(x, y, z)           a, b, c = [k.coeff(i) for i in (x, y, z)]           d = k.xreplace({x: o.args[0], y: o.args[1], z: o.args[2]})           t = abs(d/sqrt(a**2 + b**2 + c**2))           return t        if isinstance(o, LinearEntity3D):            a, b = o.p1, self.p1            c = Matrix(a.direction_ratio(b))            d = Matrix(self.normal_vector)            e = c.dot(d)            f = sqrt(sum([i**2 for i in self.normal_vector]))            return abs(e / f)        if isinstance(o, Plane):            a, b = o.p1, self.p1            c = Matrix(a.direction_ratio(b))            d = Matrix(self.normal_vector)            e = c.dot(d)            f = sqrt(sum([i**2 for i in self.normal_vector]))            return abs(e / f)        if isinstance(o, (Segment3D, Ray3D)):            a, b = o.p1, o.p2            pi, = self.intersection(Line3D(a, b))            if pi in o:                return self.distance(pi)            elif a in Segment3D(pi, b):                return self.distance(a)            else:                assert isinstance(o, Segment3D) is True                return self.distance(b)        # following code handles `Point3D`, `LinearEntity3D`, `Plane`        a = o if isinstance(o, Point3D) else o.p1        n = Point3D(self.normal_vector).unit        d = (a - self.p1).dot(n)        return abs(d)       def equals(self, o):

Intersection between Plane and Segment3D returns points outside of the segment It seems to me that, as far as ), and so additional intersections that aren't actually within the segment are returned: The expected result is of course that returns an empty list in this case. An easy workaround for the time being is to just filter these out manually: But it would be nice if this could be fixed in sympy itself. Version info: Python 3.5.3 Sympy 1.2-522-g0b350a21a () Updated intersection method in class Plane Updated the isinstance(o, (LinearEntity, LinearEntity3D)) part of intersection method in Plane class so that the returned points lie in both the intersection objects. <!-- BEGIN RELEASE NOTES --geometry updated the intersection method of plane class so that intersection points lie in both the intersection objects if the other entity is LinearEntity. <!-- END RELEASE NOTES --


Question: raise ValueError('unhandled linear entity: %s' % o.func)                 return [o]             else:                x, y, z = map(Dummy, 'xyz')                 t = Dummy()  # unnamed else it may clash with a symbol in o                 a = Point3D(o.arbitrary_point(t))                b = self.equation(x, y, z)                p1, n = self.p1, Point3D(self.normal_vector)                  # TODO: Replace solve with solveset, when this line is tested                c = solve(b.subs(list(zip((x, y, z), a.args))), t)                c = solve((a - p1).dot(n), t)                 if not c:                     return []                 else:                     p = a.subs(t, c[0])                    if p not in self:                    if p not in o:                         return []  # e.g. a segment might not intersect a plane                     return [p]         if isinstance(o, Plane):


Question: PREC = precedence(expr)         return self._operators['not'] + self.parenthesize(expr.args[0], PREC) <ins>    def _print_Indexed(self, expr):        base = expr.args[0]        index = expr.args[1:]        return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))</ins>  for k in PythonCodePrinter._kf:     setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func)

PythonCodePrinter doesn't support Indexed I use to generate some functions and save the code for further use. But the generated code for operation has some warnings which can be confirmed by following code; the output is We should add following method to :


Question: from sympy.core.compatibility import default_sort_key from sympy.core.add import Add from sympy.core.mul import Mul<ins>from sympy.printing.repr import srepr</ins>  __all__ = ['dotprint']

dotprint doesn't use the correct order for x2 The dot diagram in the tutorial is wrong (). It shows but it should show since it represents , not . I can't figure out how to make dot give the vertices in the right order. Whatever the fix is, we should fix this in the dot printer as well as the tutorial.


Question: (Expr,  {'color': 'black'}))  sort_classes = (Add, Mul) slotClasses = (Symbol, Integer, Rational, Float)# XXX: Why not just use srepr()?def purestr(x):def purestr(x, with_args=False):     """ A string that follows obj = type(obj)(*obj.args) exactly """    sargs = ()     if not isinstance(x, Basic):        return str(x)    if type(x) in slotClasses:        args = [getattr(x, slot) for slot in x.__slots__]    elif type(x) in sort_classes:        args = sorted(x.args, key=default_sort_key)        rv = str(x)    elif not x.args:        rv = srepr(x)     else:         args = x.args    return "%s(%s)"%(type(x).__name__, ', '.join(map(purestr, args)))        if isinstance(x, Add) or \                isinstance(x, Mul) and x.is_commutative:            args = sorted(args, key=default_sort_key)        sargs = tuple(map(purestr, args))        rv = "%s(%s)"%(type(x).__name__, ', '.join(sargs))    if with_args:        rv = rv, sargs    return rv   def styleof(expr, styles=default_styles):


Question: style.update(sty)     return style <ins></ins> def attrprint(d, delimiter=', '):     """ Print a dictionary of attributes


Question: """     return delimiter.join('"%s"="%s"'%item for item in sorted(d.items())) <ins></ins> def dotnode(expr, styles=default_styles, labelfunc=str, pos=(), repeat=True):     """ String defining a node


Question: >>> from sympy.printing.dot import dotnode     >>> from sympy.abc import x     >>> print(dotnode(x))    "Symbol(x)_()" ["color"="black", "label"="x", "shape"="ellipse"];    "Symbol('x')_()" ["color"="black", "label"="x", "shape"="ellipse"];     """     style = styleof(expr, styles)


Question: >>> from sympy.abc import x     >>> for e in dotedges(x+2):     ...     print(e)    "Add(Integer(2), Symbol(x))_()" -> "Integer(2)_(0,)";    "Add(Integer(2), Symbol(x))_()" -> "Symbol(x)_(1,)";    "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";    "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";     """    from sympy.utilities.misc import func_name     if atom(expr):         return []     else:        # TODO: This is quadratic in complexity (purestr(expr) already        # contains [purestr(arg) for arg in expr.args]).        expr_str = purestr(expr)        arg_strs = [purestr(arg) for arg in expr.args]        expr_str, arg_strs = purestr(expr, with_args=True)         if repeat:             expr_str += '_%s' % str(pos)            arg_strs = [arg_str + '_%s' % str(pos + (i,)) for i, arg_str in enumerate(arg_strs)]        return ['"%s" -> "%s";' % (expr_str, arg_str) for arg_str in arg_strs]            arg_strs = ['%s_%s' % (a, str(pos + (i,)))                for i, a in enumerate(arg_strs)]        return ['"%s" -> "%s";' % (expr_str, a) for a in arg_strs]  template = \ """digraph{


Question: ``repeat=True``, it will have two nodes for ``x`` and with           ``repeat=False``, it will have one (warning: even if it appears           twice in the same object, like Pow(x, x), it will still only appear          only once.  Hence, with repeat=False, the number of arrows out of an          once.  Hence, with repeat=False, the number of arrows out of an           object might not equal the number of args it has).      ``labelfunc``: How to label leaf nodes.  The default is ``str``.  Another


Question: # Nodes #     #########     <BLANKLINE>    "Add(Integer(2), Symbol(x))_()" ["color"="black", "label"="Add", "shape"="ellipse"];    "Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"];     "Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"];    "Symbol(x)_(1,)" ["color"="black", "label"="x", "shape"="ellipse"];    "Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"];     <BLANKLINE>     #########     # Edges #     #########     <BLANKLINE>    "Add(Integer(2), Symbol(x))_()" -> "Integer(2)_(0,)";    "Add(Integer(2), Symbol(x))_()" -> "Symbol(x)_(1,)";    "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";    "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";     }      """


Question: arg_list = []          # setup input argument list<ins>        # helper to get dimensions for data for array-like args        def dimensions(s):            return [(S.Zero, dim - 1) for dim in s.shape]</ins>         array_symbols = {}         for array in expressions.atoms(Indexed) | local_expressions.atoms(Indexed):             array_symbols[array.base.label] = array

autowrap with cython backend fails when array arguments do not appear in wrapped expr When using the cython backend for autowrap, it appears that the code is not correctly generated when the function in question has array arguments that do not appear in the final expression. A minimal counterexample is: This should of course return but instead fails with: A little inspection reveals that this is because the corresponding C function is generated with an incorrect signature: ( should be , not in this case) I've found that this error won't occur so long as depends at least in part on each argument. For example this slight modification of the above counterexample works perfectly: This may seem like a silly issue ("why even have as an argument if it doesn't appear in the expression you're trying to evaluate?"). But of course in interfacing with external libraries (e.g. for numerical integration), one often needs functions to have a pre-defined signature regardless of whether a given argument contributes to the output. I think I've identified the problem in and will suggest a PR shortly.


Question: for symbol in sorted(symbols, key=str):             if symbol in array_symbols:                dims = []                 array = array_symbols[symbol]                for dim in array.shape:                    dims.append((S.Zero, dim - 1))                metadata = {'dimensions': dims}                metadata = {'dimensions': dimensions(array)}             else:                 metadata = {}


Question: try:                     new_args.append(name_arg_dict[symbol])                 except KeyError:                    new_args.append(InputArgument(symbol))                    if isinstance(symbol, (IndexedBase, MatrixSymbol)):                        metadata = {'dimensions': dimensions(symbol)}                    else:                        metadata = {}                    new_args.append(InputArgument(symbol, **metadata))             arg_list = new_args          return Routine(name, arg_list, return_val, local_vars, global_vars)


Question: def _contains(self, other):         from sympy.matrices import Matrix         from sympy.solvers.solveset import solveset, linsolve<ins>        from sympy.solvers.solvers import solve</ins>         from sympy.utilities.iterables import is_sequence, iterable, cartes         L = self.lamda         if is_sequence(other):

Bug in ImageSet I think we should not use . Reason : It works fine when returns a non-empty set. But when it returns an empty set, an error is raised. As calling on an empty set raises an . This is most likely the reason why this is failing for and passing for Also, why are we type-casting the to a ? Ping Maybe you can help me out here.


Question: solns = list(linsolve([e - val for e, val in                 zip(L.expr, other)], variables))             else:                syms = [e.free_symbols & free for e in eqs]                solns = {}                for i, (e, s, v) in enumerate(zip(eqs, syms, other)):                    if not s:                        if e != v:                            return S.false                        solns[vars[i]] = [v]                        continue                    elif len(s) == 1:                        sy = s.pop()                        sol = solveset(e, sy)                        if sol is S.EmptySet:                            return S.false                        elif isinstance(sol, FiniteSet):                            solns[sy] = list(sol)                try:                    syms = [e.free_symbols & free for e in eqs]                    solns = {}                    for i, (e, s, v) in enumerate(zip(eqs, syms, other)):                        if not s:                            if e != v:                                return S.false                            solns[vars[i]] = [v]                            continue                        elif len(s) == 1:                            sy = s.pop()                            sol = solveset(e, sy)                            if sol is S.EmptySet:                                return S.false                            elif isinstance(sol, FiniteSet):                                solns[sy] = list(sol)                            else:                                raise NotImplementedError                         else:                            # if there is more than 1 symbol from                            # variables in expr than this is a                            # coupled system                             raise NotImplementedError                    else:                        raise NotImplementedError                solns = cartes(*[solns[s] for s in variables])                    solns = cartes(*[solns[s] for s in variables])                except NotImplementedError:                    solns = solve([e - val for e, val in                        zip(L.expr, other)], variables, set=True)                    if solns:                        _v, solns = solns                        # watch for infinite solutions like solving                        # for x, y and getting (x, 0), (0, y), (0, 0)                        solns = [i for i in solns if not any(                            s in i for s in variables)]         else:             x = L.variables[0]             if isinstance(L.expr, Expr):


Question: Either the start or end value of the Range must be finite.'''))          if start.is_infinite:            end = stop        else:            if step*(stop - start) < 0:                start = stop = S.One            else:                end = stop        if not start.is_infinite:             ref = start if start.is_finite else stop             n = ceiling((stop - ref)/step)             if n <= 0:


Question: "..-": "U", "...-": "V",     ".--": "W", "-..-": "X",     "-.--": "Y", "--..": "Z",    "-----": "0", "----": "1",    "-----": "0", ".----": "1",     "..---": "2", "...--": "3",     "....-": "4", ".....": "5",     "-....": "6", "--...": "7",

Morse encoding for "1" is not correct The current Morse mapping in contains an incorrect mapping of The correct mapping is .


Question: >>> X = HadamardProduct(A, OneMatrix(2, 2))     >>> X    A.*OneMatrix(2, 2)    A.*1     >>> canonicalize(X)     A diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py-- a/sympy/printing/latex.py++ b/sympy/printing/latex.py

Added OneMatrix str, pretty, and MathML presentation printing


Question: _print_RandomSymbol = _print_Symbol <del>    def _print_MatrixSymbol(self, expr):        return self._print_Symbol(expr,                                  style=self._settings['mat_symbol_style'])</del>     def _deal_with_super_sub(self, string):         if '{' in string:             return string


Question: else:             return "%s^{%s}" % (self._print(base), self._print(exp))     def _print_MatrixSymbol(self, expr):        return self._print_Symbol(expr, style=self._settings[            'mat_symbol_style'])     def _print_ZeroMatrix(self, Z):        return r"\mathbb{0}"        return r"\mathbb{0}" if self._settings[            'mat_symbol_style'] == 'plain' else r"\mathbf{0}"      def _print_OneMatrix(self, O):        return r"\mathbb{1}"        return r"\mathbb{1}" if self._settings[            'mat_symbol_style'] == 'plain' else r"\mathbf{1}"      def _print_Identity(self, I):        return r"\mathbb{I}"        return r"\mathbb{I}" if self._settings[            'mat_symbol_style'] == 'plain' else r"\mathbf{I}"      def _print_NDimArray(self, expr): diff --git a/sympy/printing/mathml.py b/sympy/printing/mathml.py-- a/sympy/printing/mathml.py++ b/sympy/printing/mathml.py


Question: x.appendChild(self.dom.createTextNode('&#x1D7D8'))         return x     def _print_OneMatrix(self, Z):        x = self.dom.createElement('mn')        x.appendChild(self.dom.createTextNode('&#x1D7D9'))        return x     def _print_Identity(self, I):         x = self.dom.createElement('mi')         x.appendChild(self.dom.createTextNode('𝕀'))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: return prettyForm.__mul__(*args)     def _print_Identity(self, expr):        if self._use_unicode:            return prettyForm(u'\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}')        else:            return prettyForm('I')    def _print_ZeroMatrix(self, expr):        if self._use_unicode:            return prettyForm(u'\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}')        else:            return prettyForm('0')    def _print_OneMatrix(self, expr):        if self._use_unicode:            return prettyForm(u'\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ONE}')        else:            return prettyForm('1')     def _print_DotProduct(self, expr):         args = list(expr.args) diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


Question: def _print_ZeroMatrix(self, expr):         return "0" <ins>    def _print_OneMatrix(self, expr):        return "1"</ins>     def _print_Predicate(self, expr):         return "Q.%s" % expr.name


Question: result[2].subs(x, rep2 + rep2b))      if f.is_polynomial(x):        return None        k = Dummy('k')        ak = sequence(Coeff(f, x, k), (k, 1, oo))        xk = sequence(x**k, (k, 0, oo))        ind = f.coeff(x, 0)        return ak, xk, ind      #  Break instances of Add     #  this allows application of different

doesn't always return a formal power series See the following: I assume the logic is that the value in question is already a polynomial so doesn't need expansion, but it doesn't support the same interface, and doesn't suggest that this is what is supposed to happen. fix issue


Question: return _compute_fps(f, x, x0, dir, hyper, order, rational, full)  <ins>class Coeff(Function):    """    Coeff(p, x, n) represents the nth coefficient of the polynomial p in x    """    @classmethod    def eval(cls, p, x, n):        if p.is_polynomial(x) and n.is_integer:            return p.coeff(x, n)</ins> class FormalPowerSeries(SeriesBase):     """Represents Formal Power Series of a function.


Question: evaluate = kwargs.get('evaluate', global_evaluate[0])          # flatten inputs to merge intersections and iterables        args = _sympify(args)        args = list(ordered(set(_sympify(args))))          # Reduce sets using known rules         if evaluate:

Intersection should remove duplicates The answer should be or remain unevaluated. The routine should give the same answer if duplicates are present; my initial guess is that duplicates should just be removed at the outset of instantiation. Ordering them will produce canonical processing.


Question: if n == S.NegativeOne:                     # n can not be -1 here                     return S.Zero                else:                elif not (-n - 2).could_extract_minus_sign():                     return -chebyshevu(-n - 2, x)             # We can evaluate for some special values of x             if x == S.Zero:

Some uses of couldextractminussign can lead to infinite recursion The issue coming from was fixed, but there is another issue has come up in my pull request Several places in use couldextractminussign() in a way that can lead to infinite recursion. For example, in : The problem is that both and could be True, leading to infinite recursion. This happens in my branch for , but probably an example could be found for master too. We need a more robust way to canonicalize this. Ideally we'd want to remove the minus sign from the highest order term. Is there a fast way to do that?


Question: if x.could_extract_minus_sign():                 return S.NegativeOne**n * legendre(n, -x)             # L_{-n}(x)  --->  L_{n-1}(x)            if n.could_extract_minus_sign():            if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():                 return legendre(-n - S.One, x)             # We can evaluate for some special values of x             if x == S.Zero:


Question: @classmethod     def eval(cls, n, x):        if n.is_integer is False:            raise ValueError("Error: n should be an integer.")         if not n.is_Number:             # Symbolic result L_n(x)             # L_{n}(-x)  --->  exp(-x) * L_{-n-1}(x)             # L_{-n}(x)  --->  exp(x) * L_{n-1}(-x)            if n.could_extract_minus_sign():                return exp(x) * laguerre(n - 1, -x)            if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():                return exp(x)*laguerre(-n - 1, -x)             # We can evaluate for some special values of x             if x == S.Zero:                 return S.One


Question: elif x == S.Infinity:                 return S.NegativeOne**n * S.Infinity         else:            # n is a given fixed integer, evaluate into polynomial             if n.is_negative:                raise ValueError(                    "The index n must be nonnegative integer (got %r)" % n)                return exp(x)*laguerre(-n - 1, -x)             else:                 return cls._eval_at_order(n, x)


Question: def _eval_rewrite_as_polynomial(self, n, x, **kwargs):         from sympy import Sum         # Make sure n \in N_0        if n.is_negative or n.is_integer is False:            raise ValueError("Error: n should be a non-negative integer.")        if n.is_negative:            return exp(x) * self._eval_rewrite_as_polynomial(-n - 1, -x, **kwargs)        if n.is_integer is False:            raise ValueError("Error: n should be an integer.")         k = Dummy("k")         kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k         return Sum(kern, (k, 0, n))


Question: References     ==========     .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Assoc_laguerre_polynomials    .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Generalized_Laguerre_polynomials     .. [2] http://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html     .. [3] http://functions.wolfram.com/Polynomials/LaguerreL/     .. [4] http://functions.wolfram.com/Polynomials/LaguerreL3/


Question: func = self._module_format('numpy.array')         return "%s(%s)" % (func, self._print(expr.tolist())) <ins>    def _print_Identity(self, expr):        shape = expr.shape        if all([dim.is_Integer for dim in shape]):            return "%s(%s)" % (self._module_format('numpy.eye'), self._print(expr.shape[0]))        else:            raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices")</ins>     def _print_BlockMatrix(self, expr):         return '{0}({1})'.format(self._module_format('numpy.block'),                                  self._print(expr.args[0].tolist()))

Lambdify misinterprets some matrix expressions Using lambdify on an expression containing an identity matrix gives us an unexpected result: Instead, the output should be , since we're adding an identity matrix to the array. Inspecting the globals and source code of shows us why we get the result: The code printer prints , which is currently being interpreted as a Python built-in complex number. The printer should support printing identity matrices, and signal an error for unsupported expressions that might be misinterpreted.


Question: def isqrt(n):     """Return the largest integer less than or equal to sqrt(n)."""    if n < 17984395633462800708566937239552:        return int(_sqrt(n))    return integer_nthroot(int(n), 2)[0]    if n < 0:        raise ValueError("n must be nonnegative")    n = int(n)    # Fast path: with IEEE 754 binary64 floats and a correctly-rounded    # math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n <    # 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either    # IEEE 754 format floats *or* correct rounding of math.sqrt, so check the    # answer and fall back to the slow method if necessary.    if n < 4503599761588224:        s = int(_sqrt(n))        if 0 <= n - s*s <= 2*s:            return s    return integer_nthroot(n, 2)[0]   def integer_nthroot(y, n):

isqrt gives incorrect results The function in gives incorrect results for some inputs. For example: or Versions: Python 3.7.3, SymPy 1.4, macOS 10.14.5 For small values of , the uses (aliased to ): The main problem is that the bound used for here is much too large, at almost . If (and it's quite a big if) we can assume that Python floats are IEEE 754 binary64 format and that supplies a correctly-rounded (using round-ties-to-even) square root function, then the largest bound that can safely be used here is , or . If we can assume IEEE 754 binary64 s but can't assume a correctly-rounded , then is still safe for smallish , where the definition of "smallish" depends on how accurate is. For example, if is known to be accurate to within 2 ulps, then it's possible to show that is safe for . (The is necessary here: wouldn't be safe even for tiny , since e.g. if the result of is off by a single ulp downwards, would produce instead of .) Whether is correctly rounded or not will depend on the platform: Python's just wraps the function from C's math library. On modern x64 hardware, one would expect and hope that C's gets mapped to the appropriate SSE2 instruction, in which case it'll be correctly rounded. But on ARM there may well not be a hardware sqrt instruction to map to, and a hand-implemented libm sqrt could easily be incorrectly rounded for some inputs. In the unlikely (but possible) case of non-IEEE 754 binary64 s, it's probably safer to avoid using at all. But this case is likely to be exceedingly rare, and doesn't seem worth worrying about in practice. I guess one option for fixing this while retaining performance for small would be to continue to use the code, but then to check the result is correct before returning it, falling back to the slow integer-only path if that check doesn't pass.


Question: """     def f(rv):    def f(rv, first=True):         if not rv.is_Mul:             return rv        if first:            n, d = rv.as_numer_denom()            return f(n, 0)/f(d, 0)          args = defaultdict(list)         coss = {}


Question: """     def f(rv):    def f(rv, first=True):         if not rv.is_Mul:             return rv        if first:            n, d = rv.as_numer_denom()            return f(n, 0)/f(d, 0)          args = defaultdict(list)         coss = {}


Question: """     def f(rv):    def f(rv, first=True):         if not rv.is_Mul:             return rv        if first:            n, d = rv.as_numer_denom()            return f(n, 0)/f(d, 0)          args = defaultdict(list)         coss = {}

e%20incorrect%20result%0A%23--%0A]) shows an incorrect result when applying to a fairly large (but ultimately basic) expression involving lots of trig functions. I get the same result on version 1.4 on my own computer, and was getting this result from 1.3 before I updated today. EDIT: Note that Ethan reduced this to a much simpler expression below, so that's obviously a better MWE. I'm sorry that I haven't been able to cut it down to smaller size and still get an error; I have tried. The MWE is this: The output is [which could be further simplified to ]. It should be as verified by Mathematica (directly using the output of ), and by direct calculation using trig identities. This isn't just a matter of refusing to do something that may not always be true; this is really the wrong result. The expression looks big and ugly, but is actually pretty simple when you stare at it for a minute: <img width="802" alt="Screen Shot 2019-06-20 at 2 11 30 PM" src="https://user-"Those denominators can be simplified immediately to of the respective arguments. Then you just cancel, group terms, and apply standard trig identities, and get the correct result. Sympy will actually correctly simplify each fraction individually, but then it refuses to further simplify the sum — but at least that sum would be correct, unlike what it does with this whole expression. (Of course, this happened in the middle of a much longer calculation, so I didn't know it was going wrong, and have spent the past few days wondering why I was getting inconsistent results when using this wrong answer.)


Question: isinstance(i, (Eq, Ne))])      def as_set(self):        return self        raise NotImplementedError()

Piecewise doesn't works correctly <!-- The title above should be a short description of the issue. --Code Result It's not working on as well, see the screenshot below, ! [1] told that it is working fine on their systems. Please help me out, either we should fix it or please suggest an alternative approach. I suspect that the error is caused, due to in . May be at least should be allowed to pass through the following loop,


Question: # change is not going to allow a simplification as far as I can tell.         if not (rv.is_Pow and rv.base.func == f):             return rv<ins>        if not rv.exp.is_real:            return rv</ins>          if (rv.exp < 0) == True:             return rv

simplify(cos(x)**I): Invalid comparison of complex I ()


Question: a logarithm of a different base ``b``, use ``log(x, b)``,     which is essentially short-hand for ``log(x)/log(b)``. <ins>    Examples    ========    >>> from sympy import log, S    >>> log(8, 2)    3    >>> log(S(8)/3, 2)    -log(3)/log(2) + 3</ins>     See Also     ========

Incorrect extraction of base powers in log class Evaluating produces , but it should produce . The issue seems to originate around line in during extraction of base powers, where is evaluated to but should evaluate to : if den.isInteger: return n + log(arg // den) / log(base) else: return n + log(arg / den) / log(base) I would suggest to fix the issue by removing the conditional and keeping the else branch (seems like a case of premature optimization). Alternatively, this also seems to fix the issue: if arg.isInteger and den.is_Integer: return n + log(arg // den) / log(base) else: return n + log(arg / den) / log(base) That said, seeing that this code was not changed recently, the issue may run deeper.


Question: # or else expand_log in Mul would have to handle this                 n = multiplicity(base, arg)                 if n:                    den = base**n                    if den.is_Integer:                        return n + log(arg // den) / log(base)                    else:                        return n + log(arg / den) / log(base)                    return n + log(arg / base**n) / log(base)                 else:                     return log(arg)/log(base)             except ValueError:


Question: r*(x - i),                                             range(1, abs(int(k)) + 1), 1) <ins>        if k.is_integer == False:            if x.is_integer and x.is_negative:                return S.Zero</ins>     def _eval_rewrite_as_gamma(self, x, k, **kwargs):         from sympy import gamma         return gamma(x + k) / gamma(x)

Automatic evaluation of RisingFactorial(n, k) with n negative integer, k non-integer This could be evaluated automatically. Note that this causes problems when used in larger expressions, for example:


Question: """     Assign a 5-item fingerprint to each symbol in the equation:     [    # of times it appeared as a Symbol,    # of times it appeared as a Not(symbol),    # of times it appeared as a Symbol in an And or Or,    # of times it appeared as a Not(Symbol) in an And or Or,    sum of the number of arguments with which it appeared    as a Symbol, counting Symbol as 1 and Not(Symbol) as 2    and counting self as 1    # of times it appeared as a Symbol;    # of times it appeared as a Not(symbol);    # of times it appeared as a Symbol in an And or Or;    # of times it appeared as a Not(Symbol) in an And or Or;    a sorted tuple of tuples, (i, j, k), where i is the number of arguments    in an And or Or with which it appeared as a Symbol, and j is    the number of arguments that were Not(Symbol); k is the number    of times that (i, j) was seen.     ]      Examples     ========      >>> from sympy.logic.boolalg import _finger as finger    >>> from sympy import And, Or, Not    >>> from sympy import And, Or, Not, Xor, to_cnf, symbols     >>> from sympy.abc import a, b, x, y     >>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y))     >>> dict(finger(eq))    {(0, 0, 1, 0, 2): [x], (0, 0, 1, 0, 3): [a, b], (0, 0, 1, 2, 2): [y]}    {(0, 0, 1, 0, ((2, 0, 1),)): [x],    (0, 0, 1, 0, ((2, 1, 1),)): [a, b],    (0, 0, 1, 2, ((2, 0, 1),)): [y]}     >>> dict(finger(x & ~y))    {(0, 1, 0, 0, 0): [y], (1, 0, 0, 0, 0): [x]}    {(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]}    In the following, the (5, 2, 6) means that there were 6 Or    functions in which a symbol appeared as itself amongst 5 arguments in    which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)``    is counted once for a0, a1 and a2.    >>> dict(finger(to_cnf(Xor(*symbols('a:5')))))    {(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]}      The equation must not have more than one level of nesting:      >>> dict(finger(And(Or(x, y), y)))    {(0, 0, 1, 0, 2): [x], (1, 0, 1, 0, 2): [y]}    {(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]}     >>> dict(finger(And(Or(x, And(a, x)), y)))     Traceback (most recent call last):     ...

xor3 boolmap equivalent to xnr3 Extension of Results in: Also due to a flaw in the finger fingerprint routine: Results in an identical fingerprint: This is also broken for XOR4 and XNR4. I haven't tested for more inputs beyond 4


Question: So y and x have unique fingerprints, but a and b do not.     """     f = eq.free_symbols    d = dict(list(zip(f, [[0] * 5 for fi in f])))    d = dict(list(zip(f, [[0]*4 + [defaultdict(int)] for fi in f])))     for a in eq.args:         if a.is_Symbol:             d[a][0] += 1         elif a.is_Not:             d[a.args[0]][1] += 1         else:            o = len(a.args) + sum(isinstance(ai, Not) for ai in a.args)            o = len(a.args), sum(isinstance(ai, Not) for ai in a.args)             for ai in a.args:                 if ai.is_Symbol:                     d[ai][2] += 1                    d[ai][-1] += o                    d[ai][-1][o] += 1                 elif ai.is_Not:                     d[ai.args[0]][3] += 1                 else:                     raise NotImplementedError('unexpected level of nesting')     inv = defaultdict(list)     for k, v in ordered(iter(d.items())):        v[-1] = tuple(sorted([i + (j,) for i, j in v[-1].items()]))         inv[tuple(v)].append(k)     return inv


Question: for e, c in self.args:             if hints.get('deep', True):                 if isinstance(e, Basic):                    e = e.doit(**hints)                    newe = e.doit(**hints)                    if newe != self:                        e = newe                 if isinstance(c, Basic):                     c = c.doit(**hints)             newargs.append((e, c))

Piecewise simplification (to avoid doit growth) Perhaps that situation should be recognized during instantiation. Or else might need to call first to avoid repeating what is known (as was reported ):


Question: import mpmath.libmp as mlib from mpmath.libmp import prec_to_dps <ins></ins> class MathMLPrinterBase(Printer):     """Contains common code required for MathMLContentPrinter and     MathMLPresentationPrinter.

printingMathML erroneous I believe I found some mathML printing errors, and noted below what I think it should be should be: should be: should be:


Question: 'Number': 'cn',             'int': 'cn',             'Pow': 'power',<ins>            'Max': 'max',            'Min': 'min',            'Abs': 'abs',            'And': 'and',            'Or': 'or',            'Xor': 'xor',            'Not': 'not',            'Implies': 'implies',</ins>             'Symbol': 'ci',             'MatrixSymbol': 'ci',             'RandomSymbol': 'ci',


Question: 'cos': 'cos',             'tan': 'tan',             'cot': 'cot',            'csc': 'csc',            'sec': 'sec',            'sinh': 'sinh',            'cosh': 'cosh',            'tanh': 'tanh',            'coth': 'coth',            'csch': 'csch',            'sech': 'sech',             'asin': 'arcsin',             'asinh': 'arcsinh',             'acos': 'arccos',             'acosh': 'arccosh',             'atan': 'arctan',             'atanh': 'arctanh',            'acot': 'arccot',             'atan2': 'arctan',            'acot': 'arccot',            'acoth': 'arccoth',            'asec': 'arcsec',            'asech': 'arcsech',            'acsc': 'arccsc',            'acsch': 'arccsch',             'log': 'ln',             'Equality': 'eq',             'Unequality': 'neq',


Question: def _print_Infinity(self, e):         return self.dom.createElement('infinity') <ins>    def _print_NaN(self, e):        return self.dom.createElement('notanumber')    def _print_EmptySet(self, e):        return self.dom.createElement('emptyset')    def _print_BooleanTrue(self, e):        return self.dom.createElement('true')    def _print_BooleanFalse(self, e):        return self.dom.createElement('false')</ins>     def _print_NegativeInfinity(self, e):         x = self.dom.createElement('apply')         x.appendChild(self.dom.createElement('minus'))


Question: dom_element.appendChild(self.dom.createTextNode(str(p)))         return dom_element <ins>    _print_Implies = _print_AssocOp    _print_Not = _print_AssocOp    _print_Xor = _print_AssocOp</ins>  class MathMLPresentationPrinter(MathMLPrinterBase):     """Prints an expression to the Presentation MathML markup language.