Question: 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.

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: 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.

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: Morse encoding for "1" is not correct The current Morse mapping in contains an incorrect mapping of The correct mapping is .

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


Question: Added OneMatrix str, pretty, and MathML presentation printing

>>> 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


Question: Added OneMatrix str, pretty, and MathML presentation printing

_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: Added OneMatrix str, pretty, and MathML presentation printing

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: Added OneMatrix str, pretty, and MathML presentation printing

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: Added OneMatrix str, pretty, and MathML presentation printing

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: Added OneMatrix str, pretty, and MathML presentation printing

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: 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

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


Question: 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

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: 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.

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:


Question: 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?

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:


Question: 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?

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: 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?

@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: 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?

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: 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?

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: 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?

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: 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.

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()))


Question: 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.

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):


Question: Simplify returns incorrect result with trig functions %0A%23--%0Aexpr%20%3D%20(-sin(beta%2F2)sin(alpha%2F2%20-%20gamma%2F2)sin(alpha%2F2%20%2B%20gamma%2F2)%2F(2cos(beta%2F2)cos(alpha%2F2%20%2B%20gamma%2F2)2)%20%2B%20sin(beta%2F2)cos(alpha%2F2%20-%20gamma%2F2)%2F(2cos(beta%2F2)cos(alpha%2F2%20%2B%20gamma%2F2)))%2F(sin(alpha%2F2%20%2B%20gamma%2F2)2%2Fcos(alpha%2F2%20%2B%20gamma%2F2)2%20%2B%201)%20%2B%20(sin(alpha%2F2%20-%20gamma%2F2)sin(alpha%2F2%20%2B%20gamma%2F2)cos(beta%2F2)%2F(2sin(beta%2F2)cos(alpha%2F2%20-%20gamma%2F2)2)%20-%20cos(beta%2F2)cos(alpha%2F2%20%2B%20gamma%2F2)%2F(2sin(beta%2F2)cos(alpha%2F2%20-%20gamma%2F2)))%2F(sin(alpha%2F2%20-%20gamma%2F2)2%2Fcos(alpha%2F2%20-%20gamma%2F2)2%20%2B%201)%0A%23--%0Aprint(mathematicacode(expr))%0A%23--%0A%23%20Using%20Mathematica%20to%20Simplify%20that%20output%20results%20in%20-Cos%5Balpha%5DCot%5Bbeta%5D%0A%23--%0A%23%20That%20is%20also%20the%20result%20that%20one%20can%20get%20using%20basic%20trig%20identities%0A%23--%0Aexpr%0A%23--%0Asimplify(expr)%0A%23--%0A%23%20That%20is%20the%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.)

"""     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: 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,

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


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

# 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


Question: 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.

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     ========


Question: 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.

# 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: 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:

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)


Question: 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

"""     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):     ...


Question: 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

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: 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 ):

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))


Question: 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:

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.


Question: 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:

'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: 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:

'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: 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:

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: 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:

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.


Question: Match doesn't respect matrix non-commutativity doesn't obey the commutativity of matrix expressions when matching scalars between two expressions. As a demonstration: should be , since the associated matrix multiplications are in a different order (and so not indentical).

return AssocOp._matches_commutative(self, expr, repl_dict, old)         elif self.is_commutative is not expr.is_commutative:             return None        # Proceed only if both both expressions are non-commutative         c1, nc1 = self.args_cnc()         c2, nc2 = expr.args_cnc()        repl_dict = repl_dict.copy()        if c1:            if not c2:                c2 = [1]            a = self.func(*c1)            if isinstance(a, AssocOp):                repl_dict = a._matches_commutative(self.func(*c2), repl_dict, old)            else:                repl_dict = a.matches(self.func(*c2), repl_dict)        if repl_dict:            a = self.func(*nc1)            if isinstance(a, self.func):                repl_dict = a._matches(self.func(*nc2), repl_dict)            else:                repl_dict = a.matches(self.func(*nc2), repl_dict)        c1, c2 = [c or [1] for c in [c1, c2]]        # TODO: Should these be self.func?        comm_mul_self = Mul(*c1)        comm_mul_expr = Mul(*c2)        repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old)        # If the commutative arguments didn't match and aren't equal, then        # then the expression as a whole doesn't match        if repl_dict is None and c1 != c2:            return None        # Now match the non-commutative arguments, expanding powers to        # multiplications        nc1 = Mul._matches_expand_pows(nc1)        nc2 = Mul._matches_expand_pows(nc2)        repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict)         return repl_dict or None     def _matches(self, expr, repl_dict={}):        # weed out negative one prefixes#        from sympy import Wild        sign = 1        a, b = self.as_two_terms()        if a is S.NegativeOne:            if b.is_Mul:                sign = -sign    @staticmethod    def _matches_expand_pows(arg_list):        new_args = []        for arg in arg_list:            if arg.is_Pow and arg.exp > 0:                new_args.extend([arg.base] * arg.exp)             else:                # the remainder, b, is not a Mul anymore                return b.matches(-expr, repl_dict)        expr = sympify(expr)        if expr.is_Mul and expr.args[0] is S.NegativeOne:            expr = -expr            sign = -sign        if not expr.is_Mul:            # expr can only match if it matches b and a matches +/- 1            if len(self.args) == 2:                # quickly test for equality                if b == expr:                    return a.matches(Rational(sign), repl_dict)                # do more expensive match                dd = b.matches(expr, repl_dict)                if dd is None:                    return None                dd = a.matches(Rational(sign), dd)                return dd            return None                new_args.append(arg)        return new_args         d = repl_dict.copy()    @staticmethod    def _matches_noncomm(nodes, targets, repl_dict={}):        """Non-commutative multiplication matcher.         # weed out identical terms        pp = list(self.args)        ee = list(expr.args)        for p in self.args:            if p in expr.args:                ee.remove(p)                pp.remove(p)        `nodes` is a list of symbols within the matcher multiplication        expression, while `targets` is a list of arguments in the        multiplication expression being matched against.        """        # List of possible future states to be considered        agenda = []        # The current matching state, storing index in nodes and targets        state = (0, 0)        node_ind, target_ind = state        # Mapping between wildcard indices and the index ranges they match        wildcard_dict = {}        repl_dict = repl_dict.copy()         # only one symbol left in pattern -> match the remaining expression        if len(pp) == 1 and isinstance(pp[0], Wild):            if len(ee) == 1:                d[pp[0]] = sign * ee[0]        while target_ind < len(targets) and node_ind < len(nodes):            node = nodes[node_ind]            if node.is_Wild:                Mul._matches_add_wildcard(wildcard_dict, state)            states_matches = Mul._matches_new_states(wildcard_dict, state,                                                     nodes, targets)            if states_matches:                new_states, new_matches = states_matches                agenda.extend(new_states)                if new_matches:                    for match in new_matches:                        repl_dict[match] = new_matches[match]            if not agenda:                return None             else:                d[pp[0]] = sign * expr.func(*ee)            return d                state = agenda.pop()                node_ind, target_ind = state        return repl_dict         if len(ee) != len(pp):    @staticmethod    def _matches_add_wildcard(dictionary, state):        node_ind, target_ind = state        if node_ind in dictionary:            begin, end = dictionary[node_ind]            dictionary[node_ind] = (begin, target_ind)        else:            dictionary[node_ind] = (target_ind, target_ind)    @staticmethod    def _matches_new_states(dictionary, state, nodes, targets):        node_ind, target_ind = state        node = nodes[node_ind]        target = targets[target_ind]        # Don't advance at all if we've exhausted the targets but not the nodes        if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1:             return None         for p, e in zip(pp, ee):            d = p.xreplace(d).matches(e, d)            if d is None:        if node.is_Wild:            match_attempt = Mul._matches_match_wilds(dictionary, node_ind,                                                     nodes, targets)            if match_attempt:                # If the same node has been matched before, don't return                # anything if the current match is diverging from the previous                # match                other_node_inds = Mul._matches_get_other_nodes(dictionary,                                                               nodes, node_ind)                for ind in other_node_inds:                    other_begin, other_end = dictionary[ind]                    curr_begin, curr_end = dictionary[node_ind]                    other_targets = targets[other_begin:other_end + 1]                    current_targets = targets[curr_begin:curr_end + 1]                    for curr, other in zip(current_targets, other_targets):                        if curr != other:                            return None                # A wildcard node can match more than one target, so only the                # target index is advanced                new_state = [(node_ind, target_ind + 1)]                # Only move on to the next node if there is one                if node_ind < len(nodes) - 1:                    new_state.append((node_ind + 1, target_ind + 1))                return new_state, match_attempt        else:            # If we're not at a wildcard, then make sure we haven't exhausted            # nodes but not targets, since in this case one node can only match            # one target            if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1:                return None            match_attempt = node.matches(target)            if match_attempt:                return [(node_ind + 1, target_ind + 1)], match_attempt            elif node == target:                return [(node_ind + 1, target_ind + 1)], None            else:                 return None        return d    @staticmethod    def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets):        """Determine matches of a wildcard with sub-expression in `target`."""        wildcard = nodes[wildcard_ind]        begin, end = dictionary[wildcard_ind]        terms = targets[begin:end + 1]        # TODO: Should this be self.func?        mul = Mul(*terms) if len(terms) > 1 else terms[0]        return wildcard.matches(mul)    @staticmethod    def _matches_get_other_nodes(dictionary, nodes, node_ind):        """Find other wildcards that may have already been matched."""        other_node_inds = []        for ind in dictionary:            if nodes[ind] == nodes[node_ind]:                other_node_inds.append(ind)        return other_node_inds      @staticmethod     def _combine_inverse(lhs, rhs):


