Question: factors[i] = (dup_convert(f, K, K0), k)              coeff = K0.convert(coeff, K)            coeff = K0.quo(coeff, denom)             if K0_inexact is None:                coeff = coeff/denom            else:            if K0_inexact:                 for i, (f, k) in enumerate(factors):                    f = dup_quo_ground(f, denom, K0)                    max_norm = dup_max_norm(f, K0)                    f = dup_quo_ground(f, max_norm, K0)                     f = dup_convert(f, K0, K0_inexact)                     factors[i] = (f, k)                    coeff = K0.mul(coeff, K0.pow(max_norm, k))                  coeff = K0_inexact.convert(coeff, K0)                 K0 = K0_inexact

Problem factoring trivial polynomial The factoring of w is incorrect - look at the order of x it is 10^-8 not 10^-4. Bug in simplify ? Hi, I'm running into issues where simplify comes up with incorrect results. sympy verion 1.0, python version 3.52, ubuntu 16.04. I've also verified the same with the Sympy online console (). The problem comes when trying to simplify a mass matrix for a simple 3-DOF robot: If I use the matrix above directly, I get correct results: which should be: If on the other hand, I simplify first I get an incorrect result: I was wondering if this is a bug with simplify, or am I doing something wrong? Thanks.


Question: factors[i] = (dmp_convert(f, u, K, K0), k)              coeff = K0.convert(coeff, K)            coeff = K0.quo(coeff, denom)             if K0_inexact is None:                coeff = coeff/denom            else:            if K0_inexact:                 for i, (f, k) in enumerate(factors):                    f = dmp_quo_ground(f, denom, u, K0)                    max_norm = dmp_max_norm(f, u, K0)                    f = dmp_quo_ground(f, max_norm, u, K0)                     f = dmp_convert(f, u, K0, K0_inexact)                     factors[i] = (f, k)                    coeff = K0.mul(coeff, K0.pow(max_norm, k))                  coeff = K0_inexact.convert(coeff, K0)                 K0 = K0_inexact


Question: from sympy.core.compatibility import (iterable,     ordered, range, as_int) from sympy.core.numbers import Float, I, pi, Rational, Integerfrom sympy.core.function import expand_log, count_ops, _mexpand, _coeff_isnegfrom sympy.core.function import expand_log, count_ops, _mexpand, _coeff_isneg, nfloat from sympy.core.rules import Transform from sympy.core.evaluate import global_evaluate from sympy.functions import (

simplify doesn't do the last simplification step Note: I'm using Python 3.5.1 and sympy 0.7.6.1. Full script is attached in the .zip file: I've been using Sympy to compute Laplacian in different geometrical coordinates system. This usually creates extremelly long expressions and simplify usually does a great job. However, I've come against one particular case where simplify does most of the job but doesn't perform the ultimate simplification step. I've reduced the problem set getting rid of all of the Derivative terms. The initial expression is still huge (675 ops!): ! A first call to sucessfully reduces it to : ! Which is great (23 ops), but somehow frustrating as we can factorize it a little more. If I apply again, then I get the expression I wanted (7 ops): ! If simplify worked perfectly, shouldn't yield a different result from From my understanding of how simplify works, it successively tries different simplification strategies and compares them. In that case, the order of the different strategies matters. In my particular case, the strategy than eventually did the final factorisation step may have been called to early. I fixed that calling simplify again. We could fix it applying an optional recursive mode at the end of the simplify function: I can make the pull request if that helps.


Question: return e  def simplify(expr, ratio=1.7, measure=count_ops, fu=False):def simplify(expr, ratio=1.7, measure=count_ops, rational=False):     """     Simplifies the given expression.


Question: simplification strategies and then compares them using the measure     function, we get a completely different result that is still different     from the input expression by doing this.<ins>    If rational=True, Floats will be recast as Rationals before simplification.    If rational=None, Floats will be recast as Rationals but the result will    be recast as Floats. If rational=False(default) then nothing will be done    to the Floats.</ins>     """     expr = sympify(expr)


Question: if len(expr.args) == 1 and len(expr.args[0].args) == 1 and \                isinstance(expr.args[0], expr.inverse(argindex=1)):                 return simplify(expr.args[0].args[0], ratio=ratio,                                measure=measure, fu=fu)        return expr.func(*[simplify(x, ratio=ratio, measure=measure, fu=fu)                                measure=measure, rational=rational)        return expr.func(*[simplify(x, ratio=ratio, measure=measure, rational=rational)                          for x in expr.args])      # TODO: Apply different strategies, considering expression pattern:


Question: return choices[0]         return min(choices, key=measure) <ins>    # rationalize Floats    floats = False    if rational is not False and expr.has(Float):        floats = True        expr = nsimplify(expr, rational=True)</ins>     expr = bottom_up(expr, lambda w: w.normal())     expr = Mul(*powsimp(expr).as_content_primitive())     _e = cancel(expr)


Question: if expr.has(BesselBase):         expr = besselsimp(expr)     if expr.has(TrigonometricFunction) and not fu or expr.has(            HyperbolicFunction):    if expr.has(TrigonometricFunction, HyperbolicFunction):         expr = trigsimp(expr, deep=True)      if expr.has(log):


Question: expr = product_simplify(expr)      short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr)<ins>    short = shorter(short, cancel(short))</ins>     short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))     if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase):         short = exptrigsimp(short, simplify=False)