Question: exp doesn't simplify based on its periodicity In current master, doesn't use its periodicity to automatically reduce its argument, not even for purely imaginary arguments:

elif isinstance(arg, SetExpr):             return arg._eval_func(cls)         elif arg.is_Mul:            if arg.is_number or arg.is_Symbol:                coeff = arg.coeff(S.Pi*S.ImaginaryUnit)                if coeff:                    if ask(Q.integer(2*coeff)):                        if ask(Q.even(coeff)):                            return S.One                        elif ask(Q.odd(coeff)):                            return S.NegativeOne                        elif ask(Q.even(coeff + S.Half)):                            return -S.ImaginaryUnit                        elif ask(Q.odd(coeff + S.Half)):                            return S.ImaginaryUnit            coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit)            if coeff:                if (2*coeff).is_integer:                    if coeff.is_even:                        return S.One                    elif coeff.is_odd:                        return S.NegativeOne                    elif (coeff + S.Half).is_even:                        return -S.ImaginaryUnit                    elif (coeff + S.Half).is_odd:                        return S.ImaginaryUnit                elif coeff.is_Rational:                    ncoeff = coeff % 2 # restrict to [0, 2pi)                    if ncoeff > 1: # restrict to (-pi, pi]                        ncoeff -= 2                    if ncoeff != coeff:                        return cls(ncoeff*S.Pi*S.ImaginaryUnit)              # Warning: code in risch.py will be very sensitive to changes             # in this (see DifferentialExtension).


Question: exp doesn't simplify based on its periodicity In current master, doesn't use its periodicity to automatically reduce its argument, not even for purely imaginary arguments:

elif arg.is_Add:             out = []             add = []            argchanged = False             for a in arg.args:                 if a is S.One:                     add.append(a)                     continue                 newa = cls(a)                 if isinstance(newa, cls):                    add.append(a)                    if newa.args[0] != a:                        add.append(newa.args[0])                        argchanged = True                    else:                        add.append(a)                 else:                     out.append(newa)            if out:            if out or argchanged:                 return Mul(*out)*cls(Add(*add), evaluate=False)          elif isinstance(arg, MatrixBase):diff --git a/sympy/physics/matrices.py b/sympy/physics/matrices.py-- a/sympy/physics/matrices.py++ b/sympy/physics/matrices.py


Question: exp doesn't simplify based on its periodicity In current master, doesn't use its periodicity to automatically reduce its argument, not even for purely imaginary arguments:

>>> mdft(3)     Matrix([     [sqrt(3)/3,                sqrt(3)/3,                sqrt(3)/3],    [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(-4*I*pi/3)/3],    [sqrt(3)/3, sqrt(3)*exp(-4*I*pi/3)/3, sqrt(3)*exp(-8*I*pi/3)/3]])    [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3,  sqrt(3)*exp(2*I*pi/3)/3],    [sqrt(3)/3,  sqrt(3)*exp(2*I*pi/3)/3, sqrt(3)*exp(-2*I*pi/3)/3]])     """     mat = [[None for x in range(n)] for y in range(n)]     base = exp(-2*pi*I/n)


Question: frac(zoo) gives TypeError Not sure what should happen, but not this. I am trying to cover these lines in a test: Clearly, they are covered by calling since the comes from that line, but I do not really want an exception...

from sympy.core import Add, S from sympy.core.evalf import get_integer_part, PrecisionExhausted from sympy.core.function import Functionfrom sympy.core.logic import fuzzy_or from sympy.core.numbers import Integerfrom sympy.core.relational import Gt, Lt, Ge, Lefrom sympy.core.relational import Gt, Lt, Ge, Le, Relational from sympy.core.symbol import Symbolfrom sympy.core.sympify import _sympify   ###############################################################################


Question: frac(zoo) gives TypeError Not sure what should happen, but not this. I am trying to cover these lines in a test: Clearly, they are covered by calling since the comes from that line, but I do not really want an exception...

def __le__(self, other):         if self.args[0] == other and other.is_real:             return S.true<ins>        if other is S.Infinity and self.is_finite:            return S.true</ins>         return Le(self, other, evaluate=False)      def __gt__(self, other):


Question: frac(zoo) gives TypeError Not sure what should happen, but not this. I am trying to cover these lines in a test: Clearly, they are covered by calling since the comes from that line, but I do not really want an exception...

def __ge__(self, other):         if self.args[0] == other and other.is_real:             return S.true<ins>        if other is S.NegativeInfinity and self.is_real:            return S.true</ins>         return Ge(self, other, evaluate=False)


Question: frac(zoo) gives TypeError Not sure what should happen, but not this. I am trying to cover these lines in a test: Clearly, they are covered by calling since the comes from that line, but I do not really want an exception...

if arg is S.NaN:                     return S.NaN                 elif arg is S.ComplexInfinity:                    return None                    return S.NaN                 else:                     return arg - floor(arg)             return cls(arg, evaluate=False)


Question: frac(zoo) gives TypeError Not sure what should happen, but not this. I am trying to cover these lines in a test: Clearly, they are covered by calling since the comes from that line, but I do not really want an exception...

if (self.rewrite(floor) == other) or \                     (self.rewrite(ceiling) == other):                 return S.true            # Check if other < 0            if other.is_extended_negative:                return S.false            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return S.false    def _eval_is_finite(self):        return True    def _eval_is_real(self):        return self.args[0].is_extended_real    def _eval_is_imaginary(self):        return self.args[0].is_imaginary    def _eval_is_integer(self):        return self.args[0].is_integer    def _eval_is_zero(self):        return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer])    def _eval_is_negative(self):        return False    def __ge__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other <= 0            if other.is_extended_nonpositive:                return S.true            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return not(res)        return Ge(self, other, evaluate=False)    def __gt__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other < 0            res = self._value_one_or_more(other)            if res is not None:                return not(res)            # Check if other >= 1            if other.is_extended_negative:                return S.true        return Gt(self, other, evaluate=False)    def __le__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other < 0            if other.is_extended_negative:                return S.false            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return res        return Le(self, other, evaluate=False)    def __lt__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other <= 0            if other.is_extended_nonpositive:                return S.false            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return res        return Lt(self, other, evaluate=False)    def _value_one_or_more(self, other):        if other.is_extended_real:            if other.is_number:                res = other >= 1                if res and not isinstance(res, Relational):                    return S.true            if other.is_integer and other.is_positive:                return S.truediff --git a/sympy/printing/latex.py b/sympy/printing/latex.py-- a/sympy/printing/latex.py++ b/sympy/printing/latex.py


Question: frac(zoo) gives TypeError Not sure what should happen, but not this. I am trying to cover these lines in a test: Clearly, they are covered by calling since the comes from that line, but I do not really want an exception...

def _print_UniversalSet(self, expr):         return r"\mathbb{U}" <ins>    def _print_frac(self, expr, exp=None):        if exp is None:            return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0])        else:            return r"\operatorname{frac}{\left(%s\right)}^{%s}" % (                    self._print(expr.args[0]), self._print(exp))</ins>     def _print_tuple(self, expr):         if self._settings['decimal_separator'] =='comma':             return r"\left( %s\right)" % \


Question: Incorrect value for hbar in The numerical value given for hbar differs from the CODATA recommended one of: .

year, years, tropical_year,     G, gravitational_constant,     c, speed_of_light,<ins>    elementary_charge,</ins>     Z0,     hbar,     planck,


Question: Incorrect value for hbar in The numerical value given for hbar differs from the CODATA recommended one of: .

>>> from sympy.physics import units as u     >>> u.find_unit('charge')    ['C', 'coulomb', 'coulombs', 'planck_charge']    ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']     >>> u.find_unit(u.charge)    ['C', 'coulomb', 'coulombs', 'planck_charge']    ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']     >>> u.find_unit("ampere")     ['ampere', 'amperes']     >>> u.find_unit('volt')diff --git a/sympy/physics/units/definitions.py b/sympy/physics/units/definitions.py-- a/sympy/physics/units/definitions.py++ b/sympy/physics/units/definitions.py


Question: Incorrect value for hbar in The numerical value given for hbar differs from the CODATA recommended one of: .

#### CONSTANTS ####  # Newton constant# REF: NIST SP 959 (June 2019) G = gravitational_constant = Quantity("gravitational_constant", abbrev="G") gravitational_constant.set_dimension(length**3*mass**-1*time**-2)gravitational_constant.set_scale_factor(6.67408e-11*m**3/(kg*s**2))gravitational_constant.set_scale_factor(6.67430e-11*m**3/(kg*s**2))  # speed of light c = speed_of_light = Quantity("speed_of_light", abbrev="c") speed_of_light.set_dimension(velocity) speed_of_light.set_scale_factor(299792458*meter/second) # Reduced Planck constanthbar = Quantity("hbar", abbrev="hbar")hbar.set_dimension(action)hbar.set_scale_factor(1.05457266e-34*joule*second)# elementary charge# REF: NIST SP 959 (June 2019)elementary_charge = Quantity("elementary_charge", abbrev="e")elementary_charge.set_dimension(charge)elementary_charge.set_scale_factor(1.602176634e-19*coulomb)  # Planck constant# REF: NIST SP 959 (June 2019) planck = Quantity("planck", abbrev="h") planck.set_dimension(action)planck.set_scale_factor(2*pi*hbar)planck.set_scale_factor(6.62607015e-34*joule*second)# Reduced Planck constant# REF: NIST SP 959 (June 2019)hbar = Quantity("hbar", abbrev="hbar")hbar.set_dimension(action)hbar.set_scale_factor(planck / (2 * pi))  # Electronvolt# REF: NIST SP 959 (June 2019) eV = electronvolt = electronvolts = Quantity("electronvolt", abbrev="eV") electronvolt.set_dimension(energy)electronvolt.set_scale_factor(1.60219e-19*joule)electronvolt.set_scale_factor(1.602176634e-19*joule)  # Avogadro number# REF: NIST SP 959 (June 2019) avogadro_number = Quantity("avogadro_number") avogadro_number.set_dimension(One)avogadro_number.set_scale_factor(6.022140857e23)avogadro_number.set_scale_factor(6.02214076e23)  # Avogadro constant avogadro = avogadro_constant = Quantity("avogadro_constant")


Question: Incorrect value for hbar in The numerical value given for hbar differs from the CODATA recommended one of: .

avogadro_constant.set_scale_factor(avogadro_number / mol)  # Boltzmann constant# REF: NIST SP 959 (June 2019) boltzmann = boltzmann_constant = Quantity("boltzmann_constant") boltzmann_constant.set_dimension(energy/temperature)boltzmann_constant.set_scale_factor(1.38064852e-23*joule/kelvin)boltzmann_constant.set_scale_factor(1.380649e-23*joule/kelvin)  # Stefan-Boltzmann constant# REF: NIST SP 959 (June 2019) stefan = stefan_boltzmann_constant = Quantity("stefan_boltzmann_constant") stefan_boltzmann_constant.set_dimension(energy*time**-1*length**-2*temperature**-4)stefan_boltzmann_constant.set_scale_factor(5.670367e-8*joule/(s*m**2*kelvin**4))stefan_boltzmann_constant.set_scale_factor(pi**2 * boltzmann_constant**4 / (60 * hbar**3 * speed_of_light ** 2))  # Atomic mass# REF: NIST SP 959 (June 2019) amu = amus = atomic_mass_unit = atomic_mass_constant = Quantity("atomic_mass_constant") atomic_mass_constant.set_dimension(mass)atomic_mass_constant.set_scale_factor(1.660539040e-24*gram)atomic_mass_constant.set_scale_factor(1.66053906660e-24*gram)  # Molar gas constant# REF: NIST SP 959 (June 2019) R = molar_gas_constant = Quantity("molar_gas_constant", abbrev="R") molar_gas_constant.set_dimension(energy/(temperature * amount_of_substance))molar_gas_constant.set_scale_factor(8.3144598*joule/kelvin/mol)molar_gas_constant.set_scale_factor(boltzmann_constant * avogadro_constant)  # Faraday constant faraday_constant = Quantity("faraday_constant") faraday_constant.set_dimension(charge/amount_of_substance)faraday_constant.set_scale_factor(96485.33289*C/mol)faraday_constant.set_scale_factor(elementary_charge * avogadro_constant)  # Josephson constant josephson_constant = Quantity("josephson_constant", abbrev="K_j") josephson_constant.set_dimension(frequency/voltage)josephson_constant.set_scale_factor(483597.8525e9*hertz/V)josephson_constant.set_scale_factor(0.5 * planck / elementary_charge)  # Von Klitzing constant von_klitzing_constant = Quantity("von_klitzing_constant", abbrev="R_k") von_klitzing_constant.set_dimension(voltage/current)von_klitzing_constant.set_scale_factor(25812.8074555*ohm)von_klitzing_constant.set_scale_factor(hbar / elementary_charge ** 2)  # Acceleration due to gravity (on the Earth surface) gee = gees = acceleration_due_to_gravity = Quantity("acceleration_due_to_gravity", abbrev="g")diff --git a/sympy/physics/units/util.py b/sympy/physics/units/util.py-- a/sympy/physics/units/util.py++ b/sympy/physics/units/util.py


Question: Incorrect value for hbar in The numerical value given for hbar differs from the CODATA recommended one of: .

>>> from sympy.physics.units import speed_of_light, meter, gram, second, day     >>> from sympy.physics.units import mile, newton, kilogram, atomic_mass_constant     >>> from sympy.physics.units import kilometer, centimeter<ins>    >>> from sympy.physics.units import gravitational_constant, hbar</ins>     >>> from sympy.physics.units import convert_to     >>> convert_to(mile, kilometer)     25146*kilometer/15625


Question: Incorrect value for hbar in The numerical value given for hbar differs from the CODATA recommended one of: .

>>> convert_to(3*newton, kilogram*meter/second**2)     3*kilogram*meter/second**2     >>> convert_to(atomic_mass_constant, gram)    1.66053904e-24*gram    1.660539060e-24*gram      Conversion to multiple units:


Question: Incorrect value for hbar in The numerical value given for hbar differs from the CODATA recommended one of: .

>>> from sympy.physics.units import gravitational_constant, hbar     >>> convert_to(atomic_mass_constant, [gravitational_constant, speed_of_light, hbar]).n()    7.62950196312651e-20*gravitational_constant**(-0.5)*hbar**0.5*speed_of_light**0.5    7.62963085040767e-20*gravitational_constant**(-0.5)*hbar**0.5*speed_of_light**0.5      """     if not isinstance(target_units, (Iterable, Tuple)):