Question: if measure(expr) > ratio*measure(original_expr):         expr = original_expr <ins>    # restore floats    if floats and rational is None:        expr = nfloat(expr, exponent=False)</ins>     return expr


Question: short = shorter(short, cancel(short))     short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))     if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase):        short = exptrigsimp(short, simplify=False)        short = exptrigsimp(short)      # get rid of hollow 2-arg Mul factorization     hollow_mul = Transform(

Simplification fails to recognize sin expressed as exponentials The expression for has not been recognized, while expressions for and have.


Question: def expander(fro):         def repl(nu, z):             if (nu % 1) == S(1)/2:                return exptrigsimp(trigsimp(unpolarify(                return simplify(trigsimp(unpolarify(                         fro(nu, z0).rewrite(besselj).rewrite(jn).expand(                             func=True)).subs(z0, z)))             elif nu.is_Integer and nu > 1:diff --git a/sympy/simplify/trigsimp.py b/sympy/simplify/trigsimp.py-- a/sympy/simplify/trigsimp.py++ b/sympy/simplify/trigsimp.py


Question: return trigsimpfunc(expr)  def exptrigsimp(expr, simplify=True):def exptrigsimp(expr):     """     Simplifies exponential / trigonometric / hyperbolic functions.    When ``simplify`` is True (default) the expression obtained after the    simplification step will be then be passed through simplify to    precondition it so the final transformations will be applied.      Examples     ========


Question: return min(*choices, key=count_ops)     newexpr = bottom_up(expr, exp_trig)     if simplify:        newexpr = newexpr.simplify()    # conversion from exp to hyperbolic    ex = newexpr.atoms(exp, S.Exp1)    ex = [ei for ei in ex if 1/ei not in ex]    ## sinh and cosh    for ei in ex:        e2 = ei**-2        if e2 in ex:            a = e2.args[0]/2 if not e2 is S.Exp1 else S.Half            newexpr = newexpr.subs((e2 + 1)*ei, 2*cosh(a))            newexpr = newexpr.subs((e2 - 1)*ei, 2*sinh(a))    ## exp ratios to tan and tanh    for ei in ex:        n, d = ei - 1, ei + 1        et = n/d        etinv = d/n  # not 1/et or else recursion errors arise        a = ei.args[0] if ei.func is exp else S.One        if a.is_Mul or a is S.ImaginaryUnit:            c = a.as_coefficient(I)            if c:                t = S.ImaginaryUnit*tan(c/2)                newexpr = newexpr.subs(etinv, 1/t)                newexpr = newexpr.subs(et, t)                continue        t = tanh(a/2)        newexpr = newexpr.subs(etinv, 1/t)        newexpr = newexpr.subs(et, t)    def f(rv):        if not rv.is_Mul:            return rv        rvd = rv.as_powers_dict()        newd = rvd.copy()        def signlog(expr, sign=1):            if expr is S.Exp1:                return sign, 1            elif isinstance(expr, exp):                return sign, expr.args[0]            elif sign == 1:                return signlog(-expr, sign=-1)            else:                return None, None        ee = rvd[S.Exp1]        for k in rvd:            if k.is_Add and len(k.args) == 2:                # k == c*(1 + sign*E**x)                c = k.args[0]                sign, x = signlog(k.args[1]/c)                if not x:                    continue                m = rvd[k]                newd[k] -= m                if ee == -x*m/2:                    # sinh and cosh                    newd[S.Exp1] -= ee                    ee = 0                    if sign == 1:                        newd[2*c*cosh(x/2)] += m                    else:                        newd[-2*c*sinh(x/2)] += m                elif newd[1 - sign*S.Exp1**x] == -m:                    # tanh                    del newd[1 - sign*S.Exp1**x]                    if sign == 1:                        newd[-c/tanh(x/2)] += m                    else:                        newd[-c*tanh(x/2)] += m                else:                    newd[1 + sign*S.Exp1**x] += m                    newd[c] += m        return Mul(*[k**newd[k] for k in newd])    newexpr = bottom_up(newexpr, f)      # sin/cos and sinh/cosh ratios to tan and tanh, respectively     if newexpr.has(HyperbolicFunction):


Question: """     from sympy import simplify, lcm_list    from sympy.functions.elementary.trigonometric import TrigonometricFunction    from sympy.functions.elementary.complexes import Abs    from sympy.functions.elementary.trigonometric import (        TrigonometricFunction, sin, cos, csc, sec)     from sympy.solvers.decompogen import decompogen    from sympy.core.relational import Relational    def _check(orig_f, period):        '''Return the checked period or raise an error.'''        new_f = orig_f.subs(symbol, symbol + period)        if new_f.equals(orig_f):            return period        else:            raise NotImplementedError(filldedent('''                The period of the given function cannot be verified.                When `%s` was replaced with `%s + %s` in `%s`, the result                was `%s` which was not recognized as being the same as                the original function.                So either the period was wrong or the two forms were                not recognized as being equal.                Set check=False to obtain the value.''' %                (symbol, symbol, period, orig_f, new_f)))      orig_f = f     f = simplify(orig_f)     period = None     if not f.has(symbol):    if symbol not in f.free_symbols:         return S.Zero     if isinstance(f, Relational):        f = f.lhs - f.rhs     if isinstance(f, TrigonometricFunction):         try:             period = f.period(symbol)         except NotImplementedError:             pass     if isinstance(f, Abs):        arg = f.args[0]        if isinstance(arg, (sec, csc, cos)):            # all but tan and cot might have a            # a period that is half as large            # so recast as sin            arg = sin(arg.args[0])        period = periodicity(arg, symbol)        if period is not None and isinstance(arg, sin):            # the argument of Abs was a trigonometric other than            # cot or tan; test to see if the half-period            # is valid. Abs(arg) has behaviour equivalent to            # orig_f, so use that for test:            orig_f = Abs(arg)            try:                return _check(orig_f, period/2)            except NotImplementedError as err:                if check:                    raise NotImplementedError(err)            # else let new orig_f and period be            # checked below     if f.is_Pow:         base, expo = f.args         base_has_sym = base.has(symbol)

periodicity(Abs(sin(x)),x) return 2pi periodicity(Abs(sin(x)),x) returns 2pi instead of pi periodicity(x 2, x) give recursion error and It fixes issue it will stop any relational Expression from entering into infinite recursion and return None It improves the periodicity of absolute trigonometric function issue


Question: if period is not None:         if check:            if orig_f.subs(symbol, symbol + period) == orig_f:                return period            else:                raise NotImplementedError(filldedent('''                    The period of the given function cannot be verified.                    Set check=False to obtain the value.'''))            return _check(orig_f, period)         return period      return Nonediff --git a/sympy/solvers/decompogen.py b/sympy/solvers/decompogen.py-- a/sympy/solvers/decompogen.py++ b/sympy/solvers/decompogen.py


Question: from sympy.core import Function, Pow, sympifyfrom sympy.core import (Function, Pow, sympify, Expr)from sympy.core.relational import Relational from sympy.polys import Poly, decomposefrom sympy.utilities.misc import func_name   def decompogen(f, symbol):


Question: """     f = sympify(f)<ins>    if not isinstance(f, Expr) or isinstance(f, Relational):        raise TypeError('expecting Expr but got: `%s`' % func_name(f))    if symbol not in f.free_symbols:        return [f]</ins>     result = []      # ===== Simple Functions ===== #


Question: >>> from sympy.abc import x      >>> AccumBounds(0, 1) + AccumBounds(1, 2)    <1, 3>    AccumBounds(1, 3)      >>> AccumBounds(0, 1) - AccumBounds(0, 2)    <-2, 1>    AccumBounds(-2, 1)      >>> AccumBounds(-2, 3)*AccumBounds(-1, 1)    <-3, 3>    AccumBounds(-3, 3)      >>> AccumBounds(1, 2)*AccumBounds(3, 5)    <3, 10>    AccumBounds(3, 10)      The exponentiation of AccumulationBounds is defined     as follows:

AccumBounds needs recreatable str/srepr The str and srepr should be recreatable. The pretty printer should be the only thing that prints the pretty form.


Question: AccumulationBounds object is neglected.      >>> AccumBounds(-1, 4)**(S(1)/2)    <0, 2>    AccumBounds(0, 2)      >>> AccumBounds(1, 2)**2    <1, 4>    AccumBounds(1, 4)      >>> AccumBounds(-1, oo)**(-1)    <-oo, oo>    AccumBounds(-oo, oo)      Note: `<a, b>^2` is not same as `<a, b>*<a, b>`      >>> AccumBounds(-1, 1)**2    <0, 1>    AccumBounds(0, 1)      >>> AccumBounds(1, 3) < 4     True


Question: is defined as `f(\langle a, b\rangle) = \{ f(x) \mid a \le x \le b \}`      >>> sin(AccumBounds(pi/6, pi/3))    <1/2, sqrt(3)/2>    AccumBounds(1/2, sqrt(3)/2)      >>> exp(AccumBounds(0, 1))    <1, E>    AccumBounds(1, E)      >>> log(AccumBounds(1, E))    <0, 1>    AccumBounds(0, 1)      Some symbol in an expression can be substituted for a AccumulationBounds     object. But it doesn't necessarily evaluate the AccumulationBounds for


Question: the form it is used for substituion. For example:      >>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1))    <-1, 4>    AccumBounds(-1, 4)      >>> ((x + 1)**2).subs(x, AccumBounds(-1, 1))    <0, 4>    AccumBounds(0, 4)      References     ==========


Question: >>> from sympy import AccumBounds, FiniteSet         >>> AccumBounds(1, 3).intersection(AccumBounds(2, 4))        <2, 3>        AccumBounds(2, 3)          >>> AccumBounds(1, 3).intersection(AccumBounds(4, 6))         EmptySet()diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py


Question: return self._print_seq(i.args[:2], left, right)     def _print_AccumuBounds(self, i):    def _print_AccumulationBounds(self, i):         left = '<'         right = '>' diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


Question: return fin.format(**{'a': a, 'b': b, 'm': m})      def _print_AccumulationBounds(self, i):        left = '<'        right = '>'        return "%s%s, %s%s" % \                (left, self._print(i.min), self._print(i.max), right)        return "AccumBounds(%s, %s)" % (self._print(i.min), self._print(i.max))      def _print_Inverse(self, I):         return "%s^-1" % self.parenthesize(I.arg, PRECEDENCE["Pow"])


Question: from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.power import Powfrom sympy.core.relational import Equalityfrom sympy.core.relational import Equality, Relational from sympy.core.singleton import Singleton from sympy.core.symbol import Dummy from sympy.core.rules import Transform

implement Piecewise rewriting for Min and Max This was mention in . I am just puttng this here as a separate issue.


Question: from sympy.functions.elementary.integers import floor from sympy.logic.boolalg import And <ins>def _minmax_as_Piecewise(op, *args):    # helper for Min/Max rewrite as Piecewise    from sympy.functions.elementary.piecewise import Piecewise    ec = []    for i, a in enumerate(args):        c = []        for j in range(i + 1, len(args)):            c.append(Relational(a, args[j], op))        ec.append((a, And(*c)))    return Piecewise(*ec)</ins> class IdentityFunction(with_metaclass(Singleton, Lambda)):     """     The identity function


Question: return Add(*[j*Mul(*[Heaviside(j - i) for i in args if i!=j]) \                 for j in args]) <ins>    def _eval_rewrite_as_Piecewise(self, *args):        return _minmax_as_Piecewise('>=', *args)</ins>     def _eval_is_positive(self):         return fuzzy_or(a.is_positive for a in self.args)


Question: return Add(*[j*Mul(*[Heaviside(i-j) for i in args if i!=j]) \                 for j in args]) <ins>    def _eval_rewrite_as_Piecewise(self, *args):        return _minmax_as_Piecewise('<=', *args)</ins>     def _eval_is_positive(self):         return fuzzy_and(a.is_positive for a in self.args)


Question: [(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()]     )) <del>    def _print_Integer(self, e):        return '%s(%d)' % (self._module_format('mpmath.mpf'), e)</del>     def _print_Float(self, e):         # XXX: This does not handle setting mpmath.mp.dps. It is assumed that         # the caller of the lambdified function will have set it to sufficient

Test failures on non-NumPy environment Following tests fail on where NumPy is not installed: Temporarily fixed by : Following doctest fails:


Question: x = fzero             nint += int(no*(mpf_cmp(x or fzero, fzero) == no))         nint = from_int(nint)        return nint, fastlog(nint) + 10        return nint, INF      re_, im_, re_acc, im_acc = None, None, None, None

evalf with subs argument incorrectly evaluates expressions with floor returns instead of 20. (Python 3.6.1, SymPy 1.1.1). It seems that incorrect attribute is somehow attached to the result of , which is why 20 is then rounded to the nearest power of 2. Considering that works correctly, perhaps a fix would be to make pass its subs argument to first, i.e., act the same as Based on a


Question: if not result:                                 for root in _try_decompose(f):                                     _update_dict(result, root, 1)<ins>                        else:                            for r in _try_heuristics(f):                                _update_dict(result, r, 1)</ins>                     else:                         for root in _try_decompose(f):                             _update_dict(result, root, 1)

Eigenvalues of a 3 by 3 symbolic matrix are not found by .eigenvals throws Since the characteristic polynomial is cubic, it can be solved explicitly: returns three roots of the characteristic polynomial. I do not understand why these are not found by which returns (hence the failure of method). Declaring x as a real symbol does not help. Based on Stack Overflow post


Question: elif re.is_number:                 re = re._to_mpmath(prec, allow_ints=False)._mpf_                 reprec = prec            else:                raise NotImplementedError             if im == 0:                 im = None                 imprec = None             elif im.is_number:                 im = im._to_mpmath(prec, allow_ints=False)._mpf_                 imprec = prec            else:                raise NotImplementedError             r = re, im, reprec, imprec         except AttributeError:             raise NotImplementedError

UnboundLocalError in evalf I found this after changing the order of Mul args in Based on the code, I think the elif clauses that define reprec and imprec should have an . That appears to fix it, although I didn't try to debug to see why the arg order is mattering here.


Question: @classmethod     def eval(cls, n, k_sym=None, symbols=None):<ins>        if n is S.Infinity:            if k_sym is None:                return S.Infinity            else:                raise ValueError("Bell polynomial is not defined")        if n.is_negative or n.is_integer is False:            raise ValueError("a non-negative integer expected")</ins>         if n.is_Integer and n.is_nonnegative:             if k_sym is None:                 return Integer(cls._bell(int(n)))

bell(n).limit(n, oo) should be oo rather than bell(oo) should take the value infinity, but the current output is . As the Bell numbers represent the number of partitions of a set, it seems natural that should be able to be evaluated rather than be returned unevaluated. This issue is also in line with the recent fixes to the corresponding limit for the Fibonacci numbers and Lucas numbers. I'm new to Sympy, so I'd appreciate the opportunity to fix this bug myself if that's alright.


Question: # it's a hexadecimal (coming from a pickled object)                 # assume that it is in standard form                 num = list(num)<ins>                # If we're loading an object pickled in Python 2 into                # Python 3, we may need to strip a tailing 'L' because                # of a shim for int on Python 3, see issue #13470.                if num[1].endswith('L'):                    num[1] = num[1][:-1]</ins>                 num[1] = long(num[1], 16)                 _mpf_ = tuple(num)             else:

Python 2-3 pickle fails with float-containing expressions Dumping a pickled sympy expression containing a float in Python 2, then loading it in Python 3 generates an error. Here is a minimum working example, verified with sympy git commit (master at time of writing), Python 2.7 and Python 3.6: and the result:


Question: x, m = _peeloff_ipi(arg)                 if m:                     cothm = coth(m)                    if cotm is S.ComplexInfinity:                    if cothm is S.ComplexInfinity:                         return coth(x)                     else: # cothm == 0                         return tanh(x)

.subs on coth(log(tan(x))) errors for certain integral values from sympy import * x = Symbol('x') e = coth(log(tan(x))) print(e.subs(x, 2)) ... File "C:\Users\E\Desktop\sympy-master\sympy\functions\elementary\", line 590, in eval if cotm is S.ComplexInfinity: NameError: name 'cotm' is not defined Fails for 2, 3, 5, 6, 8, 9, 11, 12, 13, 15, 18, ... etc.


Question: # There is expression, which couldn't change by                 # as_numer_denom(). E.g. n**(2/3) + 1 --> (n**(2/3) + 1, 1).                 # We have to catch this case.                p = sum([self._eval_product(i, (k, a, n)) for i in p.as_coeff_Add()])                from sympy.concrete.summations import Sum                p = exp(Sum(log(p), (k, a, n)))             else:                 p = self._eval_product(p, (k, a, n))             return p / q

Product(n + 1 / 2k, [k, 0, n-1]) is incorrect from sympy import from import n,k p = Product(n + 1 / 2k, [k, 0, n-1]).doit() print(simplify(p)) 2(n(-n + 1)/2) + nn print(p.subs(n,2)) 9/2 This is incorrect- for example, the product for is . The correct expression involves the .


Question: out[j, i] = out[i, j]     return out <ins></ins> def jordan_cell(eigenval, n):     """     Create a Jordan block:

randMatrix won't generatte symmetric sparse matrices When setting the percent parameter to anything else than 100, randMatrix fails to generate symmetric matrices. Consider the following examples: ' ' ' In [1]: import sympy In [2]: from sympy.matrices import randMatrix In [3]: randMatrix(3, symmetric=True, percent=1) Out[3]: Matrix([ [13, 61, 13], [59, 29, 59], [88, 13, 61]]) In [4]: randMatrix(3, symmetric=True, percent=50) Out[4]: Matrix([ [90, 60, 0], [ 0, 0, 0], [60, 59, 25]]) In [7]: randMatrix(3, symmetric=True, percent=99) Out[7]: Matrix([ [0, 0, 19], [0, 0, 0], [0, 0, 0]]) In [9]: randMatrix(3, symmetric=True, percent=0) Out[9]: Matrix([ [78, 78, 61], [68, 8, 61], [22, 68, 8]]) ' ' ' Also, the documentation says , but the behaviour is the opposite. Setting it to 100 (default) produces the expected behaviour. The problem happens with both the released version from pypi and git master.


Question: >>> A == randMatrix(3, seed=1)     True     >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP    [0, 68, 43]    [0, 68,  0]    [0, 91, 34]    [77, 70,  0],    [70,  0,  0],    [ 0,  0, 88]     """     if c is None:         c = r     # Note that ``Random()`` is equivalent to ``Random(None)``     prng = prng or random.Random(seed)    if symmetric and r != c:        raise ValueError(            'For symmetric matrices, r must equal c, but %i != %i' % (r, c))     if not symmetric:         m = Matrix._new(r, c, lambda i, j: prng.randint(min, max))    else:        m = zeros(r)        for i in range(r):            for j in range(i, r):                m[i, j] = prng.randint(min, max)        for i in range(r):            for j in range(i):                m[i, j] = m[j, i]    if percent == 100:        return m    else:        z = int(r*c*percent // 100)        if percent == 100:            return m        z = int(r*c*(100 - percent) // 100)         m._mat[:z] = [S.Zero]*z         prng.shuffle(m._mat)        return m    # Symmetric case    if r != c:        raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c))    m = zeros(r)    ij = [(i, j) for i in range(r) for j in range(i, r)]    if percent != 100:        ij = prng.sample(ij, int(len(ij)*percent // 100))    for i, j in ij:        value = prng.randint(min, max)        m[i, j] = m[j, i] = value     return m


Question: elif (qinner*(q + qinner)).is_nonpositive:                 # |qinner| < |q| and have different sign                 return p<ins>        elif isinstance(p, Add):            # separating into modulus and non modulus            both_l = non_mod_l, mod_l = [], []            for arg in p.args:                both_l[isinstance(arg, cls)].append(arg)            # if q same for all            if mod_l and all(inner.args[1] == q for inner in mod_l):                net = Add(*non_mod_l) + Add(*[i.args[0] for i in mod_l])                return cls(net, q)        elif isinstance(p, Mul):            # separating into modulus and non modulus            both_l = non_mod_l, mod_l = [], []            for arg in p.args:                both_l[isinstance(arg, cls)].append(arg)            if mod_l and all(inner.args[1] == q for inner in mod_l):                # finding distributive term                non_mod_l = [cls(x, q) for x in non_mod_l]                mod = []                non_mod = []                for j in non_mod_l:                    if isinstance(j, cls):                        mod.append(j.args[0])                    else:                        non_mod.append(j)                prod_mod = Mul(*mod)                prod_non_mod = Mul(*non_mod)                prod_mod1 = Mul(*[i.args[0] for i in mod_l])                net = prod_mod1*prod_mod                return prod_non_mod*cls(net, q)</ins>         # XXX other possibilities?          # extract gcd; any further simplification should be done by the user

Mod(Mod(x + 1, 2) + 1, 2) should simplify to Mod(x, 2) From Also, something like could be simplified. Recursively.


Question: """         other = _sympify(other)        if not (other.is_Symbol or other.is_number):            raise TypeError("Input of type real symbol or Number expected")          if other is S.Infinity or other is S.NegativeInfinity:             if self.min is S.NegativeInfinity or self.max is S.Infinity:                 return True             return False         return And(self.min <= other and self.max >= other)        rv = And(self.min <= other, self.max >= other)        if rv not in (True, False):            raise TypeError("input failed to evaluate")        return rv      def intersection(self, other):         """diff --git a/sympy/core/basic.py b/sympy/core/basic.py-- a/sympy/core/basic.py++ b/sympy/core/basic.py

Undefined functions with number arguments should have is_number be False Original issue for : Original author:


Question: is_real = self.is_real         if is_real is False:             return False        is_number = self.is_number        if is_number is False:        if not self.is_number:             return False        # don't re-eval numbers that are already evaluated since        # this will create spurious precision         n, i = [p.evalf(2) if not p.is_Number else p             for p in self.as_real_imag()]        if not i.is_Number or not n.is_Number:        if not (i.is_Number and n.is_Number):             return False         if i:             # if _prec = 1 we can't decide and if not,diff --git a/sympy/core/expr.py b/sympy/core/expr.py-- a/sympy/core/expr.py++ b/sympy/core/expr.py


Question: @property     def is_number(self):        """Returns True if ``self`` has no free symbols.        It will be faster than ``if not self.free_symbols``, however, since        ``is_number`` will fail as soon as it hits a free symbol.        """Returns True if ``self`` has no free symbols and no        undefined functions (AppliedUndef, to be precise). It will be        faster than ``if not self.free_symbols``, however, since        ``is_number`` will fail as soon as it hits a free symbol        or undefined function.          Examples         ========         >>> from sympy import log, Integral        >>> from sympy import log, Integral, cos, sin, pi        >>> from sympy.core.function import Function         >>> from sympy.abc import x        >>> f = Function('f')          >>> x.is_number         False        >>> f(1).is_number        False         >>> (2*x).is_number         False        >>> (2 + log(2)).is_number        True         >>> (2 + Integral(2, x)).is_number         False         >>> (2 + Integral(2, (x, 1, 2))).is_number         True         Not all numbers are Numbers in the SymPy sense:        >>> pi.is_number, pi.is_Number        (True, False)        If something is a number it should evaluate to a number with        real and imaginary parts that are Numbers; the result may not        be comparable, however, since the real and/or imaginary part        of the result may not have precision.        >>> cos(1).is_number and cos(1).is_comparable        True        >>> z = cos(1)**2 + sin(1)**2 - 1        >>> z.is_number        True        >>> z.is_comparable        False        See Also        ========        sympy.core.basic.is_comparable         """         return all(obj.is_number for obj in self.args)


Question: simplify = flags.get('simplify', True)         # Except for expressions that contain units, only one of these should        # be necessary since if something is        # known to be a number it should also know that there are no        # free symbols. But is_number quits as soon as it hits a non-number        # whereas free_symbols goes until all free symbols have been collected,        # thus is_number should be faster. But a double check on free symbols        # is made just in case there is a discrepancy between the two.        free = self.free_symbols        if self.is_number or not free:            # if the following assertion fails then that object's free_symbols            # method needs attention: if an expression is a number it cannot            # have free symbols            assert not free        if self.is_number:             return True        free = self.free_symbols        if not free:            return True  # assume f(1) is some constant          # if we are only interested in some symbols and they are not in the         # free symbols then this expression is constant wrt those symbols


Question: def _n2(a, b):    """Return (a - b).evalf(2) if it, a and b are comparable, else None.    """Return (a - b).evalf(2) if a and b are comparable, else None.     This should only be used when a and b are already sympified.     """    if not all(i.is_number for i in (a, b)):        return    # /!\ if is very important (see issue 8245) not to    # /!\ it is very important (see issue 8245) not to     # use a re-evaluated number in the calculation of dif     if a.is_comparable and b.is_comparable:         dif = (a - b).evalf(2)diff --git a/sympy/core/function.py b/sympy/core/function.py-- a/sympy/core/function.py++ b/sympy/core/function.py


Question: function.     """     is_number = False     def __new__(cls, *args, **options):         args = list(map(sympify, args))         obj = super(AppliedUndef, cls).__new__(cls, *args, **options)diff --git a/sympy/functions/elementary/miscellaneous.py b/sympy/functions/elementary/miscellaneous.py-- a/sympy/functions/elementary/miscellaneous.py++ b/sympy/functions/elementary/miscellaneous.py


Question: from sympy.core.containers import Tuple from sympy.core.operations import LatticeOp, ShortCircuit from sympy.core.function import (Application, Lambda,    ArgumentIndexError, AppliedUndef)    ArgumentIndexError) from sympy.core.expr import Expr from sympy.core.mul import Mul from sympy.core.numbers import Rational


Question: # pre-filter, checking comparability of arguments             if not isinstance(arg, Expr) or arg.is_real is False or (                     arg.is_number and<del>                    not arg.has(AppliedUndef) and</del>                     not arg.is_comparable):                 raise ValueError("The argument '%s' is not comparable." % arg)


Question: code0 = self._print(temp)                 lines.append(code0)             return "\n".join(lines)        elif self._settings["contract"] and (lhs.has(IndexedBase) or        elif self._settings.get("contract", False) and (lhs.has(IndexedBase) or                 rhs.has(IndexedBase)):             # Here we check if there is looping to be done, and if so             # print the required loops.diff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py-- a/sympy/printing/pycode.py++ b/sympy/printing/pycode.py

Python code printer (pycode) should support Assignment There is a lookup on 'contract', either we should give it a default in the or we should make the code accessing use with a default.


Question: def _format_code(self, lines):         return lines <ins>    def _get_statement(self, codestring):        return "%s" % codestring</ins>     def _get_comment(self, text):         return "  # {0}".format(text)


Question: return self[i, j]             elif pos <= j < pos + other.cols:                 return other[i, j - pos]            return self[i, j - pos - other.cols]            return self[i, j - other.cols]          return self._new(self.rows, self.cols + other.cols,                          lambda i, j: entry(i, j))

Matrix.col_insert() no longer seems to work correctly. Example: The 3 x 3 identify matrix to the right of the columns of twos is shifted from the bottom three rows to the top three rows. Do you think this has to do with your matrix refactor?


Question: else:             return 'O(%s)' % self.stringify(expr.args, ', ', 0)     def _print_Ordinal(self, expr):        return expr.__str__()     def _print_Cycle(self, expr):         return expr.__str__() diff --git a/sympy/sets/__init__.py b/sympy/sets/__init__.py-- a/sympy/sets/__init__.py++ b/sympy/sets/__init__.py

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


Question: from .fancysets import ImageSet, Range, ComplexRegion from .contains import Contains from .conditionset import ConditionSetfrom .ordinals import Ordinal, OmegaPower, ord0 from ..core.singleton import S Reals = S.Reals del Sdiff --git a/sympy/sets/ordinals.py b/sympy/sets/ordinals.pynew file mode 100644-- /dev/null++ b/sympy/sets/ordinals.py


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


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

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


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


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

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


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

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


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

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


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


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


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


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

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


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


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

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


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

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


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


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


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


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


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


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

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


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


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


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

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


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


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

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


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


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


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


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

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


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

Matrix determinant raises Invalid NaN comparison with particular symbolic entries from sympy import from import a f = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) f(1) 0 f(2) -a f(3) 2a(a + 2) + 2a(2a + 1) - 3a(2a + 2) f(4) 0 f(5) nan f(6) Traceback (most recent call last): File "<pyshell", line 1, in <modulef(6) File "<pyshell", line 1, in <lambdaf = lambda n: det(Matrix([[i + aj for i in range(n)] for j in range(n)])) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 53, in det return Determinant(matexpr).doit() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\expressions\", line 37, in doit return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 270, in evaldeterminant return () File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 416, in det return self.evaldetbareiss() File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 213, in evaldetbareiss return cancel(bareiss(self)) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry),


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

pivotval) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 211, in bareiss return signbareiss(( - 1, - 1, entry), pivotval) [Previous line repeated 1 more times] File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 55, in new rows, cols, flatlist = cls.handlecreationinputs(args, kwargs) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in handlecreationinputs for j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 2041, in <listcompfor j in range(cols)]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\matrices\", line 208, in entry cancel(ret) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\polys\", line 6423, in cancel f = factorterms(f, radical=True) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1193, in factorterms return do(expr) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in do [do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1189, in <listcomp*[do(a) for a in p.args]) File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in do if all(a.


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

ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 1171, in <genexprif all(a.ascoeffMul()[0] < 0 for a in listargs): File "C:\Users\E\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\", line 323, in lt raise TypeError("Invalid NaN comparison") TypeError: Invalid NaN comparison Correct me if I'm wrong but isn't the Bareiss algorithm only valid for integer matrices, which cannot be assumed here?


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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

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


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


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

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


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


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


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


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

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


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

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


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


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


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

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


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

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


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


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


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


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

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


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

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


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


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


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


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

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


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


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

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


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


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

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


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


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

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


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


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

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


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

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