Question: Latex printing issue on derivatives with superscripted symbols When I display the derivatives of second-or-more order with superscipted symbols, it gives wrong latex expression and fails to print correctly with IPython environment. For example, this gives instead of nice latex formula. I figure that this is because x^{}^{2} is wrong latex expression. It should be x^{2}, and thus I report it as an issue.

else:             return self._print(item) <ins>    def parenthesize_super(self, s):        """ Parenthesize s if there is a superscript in s"""        if "^" in s:            return r"\left({}\right)".format(s)        return s    def embed_super(self, s):        """ Embed s in {} if there is a superscript in s"""        if "^" in s:            return "{{{}}}".format(s)        return s</ins>     def doprint(self, expr):         tex = Printer.doprint(self, expr)


Question: Latex printing issue on derivatives with superscripted symbols When I display the derivatives of second-or-more order with superscipted symbols, it gives wrong latex expression and fails to print correctly with IPython environment. For example, this gives instead of nice latex formula. I figure that this is because x^{}^{2} is wrong latex expression. It should be x^{2}, and thus I report it as an issue.

if num == 1:                 tex += r"%s %s" % (diff_symbol, self._print(x))             else:                tex += r"%s %s^{%s}" % (diff_symbol, self._print(x), num)                tex += r"%s %s^{%s}" % (diff_symbol,                                        self.parenthesize_super(self._print(x)),                                        num)          if dim == 1:             tex = r"\frac{%s}{%s}" % (diff_symbol, tex)


Question: Latex printing issue on derivatives with superscripted symbols When I display the derivatives of second-or-more order with superscipted symbols, it gives wrong latex expression and fails to print correctly with IPython environment. For example, this gives instead of nice latex formula. I figure that this is because x^{}^{2} is wrong latex expression. It should be x^{2}, and thus I report it as an issue.

if isinstance(e.args[0], Implies):             return self._print_Implies(e.args[0], r"\not\Rightarrow")         if (e.args[0].is_Boolean):            return r"\neg (%s)" % self._print(e.args[0])            return r"\neg \left(%s\right)" % self._print(e.args[0])         else:             return r"\neg %s" % self._print(e.args[0])


Question: ceiling(pos) 0 should be true Also, shouldn't , and evaluate to True, too?

else:             return r <ins>    def _eval_is_negative(self):        return self.args[0].is_negative    def _eval_is_nonnegative(self):        return self.args[0].is_nonnegative</ins>     def _eval_rewrite_as_ceiling(self, arg, **kwargs):         return -ceiling(-arg)


Question: ceiling(pos) 0 should be true Also, shouldn't , and evaluate to True, too?

return S.true      def __le__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] < other + 1            if other.is_number and other.is_real:                return self.args[0] < ceiling(other)         if self.args[0] == other and other.is_real:             return S.true         if other is S.Infinity and self.is_finite:             return S.true         return Le(self, other, evaluate=False)     def __ge__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] >= other            if other.is_number and other.is_real:                return self.args[0] >= ceiling(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.NegativeInfinity and self.is_finite:            return S.true        return Ge(self, other, evaluate=False)     def __gt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] >= other + 1            if other.is_number and other.is_real:                return self.args[0] >= ceiling(other)         if self.args[0] == other and other.is_real:             return S.false        if other is S.NegativeInfinity and self.is_finite:            return S.true         return Gt(self, other, evaluate=False)     def __lt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] < other            if other.is_number and other.is_real:                return self.args[0] < ceiling(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.Infinity and self.is_finite:            return S.true        return Lt(self, other, evaluate=False)  class ceiling(RoundFunction):     """


Question: ceiling(pos) 0 should be true Also, shouldn't , and evaluate to True, too?

def _eval_rewrite_as_frac(self, arg, **kwargs):         return arg + frac(-arg) <ins>    def _eval_is_positive(self):        return self.args[0].is_positive    def _eval_is_nonpositive(self):        return self.args[0].is_nonpositive</ins>     def _eval_Eq(self, other):         if isinstance(self, ceiling):             if (self.rewrite(floor) == other) or \


Question: ceiling(pos) 0 should be true Also, shouldn't , and evaluate to True, too?

return S.true      def __lt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] <= other - 1            if other.is_number and other.is_real:                return self.args[0] <= floor(other)         if self.args[0] == other and other.is_real:             return S.false        if other is S.Infinity and self.is_finite:            return S.true         return Lt(self, other, evaluate=False)     def __gt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] > other            if other.is_number and other.is_real:                return self.args[0] > floor(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.NegativeInfinity and self.is_finite:            return S.true        return Gt(self, other, evaluate=False)     def __ge__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] > other - 1            if other.is_number and other.is_real:                return self.args[0] > floor(other)         if self.args[0] == other and other.is_real:             return S.true        if other is S.NegativeInfinity and self.is_real:        if other is S.NegativeInfinity and self.is_finite:             return S.true         return Ge(self, other, evaluate=False)     def __le__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] <= other            if other.is_number and other.is_real:                return self.args[0] <= floor(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.Infinity and self.is_finite:            return S.true        return Le(self, other, evaluate=False)  class frac(Function):     r"""Represents the fractional part of x


Question: sqrtdenest raises IndexError If an expression cannot be denested it should be returned unchanged. IndexError fixed for sqrtdenest. Now if the expression can't be denested, it will be returned unchanged. Old Result: New Result:

def rad_rationalize(num, den):     """     Rationalize num/den by removing square roots in the denominator;    num and den are sum of terms whose squares are rationals    num and den are sum of terms whose squares are positive rationals.      Examples     ========


Question: sqrtdenest raises IndexError If an expression cannot be denested it should be returned unchanged. IndexError fixed for sqrtdenest. Now if the expression can't be denested, it will be returned unchanged. Old Result: New Result:

def split_surds(expr):     """    split an expression with terms whose squares are rationals    Split an expression with terms whose squares are positive rationals     into a sum of terms whose surds squared have gcd equal to g    and a sum of terms with surds squared prime with g    and a sum of terms with surds squared prime with g.      Examples     ========diff --git a/sympy/simplify/sqrtdenest.py b/sympy/simplify/sqrtdenest.py-- a/sympy/simplify/sqrtdenest.py++ b/sympy/simplify/sqrtdenest.py


Question: sqrtdenest raises IndexError If an expression cannot be denested it should be returned unchanged. IndexError fixed for sqrtdenest. Now if the expression can't be denested, it will be returned unchanged. Old Result: New Result:

res = (p, S.Zero, S.Zero)     elif p.is_Add:         pargs = sorted(p.args, key=default_sort_key)        if all((x**2).is_Rational for x in pargs):        sqargs = [x**2 for x in pargs]        if all(sq.is_Rational and sq.is_positive for sq in sqargs):             r, b, a = split_surds(p)             res = a, b, r             return list(res)


Question: Permutation args are now subtypes of Basic Permutation has currently a subtype in its args. I changed that to

from sympy.combinatorics import Permutation         expr = _sympify(expr)         permutation = Permutation(permutation)        plist = permutation.args[0]        plist = permutation.array_form         if plist == sorted(plist):             return expr         obj = Basic.__new__(cls, expr, permutation)


Question: Permutation args are now subtypes of Basic Permutation has currently a subtype in its args. I changed that to

elif isinstance(expr, (MatrixSymbol, IndexedBase)):         return expr     elif isinstance(expr, CodegenArrayPermuteDims):        if expr.permutation.args[0] == [1, 0]:        if expr.permutation.array_form == [1, 0]:             return _RecognizeMatOp(Transpose, [_recognize_matrix_expression(expr.expr)])         elif isinstance(expr.expr, CodegenArrayTensorProduct):             ranks = expr.expr.subranksdiff --git a/sympy/combinatorics/perm_groups.py b/sympy/combinatorics/perm_groups.py-- a/sympy/combinatorics/perm_groups.py++ b/sympy/combinatorics/perm_groups.py


Question: Permutation args are now subtypes of Basic Permutation has currently a subtype in its args. I changed that to

>>> from sympy.combinatorics import Permutation, PermutationGroup         >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2))         >>> p.elements        {(3), (2 3), (3)(1 2), (1 2 3), (1 3 2), (1 3)}        {(1 2 3), (1 3 2), (1 3), (2 3), (3), (3)(1 2)}          """         return set(self._elements)diff --git a/sympy/combinatorics/permutations.py b/sympy/combinatorics/permutations.py-- a/sympy/combinatorics/permutations.py++ b/sympy/combinatorics/permutations.py


Question: Permutation args are now subtypes of Basic Permutation has currently a subtype in its args. I changed that to

import random from collections import defaultdict from sympy.core import Basicfrom sympy.core.basic import Basic, Atom from sympy.core.compatibility import is_sequence, reduce, range, as_int from sympy.matrices import zeros from sympy.polys.polytools import lcm


Question: Permutation args are now subtypes of Basic Permutation has currently a subtype in its args. I changed that to

return Cycle(self)  class Permutation(Basic):class Permutation(Atom):     """     A permutation, alternatively known as an 'arrangement number' or 'ordering'     is an arrangement of the elements of an ordered list into a one-to-one


Question: Permutation args are now subtypes of Basic Permutation has currently a subtype in its args. I changed that to

Permutation([2, 1, 3, 0])          """        p = Basic.__new__(cls, perm)        p = super(Permutation, cls).__new__(cls)         p._array_form = perm         p._size = len(perm)         return pdiff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py-- a/sympy/printing/pycode.py++ b/sympy/printing/pycode.py


Question: Permutation args are now subtypes of Basic Permutation has currently a subtype in its args. I changed that to

return "%s(%s, %s)" % (             self._module_format("numpy.transpose"),             self._print(expr.expr),            self._print(expr.permutation.args[0]),            self._print(expr.permutation.array_form),         )      def _print_CodegenArrayElementwiseAdd(self, expr):diff --git a/sympy/printing/tensorflow.py b/sympy/printing/tensorflow.py-- a/sympy/printing/tensorflow.py++ b/sympy/printing/tensorflow.py


Question: Permutation args are now subtypes of Basic Permutation has currently a subtype in its args. I changed that to

return "%s(%s, %s)" % (             self._module_format("tensorflow.transpose"),             self._print(expr.expr),            self._print(expr.permutation.args[0]),            self._print(expr.permutation.array_form),         )      def _print_CodegenArrayElementwiseAdd(self, expr):


Question: Exception when multiplying BlockMatrix containing ZeroMatrix blocks When a block matrix with zero blocks is defined then block-multiplying it once seems to work fine: but block-multiplying twice throws an exception: This seems to be caused by the fact that the zeros in are not but : However, I don't understand SymPy internals well enough to find out why this happens. I use Python 3.7.4 and sympy 1.4 (installed with pip).

# manipulate them like non-commutative scalars.                 return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)]) <ins>        if mat_class == MatAdd:            return mat_class(*matrices).doit(deep=False)</ins>         return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False)     return _postprocessor


Question: new of IndexedBase upcasts subclass of Symbol to Symbol First, thanks for creating SymPy. We're using it in a code generation framework: We noticed that our tests are failling when using the current master of SymPy. To reproduce run: While should work fine. The reason for this failure seems to be in the call of the constructor of . We're a calling it with a subclass of () which is essentially a sympy Symbol with type information. Is there a reason why the out-commented line is necessary? It causes our TypeSymbol to lose its type information by re-constructing a new Symbol. When I out-comment this line everything works fine again. In new of IndexedBase upcasts subclass of Symbol to Symbol First, thanks for creating SymPy. We're using it in a code generation framework: We noticed that our tests are failling when using the current master of SymPy. To reproduce run: While should work fine. The reason for this failure seems to be in the call of the constructor of . We're a calling it with a subclass of () which is essentially a sympy Symbol with type information. Is there a reason why the out-commented line is necessary? It causes our TypeSymbol to lose its type information by re-constructing a new Symbol. When I out-comment this line everything works fine again. In

assumptions, kw_args = _filter_assumptions(kw_args)         if isinstance(label, string_types):            label = Symbol(label)            label = Symbol(label, **assumptions)         elif isinstance(label, Symbol):             assumptions = label._merge(assumptions)            label = Symbol(label.name)         elif isinstance(label, (MatrixBase, NDimArray)):             return label         elif isinstance(label, Iterable):


Question: Unexpected exception when multiplying geometry.Point and number This line works fine But when I write the same this way it raises an exception The expected behaviour is, that both lines give the same result

coords = [simplify(x*factor) for x in self.args]         return Point(coords, evaluate=False) <ins>    def __rmul__(self, factor):        """Multiply a factor by point's coordinates."""        return self.__mul__(factor)</ins>     def __neg__(self):         """Negate the point."""         coords = [-x for x in self.args]


Question: Refine with sign Consider the following code: All the returned expression are . However, at least for and , the results should be . This probably is due to the lack of capabilities for . A PR similar to should fix this behaviour. Related issues: and .

return None  <ins>def refine_sign(expr, assumptions):    """    Handler for sign    Examples    ========    >>> from sympy.assumptions.refine import refine_sign    >>> from sympy import Symbol, Q, sign, im    >>> x = Symbol('x', real = True)    >>> expr = sign(x)    >>> refine_sign(expr, Q.positive(x) & Q.nonzero(x))    1    >>> refine_sign(expr, Q.negative(x) & Q.nonzero(x))    -1    >>> refine_sign(expr, Q.zero(x))    0    >>> y = Symbol('y', imaginary = True)    >>> expr = sign(y)    >>> refine_sign(expr, Q.positive(im(y)))    I    >>> refine_sign(expr, Q.negative(im(y)))    -I    """    arg = expr.args[0]    if ask(Q.zero(arg), assumptions):        return S.Zero    if ask(Q.real(arg)):        if ask(Q.positive(arg), assumptions):            return S.One        if ask(Q.negative(arg), assumptions):            return S.NegativeOne    if ask(Q.imaginary(arg)):        arg_re, arg_im = arg.as_real_imag()        if ask(Q.positive(arg_im), assumptions):            return S.ImaginaryUnit        if ask(Q.negative(arg_im), assumptions):            return -S.ImaginaryUnit    return expr</ins> handlers_dict = {     'Abs': refine_abs,     'Pow': refine_Pow,


Question: Refine with sign Consider the following code: All the returned expression are . However, at least for and , the results should be . This probably is due to the lack of capabilities for . A PR similar to should fix this behaviour. Related issues: and .

'StrictGreaterThan': refine_Relational,     'StrictLessThan': refine_Relational,     're': refine_re,    'im': refine_im    'im': refine_im,    'sign': refine_sign }


Question: sqrt(sympify('')) gives wrong answer It is easily verified that this answer is not correct; notably:

facs = factorint(r, limit=limit, use_trial=use_trial,                                      use_rho=use_rho, use_pm1=use_pm1,                                      verbose=verbose)                    factors.update(facs)                    for k, v in facs.items():                        factors[k] = factors.get(k, 0) + v                 raise StopIteration              # ...see if factorization can be terminated


Question: Corrected functions in subclasses of Corrected the and functions. These functions are still sort of incomplete (couldn't think of all cases, any improvements are welcome). They can directly be used to define properties like and for , , and .

else:             return self.func(arg) <ins>    def _eval_is_real(self):        arg = self.args[0]        if arg.is_real:            return True        # if `im` is of the form n*pi        # else, check if it is a number        re, im = arg.as_real_imag()        return (im%pi).is_zero</ins>     def _eval_is_extended_real(self):         if self.args[0].is_extended_real:             return True


Question: Corrected functions in subclasses of Corrected the and functions. These functions are still sort of incomplete (couldn't think of all cases, any improvements are welcome). They can directly be used to define properties like and for , , and .

def _eval_is_finite(self):         arg = self.args[0]        if arg.is_imaginary:            return True        return arg.is_finite      def _eval_is_zero(self):         arg = self.args[0]


Question: Corrected functions in subclasses of Corrected the and functions. These functions are still sort of incomplete (couldn't think of all cases, any improvements are welcome). They can directly be used to define properties like and for , , and .

else:             return self.func(arg)     def _eval_is_real(self):        arg = self.args[0]        # `cosh(x)` is real for real OR purely imaginary `x`        if arg.is_real or arg.is_imaginary:            return True        # cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a)        # the imaginary part can be an expression like n*pi        # if not, check if the imaginary part is a number        re, im = arg.as_real_imag()        return (im%pi).is_zero     def _eval_is_positive(self):         if self.args[0].is_extended_real:             return True      def _eval_is_finite(self):         arg = self.args[0]        if arg.is_imaginary:            return True        return arg.is_finite   class tanh(HyperbolicFunction):


Question: Corrected functions in subclasses of Corrected the and functions. These functions are still sort of incomplete (couldn't think of all cases, any improvements are welcome). They can directly be used to define properties like and for , , and .

else:             return self.func(arg) <ins>    def _eval_is_real(self):        from sympy import cos, sinh        arg = self.args[0]        if arg.is_real:            return True        re, im = arg.as_real_imag()        # if denom = 0, tanh(arg) = zoo        if re == 0 and im % pi == pi/2:            return None        # check if im is of the form n*pi/2 to make sin(2*im) = 0        # if not, im could be a number, return False in that case        return (im % (pi/2)).is_zero</ins>     def _eval_is_extended_real(self):         if self.args[0].is_extended_real:             return True


Question: Corrected functions in subclasses of Corrected the and functions. These functions are still sort of incomplete (couldn't think of all cases, any improvements are welcome). They can directly be used to define properties like and for , , and .

return self.args[0].is_negative      def _eval_is_finite(self):        from sympy import sinh, cos         arg = self.args[0]        re, im = arg.as_real_imag()        denom = cos(im)**2 + sinh(re)**2        if denom == 0:            return False        elif denom.is_number:            return True         if arg.is_extended_real:             return True


Question: Modified ispositive for cosh function returns if x is real. Also modified the function to return the function itself or its negative if the function is positive or negative. Example: abs(cosh(x)) should simplify to cosh(x) for real x Sympy 1.0 only simplifies in a limited set of cases:

from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.integers import floor <ins>from sympy import pi, Eqfrom sympy.logic import Or, Andfrom sympy.core.logic import fuzzy_or, fuzzy_and, fuzzy_bool</ins>  def _rewrite_hyperbolics_as_exp(expr):     expr = sympify(expr)


Question: Modified ispositive for cosh function returns if x is real. Also modified the function to return the function itself or its negative if the function is positive or negative. Example: abs(cosh(x)) should simplify to cosh(x) for real x Sympy 1.0 only simplifies in a limited set of cases:

sinh, tanh, acosh     """ <ins>    def _eval_is_positive(self):        arg = self.args[0]        if arg.is_real:            return True        re, im = arg.as_real_imag()        im_mod = im % (2*pi)        if im_mod == 0:            return True        if re == 0:            if im_mod < pi/2 or im_mod > 3*pi/2:                return True            elif im_mod >= pi/2 or im_mod <= 3*pi/2:                return False        return fuzzy_or([fuzzy_and([fuzzy_bool(Eq(re, 0)),                         fuzzy_or([fuzzy_bool(im_mod < pi/2),                                   fuzzy_bool(im_mod > 3*pi/2)])]),                         fuzzy_bool(Eq(im_mod, 0))])    def _eval_is_nonnegative(self):        arg = self.args[0]        if arg.is_real:            return True        re, im = arg.as_real_imag()        im_mod = im % (2*pi)        if im_mod == 0:            return True        if re == 0:            if im_mod <= pi/2 or im_mod >= 3*pi/2:                return True            elif im_mod > pi/2 or im_mod < 3*pi/2:                return False        return fuzzy_or([fuzzy_and([fuzzy_bool(Eq(re, 0)),                         fuzzy_or([fuzzy_bool(im_mod <= pi/2), fuzzy_bool(im_mod >= 3*pi/2)])]),                         fuzzy_bool(Eq(im_mod, 0))])</ins>     def fdiff(self, argindex=1):         if argindex == 1:             return sinh(self.args[0])


Question: Modified ispositive for cosh function returns if x is real. Also modified the function to return the function itself or its negative if the function is positive or negative. Example: abs(cosh(x)) should simplify to cosh(x) for real x Sympy 1.0 only simplifies in a limited set of cases:

re, im = arg.as_real_imag()         return (im%pi).is_zero <del>    def _eval_is_positive(self):        if self.args[0].is_extended_real:            return True</del>     def _eval_is_finite(self):         arg = self.args[0]         return arg.is_finite


Question: Intersection of ImageSet gives incorrect answer. After git bisecting by this has changed the output of ping -

return None     base_set = self.base_sets[0]     # Intersection between ImageSets with Integers as base set    # For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the    # diophantine equations f(n)=g(m).    # If the solutions for n are {h(t) : t in Integers} then we return    # {f(h(t)) : t in integers}.     if base_set is S.Integers:        g = None        gm = None         if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):            g = other.lamda.expr            gm = other.lamda.expr             m = other.lamda.variables[0]         elif other is S.Integers:            m = g = Dummy('x')        if g is not None:            f = self.lamda.expr            m = gm = Dummy('x')        if gm is not None:            fn = self.lamda.expr             n = self.lamda.variables[0]            # Diophantine sorts the solutions according to the alphabetic            # order of the variable names, since the result should not depend            # on the variable name, they are replaced by the dummy variables            # below            a, b = Dummy('a'), Dummy('b')            fa, ga = f.subs(n, a), g.subs(m, b)            solns = list(diophantine(fa - ga))            if not solns:            solns = list(diophantine(fn - gm, syms=(n, m)))            if len(solns) == 0:                 return EmptySet()            if len(solns) != 1:            elif len(solns) != 1:                 return            nsol = solns[0][0]  # since 'a' < 'b', nsol is first            t = nsol.free_symbols.pop()  # diophantine supplied symbol            nsol = nsol.subs(t, n)            if nsol != n:                # if nsol == n and we know were are working with                # a base_set of Integers then this was an unevaluated                # ImageSet representation of Integers, otherwise                # it is a new ImageSet intersection with a subset                # of integers                nsol = f.subs(n, nsol)            return imageset(Lambda(n, nsol), S.Integers)            else:                soln, solm = solns[0]                (t,) = soln.free_symbols                expr = fn.subs(n, soln.subs(t, n))                return imageset(Lambda(n, expr), S.Integers)      if other == S.Reals:         from sympy.solvers.solveset import solveset_real


Question: Catalan rewrite and doctests for latex equations First, implement . Also, something I've been thinking about for while: we have lots of LaTeX in our docs. In many cases we could generate those equations ourselves instead of typing them manually (I found errors while doing for example). This PR should demonstrate the idea. what do you think? Will this work? Its certainly nice for maintainance, although it is probably slightly less readable... (If we want to do this widely, the latex printer could probably be optimized for things like and when it uses instead of .) <!-- BEGIN RELEASE NOTES --core Catalan can be rewritten as a sum <!-- END RELEASE NOTES --

elif issubclass(number_cls, Rational):             return (Rational(9, 10), S.One) <ins>    def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None):        from sympy import Sum, Dummy        if (k_sym is not None) or (symbols is not None):            return self        k = Dummy('k', integer=True, nonnegative=True)        return Sum((-1)**k / (2*k+1)**2, (k, 0, S.Infinity))</ins>     def _sage_(self):         import sage.all as sage         return sage.catalan


Question: interpolate could provide value instead of nan Since the default x value for interpolation is the interpolation at 5 could just return 115 instead of nan.

from __future__ import print_function, division from sympy.core import S, Basic, Add, Mul, symbolsfrom sympy.core import S, Basic, Add, Mul, symbols, Dummy from sympy.core.compatibility import range from sympy.functions.combinatorial.factorials import factorial from sympy.polys.polyerrors import (


Question: interpolate could provide value instead of nan Since the default x value for interpolation is the interpolation at 5 could just return 115 instead of nan.

@public def interpolate(data, x):     """    Construct an interpolating polynomial for the data points.    Construct an interpolating polynomial for the data points    evaluated at point x (which can be symbolic or numeric).      Examples     ========      >>> from sympy.polys.polyfuncs import interpolate    >>> from sympy.abc import x    >>> from sympy.abc import a, b, x      A list is interpreted as though it were paired with a range starting     from 1:


Question: interpolate could provide value instead of nan Since the default x value for interpolation is the interpolation at 5 could just return 115 instead of nan.

>>> interpolate({-1: 2, 1: 2, 2: 5}, x)     x**2 + 1     If the interpolation is going to be used only once then the    value of interest can be passed instead of passing a symbol:    >>> interpolate([1, 4, 9], 5)    25    Symbolic coordinates are also supported:    >>> [(i,interpolate((a, b), i)) for i in range(1, 4)]    [(1, a), (2, b), (3, -a + 2*b)]     """     n = len(data)    poly = None      if isinstance(data, dict):        if x in data:            return S(data[x])         X, Y = list(zip(*data.items()))        poly = interpolating_poly(n, x, X, Y)     else:         if isinstance(data[0], tuple):             X, Y = list(zip(*data))            poly = interpolating_poly(n, x, X, Y)            if x in X:                return S(Y[X.index(x)])         else:            if x in range(1, n + 1):                return S(data[x - 1])             Y = list(data)            X = list(range(1, n + 1))             numert = Mul(*[(x - i) for i in range(1, n + 1)])            denom = -factorial(n - 1) if n%2 == 0 else factorial(n - 1)            coeffs = []            for i in range(1, n + 1):                coeffs.append(numert/(x - i)/denom)                denom = denom/(i - n)*i            poly = Add(*[coeff*y for coeff, y in zip(coeffs, Y)])    return poly.expand()    try:        return interpolating_poly(n, x, X, Y).expand()    except ValueError:        d = Dummy()        return interpolating_poly(n, d, X, Y).expand().subs(d, x)   @publicdiff --git a/sympy/polys/specialpolys.py b/sympy/polys/specialpolys.py-- a/sympy/polys/specialpolys.py++ b/sympy/polys/specialpolys.py


Question: interpolate could provide value instead of nan Since the default x value for interpolation is the interpolation at 5 could just return 115 instead of nan.

from sympy.core import Add, Mul, Symbol, sympify, Dummy, symbols from sympy.core.compatibility import range, string_types<ins>from sympy.core.containers import Tuple</ins> from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import sqrt from sympy.ntheory import nextprime


Question: interpolate could provide value instead of nan Since the default x value for interpolation is the interpolation at 5 could just return 115 instead of nan.

from sympy.polys.polyclasses import DMP from sympy.polys.polytools import Poly, PurePoly from sympy.polys.polyutils import _analyze_gensfrom sympy.utilities import subsets, publicfrom sympy.utilities import subsets, public, filldedent   @public


Question: interpolate could provide value instead of nan Since the default x value for interpolation is the interpolation at 5 could just return 115 instead of nan.

@public def interpolating_poly(n, x, X='x', Y='y'):    """Construct Lagrange interpolating polynomial for ``n`` data points. """    """Construct Lagrange interpolating polynomial for ``n``    data points. If a sequence of values are given for ``X`` and ``Y``    then the first ``n`` values will be used.    """    ok = getattr(x, 'free_symbols', None)     if isinstance(X, string_types):         X = symbols("%s:%s" % (X, n))    elif ok and ok & Tuple(*X).free_symbols:        ok = False      if isinstance(Y, string_types):         Y = symbols("%s:%s" % (Y, n))    elif ok and ok & Tuple(*Y).free_symbols:        ok = False    if not ok:        raise ValueError(filldedent('''            Expecting symbol for x that does not appear in X or Y.            Use `interpolate(list(zip(X, Y)), x)` instead.'''))      coeffs = []    numert = Mul(*[(x - u) for u in X])    numert = Mul(*[x - X[i] for i in range(n)])      for i in range(n):         numer = numert/(x - X[i])


Question: Sympy incorrectly attempts to eval reprs in its eq method Passing strings produced by unknown objects into eval is very bad. It is especially surprising for an equality check to trigger that kind of behavior. This should be fixed ASAP. Repro code: Results in: On the line: Where code is: Full trace: Related issue: an unknown object whose repr is will incorrectly compare as equal to a sympy symbol x:

def __eq__(self, other):         try:            other = sympify(other)            other = _sympify(other)             if not isinstance(other, Expr):                 return False         except (SympifyError, SyntaxError):


Question: imageset broken for complex numbers With current master: The (or any other value) is simply dropped.

from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet,                         EmptySet, Intersection, Range) from sympy.sets.fancysets import Integers, Naturals, Reals<ins>from sympy.functions.elementary.exponential import match_real_imag</ins>   _x, _y = symbols("x y")


Question: imageset broken for complex numbers With current master: The (or any other value) is simply dropped.

match = expr.match(a*n + b)     if match and match[a]:         # canonical shift        b = match[b]        if abs(match[a]) == 1:        a, b = match[a], match[b]        if a in [1, -1]:            # drop integer addends in b             nonint = []             for bi in Add.make_args(b):                 if not bi.is_integer:                     nonint.append(bi)             b = Add(*nonint)        if b.is_number and match[a].is_real:            mod = b % match[a]            reps = dict([(m, m.args[0]) for m in mod.atoms(Mod)                if not m.args[0].is_real])            mod = mod.xreplace(reps)            expr = match[a]*n + mod        else:            expr = match[a]*n + b        if b.is_number and a.is_real:            # avoid Mod for complex numbers, #11391            br, bi = match_real_imag(b)            if br and br.is_comparable and a.is_comparable:                br %= a                b = br + S.ImaginaryUnit*bi        elif b.is_number and a.is_imaginary:            br, bi = match_real_imag(b)            ai = a/S.ImaginaryUnit            if bi and bi.is_comparable and ai.is_comparable:                bi %= ai                b = br + S.ImaginaryUnit*bi        expr = a*n + b      if expr != f.expr:         return ImageSet(Lambda(n, expr), S.Integers)


Question: Simplify of simple trig expression fails trigsimp in various versions, including 1.5, incorrectly simplifies cos(x)+sqrt(sin(x)**2) as though it were cos(x)+sin(x) for general complex x. (Oddly it gets this right if x is real.) Embarrassingly I found this by accident while writing sympy-based teaching material...

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[p] = (factors[p] if p in factors else S.Zero) + factors[f]                    factors[q] = (factors[q] if q in factors else S.Zero) - factors[f]                     factors.pop(f)             if i:                 factors[I] = S.One*i


Question: Simplify of simple trig expression fails trigsimp in various versions, including 1.5, incorrectly simplifies cos(x)+sqrt(sin(x)**2) as though it were cos(x)+sin(x) for general complex x. (Oddly it gets this right if x is real.) Embarrassingly I found this by accident while writing sympy-based teaching material...

args = []         for factor, exp in self.factors.items():             if exp != 1:                b, e = factor.as_base_exp()                if isinstance(exp, int):                    e = _keep_coeff(Integer(exp), e)                elif isinstance(exp, Rational):                if isinstance(exp, Integer):                    b, e = factor.as_base_exp()                     e = _keep_coeff(exp, e)                    args.append(b**e)                 else:                    e *= exp                args.append(b**e)                    args.append(factor**exp)             else:                 args.append(factor)         return Mul(*args)


Question: Why pretty print of "oo - oo" has result "nan", if the evaluation is disabled?

@_sympifyit('other', NotImplemented)     def __add__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.NegativeInfinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__add__(self, other)     __radd__ = __add__      @_sympifyit('other', NotImplemented)     def __sub__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__sub__(self, other)      @_sympifyit('other', NotImplemented)     def __rsub__(self, other):


Question: Why pretty print of "oo - oo" has result "nan", if the evaluation is disabled?

@_sympifyit('other', NotImplemented)     def __mul__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other.is_zero or other is S.NaN:                 return S.NaN             if other.is_extended_positive:                 return self             return S.NegativeInfinity        return NotImplemented        return Number.__mul__(self, other)     __rmul__ = __mul__      @_sympifyit('other', NotImplemented)     def __div__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or \                 other is S.NegativeInfinity or \                     other is S.NaN:


Question: Why pretty print of "oo - oo" has result "nan", if the evaluation is disabled?

if other.is_extended_nonnegative:                 return self             return S.NegativeInfinity        return NotImplemented        return Number.__div__(self, other)      __truediv__ = __div__


Question: Why pretty print of "oo - oo" has result "nan", if the evaluation is disabled?

@_sympifyit('other', NotImplemented)     def __add__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__add__(self, other)     __radd__ = __add__      @_sympifyit('other', NotImplemented)     def __sub__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.NegativeInfinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__sub__(self, other)      @_sympifyit('other', NotImplemented)     def __rsub__(self, other):


Question: Why pretty print of "oo - oo" has result "nan", if the evaluation is disabled?

@_sympifyit('other', NotImplemented)     def __mul__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other.is_zero or other is S.NaN:                 return S.NaN             if other.is_extended_positive:                 return self             return S.Infinity        return NotImplemented        return Number.__mul__(self, other)     __rmul__ = __mul__      @_sympifyit('other', NotImplemented)     def __div__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or \                 other is S.NegativeInfinity or \                     other is S.NaN:


Question: Why pretty print of "oo - oo" has result "nan", if the evaluation is disabled?

if other.is_extended_nonnegative:                 return self             return S.Infinity        return NotImplemented        return Number.__div__(self, other)      __truediv__ = __div__