{"query_id": "q-en-astropy__astropy-11693-17bb2019924814a4b9f0352623cc9b397e57044b8ca4c9f7fefe791e4009ad89", "query": "'WCS.allworld2pix' failed to converge when plotting WCS with non linear distortions (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", "commid": "sympy__sympy-13551"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13574-3e60cf8f6ac778bb91a16f0ab17594097f902ae450c5bd290b01304ee98ccb4f", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13574-491f384d94d4f6332639e9ac1e7ce1bb0109c37833b1b0567970422c3eb9367e", "text": " out[j, i] = out[i, j] return out def jordan_cell(eigenval, n): \"\"\" Create a Jordan block:", "commid": "sympy__sympy-13574"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13574-3e60cf8f6ac778bb91a16f0ab17594097f902ae450c5bd290b01304ee98ccb4f", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13574-b4a6bb1ac4d45aeed729e4719ccec2d79388e2a9a44d89947072706904381cb3", "text": " >>> 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", "commid": "sympy__sympy-13574"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13581-eedf92d45cb9316929d9f679d4b557f85d14df76442934a7bcdc0af80c5cfca6", "query": "Mod(Mod(x + 1, 2) + 1, 2) should simplify to Mod(x, 2) From Also, something like could be simplified. Recursively.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13581-0759a0db96df40df0fbbe86f2e9a42c651ccba7a82a455b7bc778dd1269241ee", "text": " elif (qinner*(q + qinner)).is_nonpositive: # |qinner| < |q| and have different sign return p 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) # XXX other possibilities? # extract gcd; any further simplification should be done by the user", "commid": "sympy__sympy-13581"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13619-5788bbb397c89b07d5e37f878ad623ad6f15993efc2b2ca8a75a063b07b2a2f2", "query": "Undefined functions with number arguments should have is_number be False Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-13619-0691dfd547f9dbd64041726225fd4b8fc1a2132f6aa018fa4ba40c199fa68329", "text": " \"\"\" 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", "commid": "sympy__sympy-13619"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13619-5788bbb397c89b07d5e37f878ad623ad6f15993efc2b2ca8a75a063b07b2a2f2", "query": "Undefined functions with number arguments should have is_number be False Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-13619-98907065e69e721dc608cae7846583712962ced846104aa04199da62fba7c63c", "text": " 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", "commid": "sympy__sympy-13619"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13619-5788bbb397c89b07d5e37f878ad623ad6f15993efc2b2ca8a75a063b07b2a2f2", "query": "Undefined functions with number arguments should have is_number be False Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-13619-e2421c5bcd48ad4570948d2132a983b75b3fb1c20f41002ae1c5586127cc1a00", "text": " @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) ", "commid": "sympy__sympy-13619"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13619-5788bbb397c89b07d5e37f878ad623ad6f15993efc2b2ca8a75a063b07b2a2f2", "query": "Undefined functions with number arguments should have is_number be False Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-13619-d72492607d3cd86a6f10a81a22f27ee4d8d9cece34ca4c16ee6ed303a52085c2", "text": " 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", "commid": "sympy__sympy-13619"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13619-5788bbb397c89b07d5e37f878ad623ad6f15993efc2b2ca8a75a063b07b2a2f2", "query": "Undefined functions with number arguments should have is_number be False Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-13619-09825670115294dad7038e8885267a1de16a1e96ad2bbf8d7dae264b844dc1c3", "text": " 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", "commid": "sympy__sympy-13619"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13619-5788bbb397c89b07d5e37f878ad623ad6f15993efc2b2ca8a75a063b07b2a2f2", "query": "Undefined functions with number arguments should have is_number be False Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-13619-9908641527cc7edc6b8ca2d3d0604cb376c5e0a6d454a7daf6fe601e2c0a073b", "text": " 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", "commid": "sympy__sympy-13619"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13619-5788bbb397c89b07d5e37f878ad623ad6f15993efc2b2ca8a75a063b07b2a2f2", "query": "Undefined functions with number arguments should have is_number be False Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-13619-5c81b45c4702b03f2751149a79e9f8eef6b4eb47cdb1055ce85eed08679a9eb5", "text": " 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", "commid": "sympy__sympy-13619"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13619-5788bbb397c89b07d5e37f878ad623ad6f15993efc2b2ca8a75a063b07b2a2f2", "query": "Undefined functions with number arguments should have is_number be False Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-13619-e2512c865c07c0cebd268a5f12b8bf00216c9ac5d4e3c85659b809a3e86437d0", "text": " # pre-filter, checking comparability of arguments if not isinstance(arg, Expr) or arg.is_real is False or ( arg.is_number and not arg.has(AppliedUndef) and not arg.is_comparable): raise ValueError(\"The argument '%s' is not comparable.\" % arg)", "commid": "sympy__sympy-13619"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13624-9f6e1698b408fc63493c78702daf59308a0d3eab17b899e3374615bdc23a1c92", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13624-1f57aef464f25ff5392da863f38e60eae09e663bb21c4928bcd23533c10da5c0", "text": " 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", "commid": "sympy__sympy-13624"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13624-9f6e1698b408fc63493c78702daf59308a0d3eab17b899e3374615bdc23a1c92", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13624-723976239381d90788216bdef983f3b9ac645b237b1c2e2b43f45ced27e2bb53", "text": " def _format_code(self, lines): return lines def _get_statement(self, codestring): return \"%s\" % codestring def _get_comment(self, text): return \" # {0}\".format(text)", "commid": "sympy__sympy-13624"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13647-9d8714313229af68922566b8d1941823fc8dac82eae8c51459658a40b6233abe", "query": "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?", "positive_passages": [{"docid": "doc-en-sympy__sympy-13647-b548212cb5fa3c4090106d89556dc5f4de5dc1157a3749da30b2bfba0b42e8b9", "text": " 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))", "commid": "sympy__sympy-13647"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13682-782f5d153a32b16be53f2d63b596219dd934b6d7834da56480b23d7b9a1de529", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13682-ea7a18ea167a9bf9f2ed6afa04f350ed3fb05bcb90512d95bbd10015457b08e3", "text": " 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", "commid": "sympy__sympy-13682"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13682-782f5d153a32b16be53f2d63b596219dd934b6d7834da56480b23d7b9a1de529", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13682-cda32e422432ed481c5119bc2e877f19328b8fb5f6991aa784279de874bfa55e", "text": " 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", "commid": "sympy__sympy-13682"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13682-782f5d153a32b16be53f2d63b596219dd934b6d7834da56480b23d7b9a1de529", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13682-cc4a9fbde4f2a2e365502341a4f70d91f676ccd973fb71cc65955483067b3d9c", "text": "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", "commid": "sympy__sympy-13682"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13744-8745621163bb85252820931ec9e667c6be775e01a22dbd2edbce3379c56ded93", "query": "coset_table doctest failure (Fatal Python error: Cannot recover from stack overflow.) See https://travis- Here is the test header", "positive_passages": [{"docid": "doc-en-sympy__sympy-13744-177e65ca1bfe2374d6b93aa045af88e08d145e7d55a0238e678153d3f030ad3d", "text": " 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", "commid": "sympy__sympy-13744"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13744-8745621163bb85252820931ec9e667c6be775e01a22dbd2edbce3379c56ded93", "query": "coset_table doctest failure (Fatal Python error: Cannot recover from stack overflow.) See https://travis- Here is the test header", "positive_passages": [{"docid": "doc-en-sympy__sympy-13744-a7395bd985ea43736fe1d4ce1a743668d91127f20df7a879849167eb26e6d809", "text": " s1 = s1.subword(0, len(s1)-1) s2 = s2*g**-1 if len(s1) - len(s2) < 0: #print(\"this\", len(s1)-len(s2)) if s2 not in self.rules: if not check: self._add_rule(s2, s1)", "commid": "sympy__sympy-13744"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13757-1497d767c3a6fab13198ad1b790478cb2f8350d354654573637f8001891b42ed", "query": "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", "positive_passages": [{"docid": "doc-en-sympy__sympy-13757-37d309bf5e063274afd1a13b156d4a3f480c99af2f47355a786aa8cfb44be006", "text": " is_commutative = True is_Poly = True _op_priority = 10.001 def __new__(cls, rep, *gens, **args): \"\"\"Create a new polynomial instance out of something useful. \"\"\"", "commid": "sympy__sympy-13757"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13761-e13b22fddec39d9094455952e5880c264056262316a713b0ca9c450bad623b81", "query": "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).", "positive_passages": [{"docid": "doc-en-sympy__sympy-13761-5b5d94b2efa8c50b2d326215430dbc6bc8b664e5e52e8e25d5e19d1501a4b5d2", "text": " bernoulli(2*k)*x**(2*k - 1)/factorial(2*k)) class sinc(TrigonometricFunction):class sinc(Function): r\"\"\"Represents unnormalized sinc function Examples", "commid": "sympy__sympy-13761"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13768-a8cd9e9a06a18dcf17de8fff22d8d35d7c3ed8fa0b27c7c4a54f8d17520969a8", "query": "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", "positive_passages": [{"docid": "doc-en-sympy__sympy-13768-0af97d6a0401df3a5b0d0cc0ad2e397f6e716524e8924db84dad5d3bf45c0026", "text": " from sympy.core.compatibility import (is_sequence, default_sort_key, range, NotIterable) from sympy.utilities.exceptions import SymPyDeprecationWarning from types import FunctionType ", "commid": "sympy__sympy-13768"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13768-a8cd9e9a06a18dcf17de8fff22d8d35d7c3ed8fa0b27c7c4a54f8d17520969a8", "query": "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", "positive_passages": [{"docid": "doc-en-sympy__sympy-13768-972ea32492ded5aef828c22ae1b690797fc57ad91c1daf3ba4dee52a8a75326e", "text": " # https://github.com/sympy/sympy/pull/12854 class MatrixDeprecated(MatrixCommon): \"\"\"A class to house deprecated matrix methods.\"\"\" 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)) def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify): return self.charpoly(x=x)", "commid": "sympy__sympy-13768"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13768-a8cd9e9a06a18dcf17de8fff22d8d35d7c3ed8fa0b27c7c4a54f8d17520969a8", "query": "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", "positive_passages": [{"docid": "doc-en-sympy__sympy-13768-913dadfe531e98cf723c5ee1331ba260b03934a68c07914695a95dc4e0f402c5", "text": " 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 ========", "commid": "sympy__sympy-13768"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13768-a8cd9e9a06a18dcf17de8fff22d8d35d7c3ed8fa0b27c7c4a54f8d17520969a8", "query": "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", "positive_passages": [{"docid": "doc-en-sympy__sympy-13768-02779e0999616bb4d429db5008e5e81c172b07b16b9fcb1609c32bf7e5a07e14", "text": " 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:", "commid": "sympy__sympy-13768"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13773-8b0cdab22ee9c983f319afa0937ccf53edf7dbce3666332b4477a5420a6d87dd", "query": "@ (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", "positive_passages": [{"docid": "doc-en-sympy__sympy-13773-850e194993aaa91ebf9b4e87d39b88eb367773a74ebff00e460913795758c8e5", "text": " @call_highest_priority('__rmatmul__') def __matmul__(self, other): other = _matrixify(other) if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False): return NotImplemented return self.__mul__(other) @call_highest_priority('__rmul__')", "commid": "sympy__sympy-13773"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13773-8b0cdab22ee9c983f319afa0937ccf53edf7dbce3666332b4477a5420a6d87dd", "query": "@ (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", "positive_passages": [{"docid": "doc-en-sympy__sympy-13773-6e2c9b9aca504a29f55dce9f05c43a2d1dcc7832a04e07a03f424bc020519a9b", "text": " @call_highest_priority('__matmul__') def __rmatmul__(self, other): other = _matrixify(other) if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False): return NotImplemented return self.__rmul__(other) @call_highest_priority('__mul__')", "commid": "sympy__sympy-13773"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13798-593504aa53f9e1dabc299d2f7a6622b849d50329d9123cf59cffb7d256c689f2", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13798-bdca27ac0fe1132a050c2025d63de21d7bba95aeafaccda149be43d1b4160261", "text": " \"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 = {'(': ')', '[': ']'}", "commid": "sympy__sympy-13798"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13806-8bd562e3dd8a0270632e5f4b7d9a705e72349803a3fffa086b43736d92a38941", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13806-c992c7f71de6ae87f7008f2b2b68e6a8e18bb695bf2daef2af6b6c59a54fa851", "text": " def _print_Mul(self, expr): from sympy.core.power import Pow from sympy.physics.units import Quantity include_parens = False if _coeff_isneg(expr): expr = -expr", "commid": "sympy__sympy-13806"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13806-8bd562e3dd8a0270632e5f4b7d9a705e72349803a3fffa086b43736d92a38941", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13806-3f060923f1d81058951a1f81eb4e8cb5445b98ef804e29cc8a98fb99d55dc91d", "text": " 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)", "commid": "sympy__sympy-13806"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13806-8bd562e3dd8a0270632e5f4b7d9a705e72349803a3fffa086b43736d92a38941", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13806-c1619b58cbeae8abc09311f1a4e729c5f3f0a6eb89255314b28ddf66d2bd65fe", "text": " 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", "commid": "sympy__sympy-13806"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13806-8bd562e3dd8a0270632e5f4b7d9a705e72349803a3fffa086b43736d92a38941", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13806-065c198e859d29f06a09c0f4462b7c6588219548fbace8fb4e6f19b14dfa876c", "text": " 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:", "commid": "sympy__sympy-13806"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13806-8bd562e3dd8a0270632e5f4b7d9a705e72349803a3fffa086b43736d92a38941", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13806-c95be521d2fde4e9aadb1ddb7921b0b3c63d38cdde6352cdd88113ac09680291", "text": " 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", "commid": "sympy__sympy-13806"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13806-8bd562e3dd8a0270632e5f4b7d9a705e72349803a3fffa086b43736d92a38941", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13806-fd25fe8602e0555a561fd17366cb0e017edc804c437e519adf40a55602b1a1e8", "text": " \"\"\"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())", "commid": "sympy__sympy-13806"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13808-a0a174dfc2900f3891cbd63d5aba900909acee507a0cface4599b145a6cec3d4", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13808-241e39a1230694c5649c096a4cdebce4bf7af78267562257c64af3399dae5bc3", "text": " 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)", "commid": "sympy__sympy-13808"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13808-a0a174dfc2900f3891cbd63d5aba900909acee507a0cface4599b145a6cec3d4", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13808-df990b9fd406191e397f851f3a4a10215156e4abe3704c21dc6b7eb5f1a8689f", "text": " 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", "commid": "sympy__sympy-13808"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13808-a0a174dfc2900f3891cbd63d5aba900909acee507a0cface4599b145a6cec3d4", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13808-4ad0a5fb2ea61c232d5d4b40bc847a7b914c02092aadbefa7235b276d0452fa6", "text": " function = ret continue 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))) if antideriv is None: undone_limits.append(xab) function = self.func(*([function] + [xab])).factor()", "commid": "sympy__sympy-13808"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13840-18a2f47b2560f11e31935acddc723a3a55b31af8d410c9bbe68aef65885d29dc", "query": "Max & Min converting using SymPy Why many languages likes js and R cannot be converted from Max & Min? !", "positive_passages": [{"docid": "doc-en-sympy__sympy-13840-8e8cc0df502b5f9dc4cec8bbeca9cde9926a85521370ff041ee132798a590c2e", "text": " known_functions = { #\"Abs\": [(lambda x: not x.is_integer, \"fabs\")], \"Abs\": \"abs\", \"gamma\": \"gamma\", \"sin\": \"sin\", \"cos\": \"cos\", \"tan\": \"tan\",", "commid": "sympy__sympy-13840"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13840-18a2f47b2560f11e31935acddc723a3a55b31af8d410c9bbe68aef65885d29dc", "query": "Max & Min converting using SymPy Why many languages likes js and R cannot be converted from Max & Min? !", "positive_passages": [{"docid": "doc-en-sympy__sympy-13840-6907c2c2e7e357d3a0f27ecc904fa4a64d3772dc0a607bb94777e79e73534ef0", "text": " \"floor\": \"floor\", \"ceiling\": \"ceiling\", \"sign\": \"sign\", \"Max\": \"max\", \"Min\": \"min\", \"factorial\": \"factorial\", \"gamma\": \"gamma\", \"digamma\": \"digamma\", \"trigamma\": \"trigamma\", \"beta\": \"beta\", } # These are the core reserved words in the R language. Taken from:", "commid": "sympy__sympy-13840"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13852-e8d8ac3ad161c36fd1cc3f5591a59f53b07faf537e961d2e141b2afabdff71ac", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13852-1ac287383b8dfa5c12af72b4bdfcd546b080cc7d8090eac5abe2bacecad82b10", "text": " \"\"\" 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 #####################################", "commid": "sympy__sympy-13852"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13852-e8d8ac3ad161c36fd1cc3f5591a59f53b07faf537e961d2e141b2afabdff71ac", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13852-866b46d6316a646c69bcb2b067958bd98e7dcdd1ca000b225ed487f6f3f67071", "text": " >>> 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) ", "commid": "sympy__sympy-13852"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13852-e8d8ac3ad161c36fd1cc3f5591a59f53b07faf537e961d2e141b2afabdff71ac", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13852-fc538ab565d9f8575ad469e3d714b00be625a243f8bd2079a7bf27d91df6d40f", "text": " 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", "commid": "sympy__sympy-13852"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13852-e8d8ac3ad161c36fd1cc3f5591a59f53b07faf537e961d2e141b2afabdff71ac", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13852-0211eec3d4ec6b1444c8f6f0a5037d5c29264a542d85ae12dbaf51d931cfa2da", "text": " 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)", "commid": "sympy__sympy-13852"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13865-596d8936068da4e4075dab7ed015a26727071d1beaa6c2e245f0e08ce1058c62", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13865-4580c342979f76782056b68ee50d92722fe2f3c31933b6506b0558a3567a222b", "text": " 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])", "commid": "sympy__sympy-13865"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13877-dc4da66f5b09b03c098854dde379cfc2e68bdbbc5da530decb7f6c57b5888f5c", "query": "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 \"from sympy.core.function import expand_mul from sympy.core.power import Pow from sympy.core.symbol import (Symbol, Dummy, symbols, _uniquely_named_symbol)", "commid": "sympy__sympy-13877"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13877-dc4da66f5b09b03c098854dde379cfc2e68bdbbc5da530decb7f6c57b5888f5c", "query": "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 \"from 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", "commid": "sympy__sympy-13877"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13877-dc4da66f5b09b03c098854dde379cfc2e68bdbbc5da530decb7f6c57b5888f5c", "query": "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 \"def _is_zero_after_expand_mul(x): \"\"\"Tests by expand_mul only, suitable for polynomials and rational functions.\"\"\" return expand_mul(x) == 0 class DeferredVector(Symbol, NotIterable): \"\"\"A vector whose components are deferred (e.g. for use with lambdify) ", "commid": "sympy__sympy-13877"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13877-dc4da66f5b09b03c098854dde379cfc2e68bdbbc5da530decb7f6c57b5888f5c", "query": "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 \" # 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) # 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):", "commid": "sympy__sympy-13877"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13877-dc4da66f5b09b03c098854dde379cfc2e68bdbbc5da530decb7f6c57b5888f5c", "query": "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 \" # 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", "commid": "sympy__sympy-13877"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13877-dc4da66f5b09b03c098854dde379cfc2e68bdbbc5da530decb7f6c57b5888f5c", "query": "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 \"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):", "commid": "sympy__sympy-13877"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13895-f09881c35d5071947111b2e9e5e26d7d848dff88f64ae624d1d73f9b89ce9c96", "query": "(-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", "positive_passages": [{"docid": "doc-en-sympy__sympy-13895-10fc520c43abf6d406961de118eb2a2bf5e7960f2b638ab45adbde1ca4cf3cc5", "text": " 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", "commid": "sympy__sympy-13895"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13895-f09881c35d5071947111b2e9e5e26d7d848dff88f64ae624d1d73f9b89ce9c96", "query": "(-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", "positive_passages": [{"docid": "doc-en-sympy__sympy-13895-118736f0343cb78232221506ec5365eb00fb0ca4380f1cdae69b134244e59518", "text": " 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):", "commid": "sympy__sympy-13895"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13903-b571fa52afba675f9dfd85f2ce9092083e38f9f0277aba29e78e1f9e8b9f9adf", "query": "max & min i found most language cannot be converted into max & min like octave,Fortran and others (js and R have been fix , thx ;) )", "positive_passages": [{"docid": "doc-en-sympy__sympy-13903-a7781587b4f9ee85d93422dc2512a90ecd8ca79fd3567c37eeea3ff8a61e8a36", "text": " \"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", "commid": "sympy__sympy-13903"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13903-b571fa52afba675f9dfd85f2ce9092083e38f9f0277aba29e78e1f9e8b9f9adf", "query": "max & min i found most language cannot be converted into max & min like octave,Fortran and others (js and R have been fix , thx ;) )", "positive_passages": [{"docid": "doc-en-sympy__sympy-13903-bd786acd1f365fa6b68ada3ba1e728513560ba2269c480cd130ff39b75054959", "text": " \"laguerre\": \"laguerreL\", \"li\": \"logint\", \"loggamma\": \"gammaln\", \"Max\": \"max\", \"Min\": \"min\", \"polygamma\": \"psi\", \"Shi\": \"sinhint\", \"Si\": \"sinint\",", "commid": "sympy__sympy-13903"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13903-b571fa52afba675f9dfd85f2ce9092083e38f9f0277aba29e78e1f9e8b9f9adf", "query": "max & min i found most language cannot be converted into max & min like octave,Fortran and others (js and R have been fix , thx ;) )", "positive_passages": [{"docid": "doc-en-sympy__sympy-13903-31a561e87e9a356f65e52937e83c7ecbaf0d40de81fce42b1f7dd6d13fc44642", "text": " # assignment (if False). FIXME: this should be looked a more carefully # for Octave. def __init__(self, settings={}): super(OctaveCodePrinter, self).__init__(settings) self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))", "commid": "sympy__sympy-13903"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13903-b571fa52afba675f9dfd85f2ce9092083e38f9f0277aba29e78e1f9e8b9f9adf", "query": "max & min i found most language cannot be converted into max & min like octave,Fortran and others (js and R have been fix , thx ;) )", "positive_passages": [{"docid": "doc-en-sympy__sympy-13903-48a30b325aae54c5105f894a001df6fb8e73265723291ad28b76b26703db1701", "text": " return \"lambertw(\" + args + \")\" 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 def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting", "commid": "sympy__sympy-13903"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13915-69006d2b10982ed4d50b7399aada67b18d2db3178135eb25744e9ebdc2eb9cd9", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13915-6d0209adc692345281df1a645f44723d1ad56948ab125178155035b4ef9dad80", "text": " changed = False for b, e in c_powers: if e.is_zero: # 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 continue if e is S.One: if b.is_Number:", "commid": "sympy__sympy-13915"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13962-bd0fc90c2a55d8b5d28b9535f4d431b0b1f57079c5fa3be362c9a24a4ff1a4fc", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13962-e7e3fb09ca1c83f3e8f00b119c05604a3404806167e82e9db8fcb28576d66e13", "text": " \"order\": None, \"full_prec\": \"auto\", \"sympy_integers\": False, \"abbrev\": False, } _relationals = dict()", "commid": "sympy__sympy-13962"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13962-bd0fc90c2a55d8b5d28b9535f4d431b0b1f57079c5fa3be362c9a24a4ff1a4fc", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13962-d9af59ff397bf2138c2f5e1667b3f5962055db41edfc9f81bb0bbda9d3b60e64", "text": " return r' \\ '.join(self._print(set) for set in expr.args) def _print_Quantity(self, expr): if self._settings.get(\"abbrev\", False): return \"%s\" % expr.abbrev return \"%s\" % expr.name def _print_Quaternion(self, expr):", "commid": "sympy__sympy-13962"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13962-bd0fc90c2a55d8b5d28b9535f4d431b0b1f57079c5fa3be362c9a24a4ff1a4fc", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13962-d49de39a0c7008d989091e21079f6e55bcb48021715cbdaee32f4d8d8d637499", "text": " \"\"\"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 ========", "commid": "sympy__sympy-13962"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13971-e9f0050460aefd9e7aa1198cec5b4a7f3b41a6b98de8c01234ce94138e70d5fb", "query": "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?", "positive_passages": [{"docid": "doc-en-sympy__sympy-13971-a048269015d7bdc19a19de5c55247bcb057f476c7c82a294ad4b0d64260d9032", "text": " 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", "commid": "sympy__sympy-13971"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13974-f49daab937c9dab3e2abb330f7c11ad0173ad4d541663d9b55d565cfe26aae56", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13974-28a52a6e905492819859aa3c6c8e79ac1fdf687d87bda1cc6cd1e1627b1fc8a5", "text": " matrix_tensor_product ) __all__ = [ 'TensorProduct', 'tensor_product_simp'", "commid": "sympy__sympy-13974"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13974-f49daab937c9dab3e2abb330f7c11ad0173ad4d541663d9b55d565cfe26aae56", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13974-78afdb73dae6a814c29220902f7ba7296c5b7dfbb4d2eaa35405fc378bdfc2ba", "text": " \"\"\" # 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:]:", "commid": "sympy__sympy-13974"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13974-f49daab937c9dab3e2abb330f7c11ad0173ad4d541663d9b55d565cfe26aae56", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13974-40482c9d5e8768dff00fe96da06a9657d9c6f3b4a594a19d23e98b63f732bdf2", "text": " 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.", "commid": "sympy__sympy-13974"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13974-f49daab937c9dab3e2abb330f7c11ad0173ad4d541663d9b55d565cfe26aae56", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13974-11c7805ad271c61a57157000effe0b100c45e2346864520cfced7f2897673a87", "text": " 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):", "commid": "sympy__sympy-13974"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13978-a8ba326202e056eb1f8366254fd19002e46939ffe13756ab85f8e682615585f7", "query": "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 ?", "positive_passages": [{"docid": "doc-en-sympy__sympy-13978-1a6d427211fa71f53eee9d6a249462bd32c4882b639965e5e2f9f86e10c6ff7e", "text": " 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", "commid": "sympy__sympy-13978"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13988-d71747c3f5114ce9fd2ab3e38830f26c023bd7dbad25a06ef7af069aaa56fc9b", "query": "() 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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13988-b4d68a3422bd193527a5ae8a59e75081fb1ecdec7c63a582db59922c5f35ebb1", "text": " 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", "commid": "sympy__sympy-13988"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13988-d71747c3f5114ce9fd2ab3e38830f26c023bd7dbad25a06ef7af069aaa56fc9b", "query": "() 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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13988-e0a6da42b37c523e67ca5c4725031e7f7ffdfc1c9c9d582d84430ad9867c5dc5", "text": " >>> (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)", "commid": "sympy__sympy-13988"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13988-d71747c3f5114ce9fd2ab3e38830f26c023bd7dbad25a06ef7af069aaa56fc9b", "query": "() 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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13988-e88ca870d7468c8441a053b63256c196c82beb51a6b51d0d2bae67e7467c6955", "text": " 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 ========", "commid": "sympy__sympy-13988"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-13988-d71747c3f5114ce9fd2ab3e38830f26c023bd7dbad25a06ef7af069aaa56fc9b", "query": "() 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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-13988-e5aee148462507d83a75ae145c122b1fd548dcc71387e17cad0ce547f7edf5cc", "text": " 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", "commid": "sympy__sympy-13988"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14024-2f755bfae4d45b54aff6dee79ff64a771d75f0fc584caa40140fa9b56775af17", "query": "Inconsistency when simplifying (-a)x * a(-x), a a positive integer Compare: vs", "positive_passages": [{"docid": "doc-en-sympy__sympy-14024-69beb2cf29a60cc93e3dae744da5682adcf7bbe826c32c46094fcb3290c89a8b", "text": " 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", "commid": "sympy__sympy-14024"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14024-2f755bfae4d45b54aff6dee79ff64a771d75f0fc584caa40140fa9b56775af17", "query": "Inconsistency when simplifying (-a)x * a(-x), a a positive integer Compare: vs", "positive_passages": [{"docid": "doc-en-sympy__sympy-14024-7155ed912c1984795902a81e02a2222bcb8561945daeaf7f5e8d7bfbb4ef27f9", "text": " # 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", "commid": "sympy__sympy-14024"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14031-d06e2f3eedf66b108be953dcce14a4863ae80b9d02c2d3550f70110b19df633b", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14031-484bed0b5835acb31ea49c3a402412f1b4845db11946e09ebc5a826e437f882f", "text": " from sympy.core.compatibility import is_sequence, reduce, string_types from sympy.core.expr import Expr from sympy.core.mod import Modfrom sympy.core.numbers import Exp1from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import CantSympify, sympify from sympy.functions.elementary.exponential import ExpBase", "commid": "sympy__sympy-14031"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14031-d06e2f3eedf66b108be953dcce14a4863ae80b9d02c2d3550f70110b19df633b", "query": "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.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14031-66f150b11092e1ff6d703394ed6e634e0633d038e8bd3a11b99185814acdb2e5", "text": " 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)", "commid": "sympy__sympy-14031"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14038-5933a01d964e44b392a9832dab22b27a1d6b22c85b53af138e23317e945fe920", "query": "product(1 - a2 / (n*pi)2, [n, 1, oo]) should not evaluate to 0 (if the product is evaluated the correct result is )", "positive_passages": [{"docid": "doc-en-sympy__sympy-14038-3945d53c21c3bedf5dc2e6e6bbed01f078522aed007a62b8a164a43b207130f2", "text": " from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.concrete.expr_with_intlimits import ExprWithIntLimitsfrom sympy.core.exprtools import factor_terms from sympy.functions.elementary.exponential import exp, log from sympy.polys import quo, roots from sympy.simplify import powsimp", "commid": "sympy__sympy-14038"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14038-5933a01d964e44b392a9832dab22b27a1d6b22c85b53af138e23317e945fe920", "query": "product(1 - a2 / (n*pi)2, [n, 1, oo]) should not evaluate to 0 (if the product is evaluated the correct result is )", "positive_passages": [{"docid": "doc-en-sympy__sympy-14038-ff4b9fe9085f7b45c1943553c0d4299816182a9979fafe1dedcfbe092314d1f9", "text": " 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 = [], []", "commid": "sympy__sympy-14038"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14070-8f4f938d7ef07747b1bd2edbae809fdc0251cf545461620cd8c515a235673d4d", "query": "logcombine(log(3) - log(2)) does nothing Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14070-728ffa252055cbeb8a31f68dff97bcbd816d7b75fe610fc2ef679d3bd336eec7", "text": " 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())):", "commid": "sympy__sympy-14070"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14070-8f4f938d7ef07747b1bd2edbae809fdc0251cf545461620cd8c515a235673d4d", "query": "logcombine(log(3) - log(2)) does nothing Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14070-53bcf2455f08699ce12ccf4957062aff12056ad63fbd57c6cac3f9a93c2c5988", "text": " 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))", "commid": "sympy__sympy-14070"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14082-9e7cb03c0f5151b17838ce4d0933c720fc3eda4210ded45154eef8293a7a4e43", "query": "Integrate(1/(x2 + y2), x) returns a wrong result The correct result is . It seems similar to .", "positive_passages": [{"docid": "doc-en-sympy__sympy-14082-72c711272a2e22a0e4dc02048cdeaf946097cb51d1315efc682379cb081a9349", "text": " 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})", "commid": "sympy__sympy-14082"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14085-9123b72746d45ec2d39fee0df1feff71a7c12c247a297e455ee4bd3ec2fb6a1e", "query": "sympify(u\"\u03b1\") does not work Original issue for : Original author: Original owner:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14085-da58c0981b3bed34f9650d2784a1d5f7f3aa6da9919b95c42750560b9a732417", "text": " 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.", "commid": "sympy__sympy-14085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14085-9123b72746d45ec2d39fee0df1feff71a7c12c247a297e455ee4bd3ec2fb6a1e", "query": "sympify(u\"\u03b1\") does not work Original issue for : Original author: Original owner:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14085-1e4ba3c6acaeae89ab68760ef5313a13e3669c9cbb8dbd23415258bd2438d2aa", "text": " def factorial_notation(tokens, local_dict, global_dict): \"\"\"Allows standard notation for factorial.\"\"\" result = [] prevtoken = '' nfactorial = 0 for toknum, tokval in tokens: if toknum == OP: if toknum == ERRORTOKEN: op = tokval if op == '!!': if prevtoken == '!' or prevtoken == '!!': raise TokenError result = _add_factorial_tokens('factorial2', result) elif op == '!': if prevtoken == '!' or prevtoken == '!!': raise TokenError result = _add_factorial_tokens('factorial', result) if op == '!': nfactorial += 1 else: nfactorial = 0 result.append((OP, op)) else: if nfactorial == 1: result = _add_factorial_tokens('factorial', result) elif nfactorial == 2: result = _add_factorial_tokens('factorial2', result) elif nfactorial > 2: raise TokenError nfactorial = 0 result.append((toknum, tokval)) prevtoken = tokval return result ", "commid": "sympy__sympy-14085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14085-9123b72746d45ec2d39fee0df1feff71a7c12c247a297e455ee4bd3ec2fb6a1e", "query": "sympify(u\"\u03b1\") does not work Original issue for : Original author: Original owner:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14085-1d341f10b379f138340962ebab02b38cbec19c4f66238a7e50ac02d622d3b392", "text": " return result def repeated_decimals(tokens, local_dict, global_dict): \"\"\" Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90) Run this before auto_number. \"\"\" result = [] def is_digit(s): return all(i in '0123456789_' for i in s) # num will running match any DECIMAL [ INTEGER ] num = [] for toknum, tokval in tokens: if toknum == NUMBER: if (not num and '.' in tokval and 'e' not in tokval.lower() and 'j' not in tokval.lower()): num.append((toknum, tokval)) elif is_digit(tokval)and len(num) == 2: num.append((toknum, tokval)) elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]): # Python 2 tokenizes 00123 as '00', '123' # Python 3 tokenizes 01289 as '012', '89' num.append((toknum, tokval)) else: num = [] elif toknum == OP: if tokval == '[' and len(num) == 1: num.append((OP, tokval)) elif tokval == ']' and len(num) >= 3: num.append((OP, tokval)) elif tokval == '.' and not num: # handle .[1] num.append((NUMBER, '0.')) else: num = [] else: num = [] result.append((toknum, tokval)) if num and num[-1][1] == ']': # pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post, # and d/e = repetend result = result[:-len(num)] pre, post = num[0][1].split('.') repetend = num[2][1] if len(num) == 5: repetend += num[3][1] pre = pre.replace('_', '') post = post.replace('_', '') repetend = repetend.replace('_', '') zeros = '0'*len(post) post, repetends = [w.lstrip('0') for w in [post, repetend]] # or else interpreted as octal a = pre or '0' b, c = post or '0', '1' + zeros d, e = repetends, ('9'*len(repetend)) + zeros seq = [ (OP, '('), (NAME, 'Integer'), (OP, '('), (NUMBER, a), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), (NUMBER, b), (OP, ','), (NUMBER, c), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), (NUMBER, d), (OP, ','), (NUMBER, e), (OP, ')'), (OP, ')'), ] result.extend(seq) num = [] return result def auto_number(tokens, local_dict, global_dict): \"\"\"Converts numeric literals to use SymPy equivalents. \"\"\" Converts numeric literals to use SymPy equivalents. Complex numbers use ``I``; integer literals use ``Integer``, float literals use ``Float``, and repeating decimals use ``Rational``. Complex numbers use ``I``, integer literals use ``Integer``, and float literals use ``Float``. \"\"\" result = [] prevtoken = '' for toknum, tokval in tokens: if toknum == NUMBER:", "commid": "sympy__sympy-14085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14085-9123b72746d45ec2d39fee0df1feff71a7c12c247a297e455ee4bd3ec2fb6a1e", "query": "sympify(u\"\u03b1\") does not work Original issue for : Original author: Original owner:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14085-ff248afaf9f3c5848fba21b6fb0af76906e97fb35fb7a411694c2596f6bd3de3", "text": " if '.' in number or (('e' in number or 'E' in number) and not (number.startswith('0x') or number.startswith('0X'))): match = _re_repeated.match(number) if match is not None: # Clear repeating decimals, e.g. 3.4[31] -> (3 + 4/10 + 31/990) pre, post, repetend = match.groups() zeros = '0'*len(post) post, repetends = [w.lstrip('0') for w in [post, repetend]] # or else interpreted as octal a = pre or '0' b, c = post or '0', '1' + zeros d, e = repetends, ('9'*len(repetend)) + zeros seq = [ (OP, '('), (NAME, 'Integer'), (OP, '('), (NUMBER, a), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), ( NUMBER, b), (OP, ','), (NUMBER, c), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), ( NUMBER, d), (OP, ','), (NUMBER, e), (OP, ')'), (OP, ')'), ] else: seq = [(NAME, 'Float'), (OP, '('), (NUMBER, repr(str(number))), (OP, ')')] seq = [(NAME, 'Float'), (OP, '('), (NUMBER, repr(str(number))), (OP, ')')] else: seq = [(NAME, 'Integer'), (OP, '('), ( NUMBER, number), (OP, ')')]", "commid": "sympy__sympy-14085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14085-9123b72746d45ec2d39fee0df1feff71a7c12c247a297e455ee4bd3ec2fb6a1e", "query": "sympify(u\"\u03b1\") does not work Original issue for : Original author: Original owner:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14085-96c06f8fde08e57878d50bde5fc6d073ac487dbe3e52576634d00884130da67f", "text": " return result def rationalize(tokens, local_dict, global_dict): \"\"\"Converts floats into ``Rational``. Run AFTER ``auto_number``.\"\"\" result = []", "commid": "sympy__sympy-14085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14085-9123b72746d45ec2d39fee0df1feff71a7c12c247a297e455ee4bd3ec2fb6a1e", "query": "sympify(u\"\u03b1\") does not work Original issue for : Original author: Original owner:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14085-9529ec198be79a3c06e5b9403ebafe775b1ff57724477229c96c21644c78c5a0", "text": " #: Standard transformations for :func:`parse_expr`. #: Inserts calls to :class:`Symbol`, :class:`Integer`, and other SymPy #: datatypes and allows the use of standard factorial notation (e.g. ``x!``).standard_transformations = (lambda_notation, auto_symbol, auto_number, factorial_notation)standard_transformations = (lambda_notation, auto_symbol, repeated_decimals, auto_number, factorial_notation) def stringify_expr(s, local_dict, global_dict, transformations):diff --git a/sympy/parsing/sympy_tokenize.py b/sympy/parsing/sympy_tokenize.pydeleted file mode 100644-- a/sympy/parsing/sympy_tokenize.py++ /dev/null", "commid": "sympy__sympy-14085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14085-9123b72746d45ec2d39fee0df1feff71a7c12c247a297e455ee4bd3ec2fb6a1e", "query": "sympify(u\"\u03b1\") does not work Original issue for : Original author: Original owner:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14085-c16cedbc23783cbc3f3386ba990837464caa61a19067c08ae86030edfea64110", "text": "\"\"\"Tokenization help for Python programs.generate_tokens(readline) is a generator that breaks a stream oftext into Python tokens. It accepts a readline-like method which is calledrepeatedly to get the next line of input (or \"\" for EOF). It generates5-tuples with these members: the token type (see token.py) the token (a string) the starting (row, column) indices of the token (a 2-tuple of ints) the ending (row, column) indices of the token (a 2-tuple of ints) the original line (string)It is designed to match the working of the Python tokenizer exactly, exceptthat it produces COMMENT tokens for comments and gives type OP for alloperatorsOlder entry points tokenize_loop(readline, tokeneater) tokenize(readline, tokeneater=printtoken)are the same, except instead of generating tokens, tokeneater is a callbackfunction to which the 5 fields described above are passed as 5 arguments,each time a new token is found.\"\"\"from __future__ import print_function, division__author__ = 'Ka-Ping Yee '__credits__ = \\ 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger'import stringimport refrom token import *import token__all__ = [x for x in dir(token) if x[0] != '_'] + [\"COMMENT\", \"tokenize\", \"generate_tokens\", \"NL\", \"untokenize\"]del tokenCOMMENT = N_TOKENStok_name[COMMENT] = 'COMMENT'NL = N_TOKENS + 1tok_name[NL] = 'NL'N_TOKENS += 2def group(*choices): return '(' + '|'.join(choices) + ')'def any(*choices): return group(*choices) + '*'def maybe(*choices): return group(*choices) + '?'Whitespace = r'[ \\f\\t]*'Comment = r'#[^\\r\\n]*'Ignore = Whitespace + any(r'\\\\\\r?\\n' + Whitespace) + maybe(Comment)Name = r'[a-zA-Z_]\\w*'Hexnumber = r'0[xX][\\da-fA-F]+[lL]?'Octnumber = r'(0[oO][0-7]+)|(0[0-7]*)[lL]?'Binnumber = r'0[bB][01]+[lL]?'Decnumber = r'[1-9]\\d*[lL]?'Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)Exponent = r'[eE][-+]?\\d+'Pointfloat = group(r'\\d+\\.\\d*', r'\\.\\d+') + maybe(Exponent)Repeatedfloat = r'\\d*\\.\\d*\\[\\d+\\]'Expfloat = r'\\d+' + ExponentFloatnumber = group(Repeatedfloat, Pointfloat, Expfloat)Imagnumber = group(r'\\d+[jJ]', Floatnumber + r'[jJ]')Number = group(Imagnumber, Floatnumber, Intnumber)# Tail end of ' string.Single = r\"[^'\\\\]*(?:\\\\.[^'\\\\]*)*'\"# Tail end of \" string.Double = r'[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"'# Tail end of ''' string.Single3 = r\"[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''\"# Tail end of \"\"\" string.Double3 = r'[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\"'Triple = group(\"[uU]?[rR]?'''\", '[uU]?[rR]?\"\"\"')# Single-line ' or \" string.String = group(r\"[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'\", r'[uU]?[rR]?\"[^\\n\"\\\\]*(?:\\\\.[^\\n\"\\\\]*)*\"')# Because of leftmost-then-longest match semantics, be sure to put the# longest operators first (e.g., if = came before ==, == would get# recognized as two instances of =).Operator = group(r\"\\*\\*=?\", r\">>=?\", r\"<<=?\", r\"<>\", r\"!=\", r\"//=?\", r\"[+\\-*/%&|^=<>]=?\", r\"~\")Bracket = '[][(){}]'Special = group(r'\\r?\\n', r'[:;.,`@]', r'\\!\\!', r'\\!')Funny = group(Operator, Bracket, Special)PlainToken = group(Number, Funny, String, Name)Token = Ignore + PlainToken# First (or only) line of ' or \" string.ContStr = group(r\"[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*\" + group(\"'\", r'\\\\\\r?\\n'), r'[uU]?[rR]?\"[^\\n\"\\\\]*(?:\\\\.[^\\n\"\\\\]*)*' + group('\"', r'\\\\\\r?\\n'))PseudoExtras = group(r'\\\\\\r?\\n', Comment, Triple)PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)tokenprog, pseudoprog, single3prog, double3prog = map( re.compile, (Token, PseudoToken, Single3, Double3))endprogs = {\"'\": re.compile(Single), '\"': re.compile(Double), \"'''\": single3prog, '\"\"\"': double3prog, \"r'''\": single3prog, 'r\"\"\"': double3prog, \"u'''\": single3prog, 'u\"\"\"': double3prog, \"ur'''\": single3prog, 'ur\"\"\"': double3prog, \"R'''\": single3prog, 'R\"\"\"': double3prog, \"U'''\": single3prog, 'U\"\"\"': double3prog, \"uR'''\": single3prog, 'uR\"\"\"': double3prog, \"Ur'''\": single3prog, 'Ur\"\"\"': double3prog, \"UR'''\": single3prog, 'UR\"\"\"': double3prog, \"b'''\": single3prog, 'b\"\"\"': double3prog, \"br'''\": single3prog, 'br\"\"\"': double3prog, \"B'''\": single3prog, 'B\"\"\"': double3prog, \"bR'''\": single3prog, 'bR\"\"\"': double3prog, \"Br'''\": single3prog, 'Br\"\"\"': double3prog, \"BR'''\": single3prog, 'BR\"\"\"': double3prog, 'r': None, 'R': None, 'u': None, 'U': None, 'b': None, 'B': None}triple_quoted = {}for t in (\"'''\", '\"\"\"', \"r'''\", 'r\"\"\"', \"R'''\", 'R\"\"\"', \"u'''\", 'u\"\"\"', \"U'''\", 'U\"\"\"', \"ur'''\", 'ur\"\"\"', \"Ur'''\", 'Ur\"\"\"', \"uR'''\", 'uR\"\"\"', \"UR'''\", 'UR\"\"\"', \"b'''\", 'b\"\"\"', \"B'''\", 'B\"\"\"', \"br'''\", 'br\"\"\"', \"Br'''\", 'Br\"\"\"', \"bR'''\", 'bR\"\"\"', \"BR'''\", 'BR\"\"\"'): triple_quoted[t] = tsingle_quoted = {}for t in (\"'\", '\"', \"r'\", 'r\"', \"R'\", 'R\"', \"u'\", 'u\"', \"U'\", 'U\"', \"ur'\", 'ur\"', \"Ur'\", 'Ur\"', \"uR'\", 'uR\"', \"UR'\", 'UR\"', \"b'\", 'b\"', \"B'\", 'B\"', \"br'\", 'br\"', \"Br'\", 'Br\"', \"bR'\", 'bR\"', \"BR'\", 'BR\"' ): single_quoted[t] = ttabsize = 8class TokenError(Exception): passclass StopTokenizing(Exception): passdef printtoken(type, token, srow_scol, erow_ecol, line): # for testing srow, scol = srow_scol erow, ecol = erow_ecol print(\"%d,%d-%d,%d:\\t%s\\t%s\" % \\ (srow, scol, erow, ecol, tok_name[type], repr(token)))def tokenize(readline, tokeneater=printtoken): \"\"\" The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens(). \"\"\" try: tokenize_loop(readline, tokeneater) except StopTokenizing: pass# backwards compatible interfacedef tokenize_loop(readline, tokeneater): for token_info in generate_tokens(readline): tokeneater(*token_info)class Untokenizer: def __init__(self): self.tokens = [] self.prev_row = 1 self.prev_col = 0 def add_whitespace(self, start): row, col = start if row > self.prev_row: raise ValueError(\"row should not be greater than prev_row\") col_offset = col - self.prev_col if col_offset: self.tokens.append(\" \" * col_offset) def untokenize(self, iterable): for t in iterable: if len(t) == 2: self.compat(t, iterable) break tok_type, token, start, end, line = t self.add_whitespace(start) self.tokens.append(token) self.prev_row, self.prev_col = end if tok_type in (NEWLINE, NL): self.prev_row += 1 self.prev_col = 0 return \"\".join(self.tokens) def compat(self, token, iterable): startline = False indents = [] toks_append = self.tokens.append toknum, tokval = token if toknum in (NAME, NUMBER): tokval += ' ' if toknum in (NEWLINE, NL): startline = True prevstring = False for tok in iterable: toknum, tokval = tok[:2] if toknum in (NAME, NUMBER): tokval += ' ' # Insert a space between two consecutive strings if toknum == STRING: if prevstring: tokval = ' ' + tokval prevstring = True else: prevstring = False if toknum == INDENT: indents.append(tokval) continue elif toknum == DEDENT: indents.pop() continue elif toknum in (NEWLINE, NL): startline = True elif startline and indents: toks_append(indents[-1]) startline = False toks_append(tokval)def untokenize(iterable): \"\"\"Transform tokens back into Python source code. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited intput:: # Output text will tokenize the back to the input t1 = [tok[:2] for tok in generate_tokens(f.readline)] newcode = untokenize(t1) readline = iter(newcode.splitlines(1)).next t2 = [tok[:2] for tok in generate_tokens(readline)] if t1 != t2: raise ValueError(\"t1 should be equal to t2\") \"\"\" ut = Untokenizer() return ut.untokenize(iterable)def generate_tokens(readline): \"\"\" The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration:: readline = open(myfile).next # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included. \"\"\" lnum = parenlev = continued = 0 namechars, numchars = string.ascii_letters + '_', '0123456789' contstr, needcont = '', 0 contline = None indents = [0] while 1: # loop over lines in stream try: line = readline() except StopIteration: line = '' lnum = lnum + 1 pos, max = 0, len(line) if contstr: # continued string if not line: raise TokenError(\"EOF in multi-line string\", strstart) endmatch = endprog.match(line) if endmatch: pos = end = endmatch.end(0) yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line) contstr, needcont = '', 0 contline = None elif needcont and line[-2:] != '\\\\\\n' and line[-3:] != '\\\\\\r\\n': yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline) contstr = '' contline = None continue else: contstr = contstr + line contline = contline + line continue elif parenlev == 0 and not continued: # new statement if not line: break column = 0 while pos < max: # measure leading whitespace if line[pos] == ' ': column = column + 1 elif line[pos] == '\\t': column = (column/tabsize + 1)*tabsize elif line[pos] == '\\f': column = 0 else: break pos = pos + 1 if pos == max: break if line[pos] in '#\\r\\n': # skip comments or blank lines if line[pos] == '#': comment_token = line[pos:].rstrip('\\r\\n') nl_pos = pos + len(comment_token) yield (COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line) yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line) else: yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line) continue if column > indents[-1]: # count indents or dedents indents.append(column) yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line) while column < indents[-1]: if column not in indents: raise IndentationError( \"unindent does not match any outer indentation level\", (\"\", lnum, pos, line)) indents = indents[:-1] yield (DEDENT, '', (lnum, pos), (lnum, pos), line) else: # continued statement if not line: raise TokenError(\"EOF in multi-line statement\", (lnum, 0)) continued = 0 while pos < max: pseudomatch = pseudoprog.match(line, pos) if pseudomatch: # scan for tokens start, end = pseudomatch.span(1) spos, epos, pos = (lnum, start), (lnum, end), end token, initial = line[start:end], line[start] if initial in numchars or \\ (initial == '.' and token != '.'): # ordinary number yield (NUMBER, token, spos, epos, line) elif initial in '\\r\\n': yield (NL if parenlev > 0 else NEWLINE, token, spos, epos, line) elif initial == '#': if token.endswith(\"\\n\"): raise ValueError(\"Token should not end with \\n\") yield (COMMENT, token, spos, epos, line) elif token in triple_quoted: endprog = endprogs[token] endmatch = endprog.match(line, pos) if endmatch: # all on one line pos = endmatch.end(0) token = line[start:pos] yield (STRING, token, spos, (lnum, pos), line) else: strstart = (lnum, start) # multiple lines contstr = line[start:] contline = line break elif initial in single_quoted or \\ token[:2] in single_quoted or \\ token[:3] in single_quoted: if token[-1] == '\\n': # continued string strstart = (lnum, start) endprog = (endprogs[initial] or endprogs[token[1]] or endprogs[token[2]]) contstr, needcont = line[start:], 1 contline = line break else: # ordinary string yield (STRING, token, spos, epos, line) elif initial in namechars: # ordinary name yield (NAME, token, spos, epos, line) elif initial == '\\\\': # continued stmt continued = 1 else: if initial in '([{': parenlev = parenlev + 1 elif initial in ')]}': parenlev = parenlev - 1 yield (OP, token, spos, epos, line) else: yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos + 1), line) pos = pos + 1 for indent in indents[1:]: # pop remaining indent levels yield (DEDENT, '', (lnum, 0), (lnum, 0), '') yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')if __name__ == '__main__': # testing import sys if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline) else: tokenize(sys.stdin.readline)", "commid": "sympy__sympy-14085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14104-ae12ab9eeac93afaf7b54f43794b0279129f9651ba251b10bb5f136e2c5fc655", "query": "pprint(x*DiracDelta(x, 1)) gives TypeError: unorderable types: NoneType() int() I bisected it to commit : CC", "positive_passages": [{"docid": "doc-en-sympy__sympy-14104-6d5d20421c60d001f1e7af0baecd2554045a4767f1b9ec5311b782e88f00bf3b", "text": " c = self._print(e.args[0]) c = prettyForm(*c.parens()) pform = a**b pform = stringPict(*pform.right(' ')) pform = stringPict(*pform.right(c)) pform = prettyForm(*pform.right(' ')) pform = prettyForm(*pform.right(c)) return pform pform = self._print(e.args[0]) pform = prettyForm(*pform.parens())", "commid": "sympy__sympy-14104"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14166-f93fa8cf30f91411217297a5ab584256f63f684b0aa3239189d05729df629222", "query": "Typesetting of big-O symbol Currently typesetting of big-O symbol uses the ordinary 'O', we can use the typesetting as defined here .", "positive_passages": [{"docid": "doc-en-sympy__sympy-14166-49b75d2f672bea32d970c9e9d92429977b5c9dbd80a93778390917d2df7850c6", "text": " s += self._print(expr.point) else: s += self._print(expr.point[0]) return r\"\\mathcal{O}\\left(%s\\right)\" % s return r\"O\\left(%s\\right)\" % s def _print_Symbol(self, expr): if expr in self._settings['symbol_names']:", "commid": "sympy__sympy-14166"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14180-b68a3e37f00ae3668a01aefe96142c3a24d776fbaf076416bb5554ac84111d9d", "query": "Converting to LaTeX was converted to which is in some fields is log10(10) or log2(10). There is '\\ln' in LaTeX and should be converted to it not to", "positive_passages": [{"docid": "doc-en-sympy__sympy-14180-aead28c2b119198c3c9b4ef5172e0fde8f4d502c400b0f782bac04a7503cd229", "text": " \"mat_str\": None, \"mat_delim\": \"[\", \"symbol_names\": {}, \"ln_notation\": False, } def __init__(self, settings=None):", "commid": "sympy__sympy-14180"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14180-b68a3e37f00ae3668a01aefe96142c3a24d776fbaf076416bb5554ac84111d9d", "query": "Converting to LaTeX was converted to which is in some fields is log10(10) or log2(10). There is '\\ln' in LaTeX and should be converted to it not to", "positive_passages": [{"docid": "doc-en-sympy__sympy-14180-6e3d6be84ccfd1e6d588aedb9707231caf44e77b10b6973445852963a2a22703", "text": " else: return tex def _print_log(self, expr, exp=None): if not self._settings[\"ln_notation\"]: tex = r\"\\log{\\left (%s \\right )}\" % self._print(expr.args[0]) else: tex = r\"\\ln{\\left (%s \\right )}\" % self._print(expr.args[0]) if exp is not None: return r\"%s^{%s}\" % (tex, exp) else: return tex def _print_Abs(self, expr, exp=None): tex = r\"\\left|{%s}\\right|\" % self._print(expr.args[0]) ", "commid": "sympy__sympy-14180"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14180-b68a3e37f00ae3668a01aefe96142c3a24d776fbaf076416bb5554ac84111d9d", "query": "Converting to LaTeX was converted to which is in some fields is log10(10) or log2(10). There is '\\ln' in LaTeX and should be converted to it not to", "positive_passages": [{"docid": "doc-en-sympy__sympy-14180-b8c351884c17eb98faf28934fdc8a85fbd2c9d684c93700cbc610d3c594836e5", "text": " r\"\"\" Convert the given expression to LaTeX representation. >>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational >>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log >>> from sympy.abc import x, y, mu, r, tau >>> print(latex((2*tau)**Rational(7,2)))", "commid": "sympy__sympy-14180"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14180-b68a3e37f00ae3668a01aefe96142c3a24d776fbaf076416bb5554ac84111d9d", "query": "Converting to LaTeX was converted to which is in some fields is log10(10) or log2(10). There is '\\ln' in LaTeX and should be converted to it not to", "positive_passages": [{"docid": "doc-en-sympy__sympy-14180-f4ddb05f5d8e4e7368991964cd48d63b0faf7f69c92f7e4f6cd1ccc8115f33a6", "text": " >>> print(latex([2/x, y], mode='inline')) $\\left [ 2 / x, \\quad y\\right ]$ ln_notation: If set to ``True`` \"\\ln\" is used instead of default \"\\log\" >>> print(latex(log(10))) \\log{\\left (10 \\right )} >>> print(latex(log(10), ln_notation=True)) \\ln{\\left (10 \\right )} \"\"\" return LatexPrinter(settings).doprint(expr)", "commid": "sympy__sympy-14180"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14248-c4cdfc2ff76a2dcd4a10ddf41e90b30fe4dd7ef530a8009902aee29bcd404715", "query": "The difference of MatrixSymbols prints as a sum with (-1) coefficient Internally, differences like a-b are represented as the sum of a with , but they are supposed to print like a-b. This does not happen with MatrixSymbols. I tried three printers: str, pretty, and latex: Output: Based on a", "positive_passages": [{"docid": "doc-en-sympy__sympy-14248-db2d14220af0e201b3ceb310c29f4d7af2cef5275447df728829faf3432fcc29", "text": " return r\"%s^\\dagger\" % self._print(mat) def _print_MatAdd(self, expr): terms = list(expr.args) tex = \" + \".join(map(self._print, terms)) return tex terms = [self._print(t) for t in expr.args] l = [] for t in terms: if t.startswith('-'): sign = \"-\" t = t[1:] else: sign = \"+\" l.extend([sign, t]) sign = l.pop(0) if sign == '+': sign = \"\" return sign + ' '.join(l) def _print_MatMul(self, expr): from sympy import Add, MatAdd, HadamardProduct from sympy import Add, MatAdd, HadamardProduct, MatMul, Mul def parens(x): if isinstance(x, (Add, MatAdd, HadamardProduct)): return r\"\\left(%s\\right)\" % self._print(x) return self._print(x) return ' '.join(map(parens, expr.args)) if isinstance(expr, MatMul) and expr.args[0].is_Number and expr.args[0]<0: expr = Mul(-1*expr.args[0], MatMul(*expr.args[1:])) return '-' + ' '.join(map(parens, expr.args)) else: return ' '.join(map(parens, expr.args)) def _print_Mod(self, expr, exp=None): if exp is not None: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", "commid": "sympy__sympy-14248"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14248-c4cdfc2ff76a2dcd4a10ddf41e90b30fe4dd7ef530a8009902aee29bcd404715", "query": "The difference of MatrixSymbols prints as a sum with (-1) coefficient Internally, differences like a-b are represented as the sum of a with , but they are supposed to print like a-b. This does not happen with MatrixSymbols. I tried three printers: str, pretty, and latex: Output: Based on a", "positive_passages": [{"docid": "doc-en-sympy__sympy-14248-902a5a421305f02a57e6084d6d96ff427feef28ee571490e4648a88630450e9c", "text": " return self._print(B.blocks) def _print_MatAdd(self, expr): return self._print_seq(expr.args, None, None, ' + ') s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: if S(item.args[0]).is_negative: s = prettyForm(*stringPict.next(s, ' ')) pform = self._print(item) else: s = prettyForm(*stringPict.next(s, ' + ')) s = prettyForm(*stringPict.next(s, pform)) return s def _print_MatMul(self, expr): args = list(expr.args)diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py", "commid": "sympy__sympy-14248"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14248-c4cdfc2ff76a2dcd4a10ddf41e90b30fe4dd7ef530a8009902aee29bcd404715", "query": "The difference of MatrixSymbols prints as a sum with (-1) coefficient Internally, differences like a-b are represented as the sum of a with , but they are supposed to print like a-b. This does not happen with MatrixSymbols. I tried three printers: str, pretty, and latex: Output: Based on a", "positive_passages": [{"docid": "doc-en-sympy__sympy-14248-6a3b24b5b69bbbf59a53c21c4f9e88779e45464fa0891c611a90e2ee661b1ba1", "text": " return sign + '*'.join(a_str) + \"/(%s)\" % '*'.join(b_str) def _print_MatMul(self, expr): return '*'.join([self.parenthesize(arg, precedence(expr)) c, m = expr.as_coeff_mmul() if c.is_number and c < 0: expr = _keep_coeff(-c, m) sign = \"-\" else: sign = \"\" return sign + '*'.join([self.parenthesize(arg, precedence(expr)) for arg in expr.args]) def _print_HadamardProduct(self, expr):", "commid": "sympy__sympy-14248"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14248-c4cdfc2ff76a2dcd4a10ddf41e90b30fe4dd7ef530a8009902aee29bcd404715", "query": "The difference of MatrixSymbols prints as a sum with (-1) coefficient Internally, differences like a-b are represented as the sum of a with , but they are supposed to print like a-b. This does not happen with MatrixSymbols. I tried three printers: str, pretty, and latex: Output: Based on a", "positive_passages": [{"docid": "doc-en-sympy__sympy-14248-9731139d097caec0ba3f31fccf6a0eb7315e79f4635a791d0153392a7ccd2aa2", "text": " for arg in expr.args]) def _print_MatAdd(self, expr): return ' + '.join([self.parenthesize(arg, precedence(expr)) for arg in expr.args]) terms = [self.parenthesize(arg, precedence(expr)) for arg in expr.args] l = [] for t in terms: if t.startswith('-'): sign = \"-\" t = t[1:] else: sign = \"+\" l.extend([sign, t]) sign = l.pop(0) if sign == '+': sign = \"\" return sign + ' '.join(l) def _print_NaN(self, expr): return 'nan'", "commid": "sympy__sympy-14248"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14296-09a174aa8fac18e1b1a4e3ff2dfe1b592191dd6d6f546d10947cf35990769e1a", "query": "Sign of generator of an algebraic numberfield calls , but the implementation is defective as it does not change the minimal polynomial. I think this could be fixed in two ways: Add code to create the changed minimal polynomial. Ignore the sign and remove the code changing it. I am inclined to prefer the latter, simpler solution, but I would also like to hear other suggestions.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14296-9d67b0e700ddc9923364626b0c7da22c54d63c9b3f831cee4ffc25806fbc1115", "text": " rep = DMP.from_list([1, 0], 0, dom) scoeffs = Tuple(1, 0) if root.is_negative: rep = -rep scoeffs = Tuple(-1, 0) sargs = (root, scoeffs) if alias is not None:", "commid": "sympy__sympy-14296"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14308-240b8f2d9b6dd41bdb6ad7cd53f65a1957075fb698d7d93f6596a952ce6ae5d8", "query": "vectors break pretty printing Also, when it does print correctly, the baseline is wrong (it should be centered).", "positive_passages": [{"docid": "doc-en-sympy__sympy-14308-84cb493b884292101dbecd900553984f94516a061bb4f7e98d4c7170cf65413d", "text": " #Fixing the newlines lengths = [] strs = [''] flag = [] for i, partstr in enumerate(o1): flag.append(0) # XXX: What is this hack? if '\\n' in partstr: tempstr = partstr tempstr = tempstr.replace(vectstrs[i], '') tempstr = tempstr.replace(u'\\N{RIGHT PARENTHESIS UPPER HOOK}', u'\\N{RIGHT PARENTHESIS UPPER HOOK}' + ' ' + vectstrs[i]) if u'\\N{right parenthesis extension}' in tempstr: # If scalar is a fraction for paren in range(len(tempstr)): flag[i] = 1 if tempstr[paren] == u'\\N{right parenthesis extension}': tempstr = tempstr[:paren] + u'\\N{right parenthesis extension}'\\ + ' ' + vectstrs[i] + tempstr[paren + 1:] break elif u'\\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr: flag[i] = 1 tempstr = tempstr.replace(u'\\N{RIGHT PARENTHESIS LOWER HOOK}', u'\\N{RIGHT PARENTHESIS LOWER HOOK}' + ' ' + vectstrs[i]) else: tempstr = tempstr.replace(u'\\N{RIGHT PARENTHESIS UPPER HOOK}', u'\\N{RIGHT PARENTHESIS UPPER HOOK}' + ' ' + vectstrs[i]) o1[i] = tempstr o1 = [x.split('\\n') for x in o1] n_newlines = max([len(x) for x in o1]) for parts in o1: lengths.append(len(parts[0])) n_newlines = max([len(x) for x in o1]) # Width of part in its pretty form if 1 in flag: # If there was a fractional scalar for i, parts in enumerate(o1): if len(parts) == 1: # If part has no newline parts.insert(0, ' ' * (len(parts[0]))) flag[i] = 1 for i, parts in enumerate(o1): lengths.append(len(parts[flag[i]])) for j in range(n_newlines): if j+1 <= len(parts): if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) if j == 0: strs[0] += parts[0] + ' + ' if j == flag[i]: strs[flag[i]] += parts[flag[i]] + ' + ' else: strs[j] += parts[j] + ' '*(lengths[-1] - len(parts[j])+", "commid": "sympy__sympy-14308"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14317-4a266ab342226e4f79b6e2769eecc413df327bfb2aef9b3e5d5b0029d62e9161", "query": "LaTeX printer does not use the same order of monomials as pretty and str When printing a Poly, the str and pretty printers use the logical order of monomials, from highest to lowest degrees. But latex printer does not.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14317-78c05516cbb06f7a656f9cf3e45a58562d8994cc4d763b67c1355f1b55c070cc", "text": " def _print_Poly(self, poly): cls = poly.__class__.__name__ expr = self._print(poly.as_expr()) terms = [] for monom, coeff in poly.terms(): s_monom = '' for i, exp in enumerate(monom): if exp > 0: if exp == 1: s_monom += self._print(poly.gens[i]) else: s_monom += self._print(pow(poly.gens[i], exp)) if coeff.is_Add: if s_monom: s_coeff = r\"\\left(%s\\right)\" % self._print(coeff) else: s_coeff = self._print(coeff) else: if s_monom: if coeff is S.One: terms.extend(['+', s_monom]) continue if coeff is S.NegativeOne: terms.extend(['-', s_monom]) continue s_coeff = self._print(coeff) if not s_monom: s_term = s_coeff else: s_term = s_coeff + \" \" + s_monom if s_term.startswith('-'): terms.extend(['-', s_term[1:]]) else: terms.extend(['+', s_term]) if terms[0] in ['-', '+']: modifier = terms.pop(0) if modifier == '-': terms[0] = '-' + terms[0] expr = ' '.join(terms) gens = list(map(self._print, poly.gens)) domain = \"domain=%s\" % self._print(poly.get_domain())", "commid": "sympy__sympy-14317"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14333-caf3424a69e339412e268c638f7cd3a0bba3250d16163a93cefac34b616198f6", "query": "Modular inverse for negative modulo and sign resolve SymPy assigns the same sign as . Mathematically, has range for , for . The former sign assignment is used in C/C++/Java built-in modulo operator as returns . The latter sign assignment is used in Python's built-in modulo operator as returns . SymPy does not find modular inverses for negative modulo (because of the check). Moreover, as checked from WA (uses the same sign as rule)", "positive_passages": [{"docid": "doc-en-sympy__sympy-14333-efb20d9f015b4b65a1de663d331a619f8e8fae7022ce077c247dbc0f74cdd1c6", "text": " def mod_inverse(a, m): \"\"\" Return the number c such that, ( a * c ) % m == 1 where c has the same sign as a. If no such value exists, a ValueError is raised. Return the number c such that, (a * c) = 1 (mod m) where c has the same sign as m. If no such value exists, a ValueError is raised. Examples ========", "commid": "sympy__sympy-14333"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14333-caf3424a69e339412e268c638f7cd3a0bba3250d16163a93cefac34b616198f6", "query": "Modular inverse for negative modulo and sign resolve SymPy assigns the same sign as . Mathematically, has range for , for . The former sign assignment is used in C/C++/Java built-in modulo operator as returns . The latter sign assignment is used in Python's built-in modulo operator as returns . SymPy does not find modular inverses for negative modulo (because of the check). Moreover, as checked from WA (uses the same sign as rule)", "positive_passages": [{"docid": "doc-en-sympy__sympy-14333-3924e4ca3f42a80af69f71204c53688d9b5181236e6b7d496fae384a47897230", "text": " Suppose we wish to find multiplicative inverse x of 3 modulo 11. This is the same as finding x such that 3 * x = 1 (mod 11). One value of x that satisfies this congruence is 4. Because 3 * 4 = 12 and 12 = 1 mod(11). this congruence is 4. Because 3 * 4 = 12 and 12 = 1 (mod 11). This is the value return by mod_inverse: >>> mod_inverse(3, 11) 4 >>> mod_inverse(-3, 11) -4 7 When there is a common factor between the numerators of ``a`` and ``m`` the inverse does not exist:", "commid": "sympy__sympy-14333"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14333-caf3424a69e339412e268c638f7cd3a0bba3250d16163a93cefac34b616198f6", "query": "Modular inverse for negative modulo and sign resolve SymPy assigns the same sign as . Mathematically, has range for , for . The former sign assignment is used in C/C++/Java built-in modulo operator as returns . The latter sign assignment is used in Python's built-in modulo operator as returns . SymPy does not find modular inverses for negative modulo (because of the check). Moreover, as checked from WA (uses the same sign as rule)", "positive_passages": [{"docid": "doc-en-sympy__sympy-14333-2b6aac42d0d99d62ad34d7c126995767b4c45de2cd231301781a2878ec38e516", "text": " c = None try: a, m = as_int(a), as_int(m) if m > 1: if m != 1 and m != -1: x, y, g = igcdex(a, m) if g == 1: c = x % m if a < 0: c -= m except ValueError: a, m = sympify(a), sympify(m) if not (a.is_number and m.is_number):", "commid": "sympy__sympy-14333"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14396-de7451dfb75ed021f2ec478a3c9b9dca32f0f87a414d087351d55d90a256a1f2", "query": "Poly(domain='RR[y,z]') doesn't work Also, the wording of error message could be improved", "positive_passages": [{"docid": "doc-en-sympy__sympy-14396-b5d999624bcb518363f6845d05240ebbc7217038bd6ca32f87e0ca9f6bc93b62", "text": " _re_realfield = re.compile(r\"^(R|RR)(_(\\d+))?$\") _re_complexfield = re.compile(r\"^(C|CC)(_(\\d+))?$\") _re_finitefield = re.compile(r\"^(FF|GF)\\((\\d+)\\)$\") _re_polynomial = re.compile(r\"^(Z|ZZ|Q|QQ)\\[(.+)\\]$\") _re_polynomial = re.compile(r\"^(Z|ZZ|Q|QQ|R|RR|C|CC)\\[(.+)\\]$\") _re_fraction = re.compile(r\"^(Z|ZZ|Q|QQ)\\((.+)\\)$\") _re_algebraic = re.compile(r\"^(Q|QQ)\\<(.+)\\>$\") ", "commid": "sympy__sympy-14396"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14396-de7451dfb75ed021f2ec478a3c9b9dca32f0f87a414d087351d55d90a256a1f2", "query": "Poly(domain='RR[y,z]') doesn't work Also, the wording of error message could be improved", "positive_passages": [{"docid": "doc-en-sympy__sympy-14396-174b6227d58118ddc30738a5120d35f687991bd0b7450760e2398e80494ad11b", "text": " if ground in ['Z', 'ZZ']: return sympy.polys.domains.ZZ.poly_ring(*gens) else: elif ground in ['Q', 'QQ']: return sympy.polys.domains.QQ.poly_ring(*gens) elif ground in ['R', 'RR']: return sympy.polys.domains.RR.poly_ring(*gens) else: return sympy.polys.domains.CC.poly_ring(*gens) r = cls._re_fraction.match(domain)", "commid": "sympy__sympy-14396"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14564-01cd094863e210942b94b8d21a5b06820f94981122e1c6a45f828588a0c8735b", "query": "ambiguous behavior of ConditionSet Does that mean the \"set of all x in S for which condition(x) is True\" or \"the set S if the condition(x) is True\"? Also, should there be a doit method or autoevaluation for something like this? Other fixes: should be S.EmptySet should be unchanged: the dummy is not there to help with the condition, only to test idientify where the element from the base_set should be tested in the condition.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14564-b889197398c9e92d1d2f637b9f24201447a2e146098267e1ad9aa4d6a94db145", "text": " def _print_ConditionSet(self, s): vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)]) return r\"\\left\\{%s\\; |\\; %s \\in %s \\wedge %s \\right\\}\" % ( if s.base_set is S.UniversalSet: return r\"\\left\\{%s \\mid %s \\right\\}\" % ( vars_print, self._print(s.condition.as_expr())) return r\"\\left\\{%s \\mid %s \\in %s \\wedge %s \\right\\}\" % ( vars_print, vars_print, self._print(s.base_set),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", "commid": "sympy__sympy-14564"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14564-01cd094863e210942b94b8d21a5b06820f94981122e1c6a45f828588a0c8735b", "query": "ambiguous behavior of ConditionSet Does that mean the \"set of all x in S for which condition(x) is True\" or \"the set S if the condition(x) is True\"? Also, should there be a doit method or autoevaluation for something like this? Other fixes: should be S.EmptySet should be unchanged: the dummy is not there to help with the condition, only to test idientify where the element from the base_set should be tested in the condition.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14564-9ffd452fdf014e86f169c974f2ef0401093792675abaec414c63e06f0828f9bb", "text": " cond = self._print_seq(cond, \"(\", \")\") bar = self._print(\"|\") base = self._print(ts.base_set) if ts.base_set is S.UniversalSet: return self._print_seq((variables, bar, cond), \"{\", \"}\", ' ') base = self._print(ts.base_set) return self._print_seq((variables, bar, variables, inn, base, _and, cond), \"{\", \"}\", ' ') diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py", "commid": "sympy__sympy-14564"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14564-01cd094863e210942b94b8d21a5b06820f94981122e1c6a45f828588a0c8735b", "query": "ambiguous behavior of ConditionSet Does that mean the \"set of all x in S for which condition(x) is True\" or \"the set S if the condition(x) is True\"? Also, should there be a doit method or autoevaluation for something like this? Other fixes: should be S.EmptySet should be unchanged: the dummy is not there to help with the condition, only to test idientify where the element from the base_set should be tested in the condition.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14564-d6e8472e5c5a47a699e9ac2e7c0ea914d777d8f7bf663bceeefea43df4ea221a", "text": " def _print_ComplexInfinity(self, expr): return 'zoo' def _print_ConditionSet(self, s): args = tuple([self._print(i) for i in (s.sym, s.condition)]) if s.base_set is S.UniversalSet: return 'ConditionSet(%s, %s)' % args args += (self._print(s.base_set),) return 'ConditionSet(%s, %s, %s)' % args def _print_Derivative(self, expr): dexpr = expr.expr dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count]diff --git a/sympy/sets/conditionset.py b/sympy/sets/conditionset.py-- a/sympy/sets/conditionset.py++ b/sympy/sets/conditionset.py", "commid": "sympy__sympy-14564"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14564-01cd094863e210942b94b8d21a5b06820f94981122e1c6a45f828588a0c8735b", "query": "ambiguous behavior of ConditionSet Does that mean the \"set of all x in S for which condition(x) is True\" or \"the set S if the condition(x) is True\"? Also, should there be a doit method or autoevaluation for something like this? Other fixes: should be S.EmptySet should be unchanged: the dummy is not there to help with the condition, only to test idientify where the element from the base_set should be tested in the condition.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14564-ba5bf7072557d3a9cfda5ecf4ae0df258ac1c504e5d00401c7c93861a6b065ae", "text": " from __future__ import print_function, division from sympy import Sfrom sympy.sets.contains import Contains from sympy.core.basic import Basic from sympy.core.containers import Tuplefrom sympy.core.expr import Expr from sympy.core.function import Lambda from sympy.core.logic import fuzzy_bool from sympy.core.symbol import Symbol, Dummy", "commid": "sympy__sympy-14564"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14564-01cd094863e210942b94b8d21a5b06820f94981122e1c6a45f828588a0c8735b", "query": "ambiguous behavior of ConditionSet Does that mean the \"set of all x in S for which condition(x) is True\" or \"the set S if the condition(x) is True\"? Also, should there be a doit method or autoevaluation for something like this? Other fixes: should be S.EmptySet should be unchanged: the dummy is not there to help with the condition, only to test idientify where the element from the base_set should be tested in the condition.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14564-abb7ea18b1362be3d4d2af2002c9669e5ea48d7387e1965db9e01a239ab721d8", "text": " from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.utilities.iterables import siftfrom sympy.utilities.misc import filldedent from sympy.multipledispatch import dispatch ", "commid": "sympy__sympy-14564"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14564-01cd094863e210942b94b8d21a5b06820f94981122e1c6a45f828588a0c8735b", "query": "ambiguous behavior of ConditionSet Does that mean the \"set of all x in S for which condition(x) is True\" or \"the set S if the condition(x) is True\"? Also, should there be a doit method or autoevaluation for something like this? Other fixes: should be S.EmptySet should be unchanged: the dummy is not there to help with the condition, only to test idientify where the element from the base_set should be tested in the condition.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14564-990d1509d67f702e7ea66423baf3f18518d624f14464b4158514235ce64cd902", "text": " ======== >>> from sympy import Symbol, S, ConditionSet, pi, Eq, sin, Interval >>> x = Symbol('x') >>> from sympy.abc import x, y, z >>> sin_sols = ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi)) >>> 2*pi in sin_sols True", "commid": "sympy__sympy-14564"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14564-01cd094863e210942b94b8d21a5b06820f94981122e1c6a45f828588a0c8735b", "query": "ambiguous behavior of ConditionSet Does that mean the \"set of all x in S for which condition(x) is True\" or \"the set S if the condition(x) is True\"? Also, should there be a doit method or autoevaluation for something like this? Other fixes: should be S.EmptySet should be unchanged: the dummy is not there to help with the condition, only to test idientify where the element from the base_set should be tested in the condition.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14564-eb6f0c1072cfb13d9e5452413ae3128ed939387d6b1a77ea4a0252afb0d1511d", "text": " False >>> 5 in ConditionSet(x, x**2 > 4, S.Reals) True If the value is not in the base set, the result is false: >>> 5 in ConditionSet(x, x**2 > 4, Interval(2, 4)) False Notes ===== Symbols with assumptions should be avoided or else the condition may evaluate without consideration of the set: >>> n = Symbol('n', negative=True) >>> cond = (n > 0); cond False >>> ConditionSet(n, cond, S.Integers) EmptySet() In addition, substitution of a dummy symbol can only be done with a generic symbol with matching commutativity or else a symbol that has identical assumptions. If the base set contains the dummy symbol it is logically distinct and will be the target of substitution. >>> c = ConditionSet(x, x < 1, {x, z}) >>> c.subs(x, y) ConditionSet(x, x < 1, {y, z}) A second substitution is needed to change the dummy symbol, too: >>> _.subs(x, y) ConditionSet(y, y < 1, {y, z}) And trying to replace the dummy symbol with anything but a symbol is ignored: the only change possible will be in the base set: >>> ConditionSet(y, y < 1, {y, z}).subs(y, 1) ConditionSet(y, y < 1, {z}) >>> _.subs(y, 1) ConditionSet(y, y < 1, {z}) Notes ===== If no base set is specified, the universal set is implied: >>> ConditionSet(x, x < 1).base_set UniversalSet() Although expressions other than symbols may be used, this is discouraged and will raise an error if the expression is not found in the condition: >>> ConditionSet(x + 1, x + 1 < 1, S.Integers) ConditionSet(x + 1, x + 1 < 1, S.Integers) >>> ConditionSet(x + 1, x < 1, S.Integers) Traceback (most recent call last): ... ValueError: non-symbol dummy not recognized in condition Although the name is usually respected, it must be replaced if the base set is another ConditionSet and the dummy symbol and appears as a free symbol in the base set and the dummy symbol of the base set appears as a free symbol in the condition: >>> ConditionSet(x, x < y, ConditionSet(y, x + y < 2, S.Integers)) ConditionSet(lambda, (lambda < y) & (lambda + x < 2), S.Integers) The best way to do anything with the dummy symbol is to access it with the sym property. >>> _.subs(_.sym, Symbol('_x')) ConditionSet(_x, (_x < y) & (_x + x < 2), S.Integers) \"\"\" def __new__(cls, sym, condition, base_set): def __new__(cls, sym, condition, base_set=S.UniversalSet): # nonlinsolve uses ConditionSet to return an unsolved system # of equations (see _return_conditionset in solveset) so until # that is changed we do minimal checking of the args unsolved = isinstance(sym, (Tuple, tuple)) if unsolved: if isinstance(sym, (Tuple, tuple)): # unsolved eqns syntax sym = Tuple(*sym) condition = FiniteSet(*condition) else: condition = as_Boolean(condition) return Basic.__new__(cls, sym, condition, base_set) condition = as_Boolean(condition) if isinstance(base_set, set): base_set = FiniteSet(*base_set) elif not isinstance(base_set, Set): raise TypeError('expecting set for base_set') if condition == S.false: if condition is S.false: return S.EmptySet if condition == S.true: if condition is S.true: return base_set if isinstance(base_set, EmptySet): return base_set if not unsolved: if isinstance(base_set, FiniteSet): sifted = sift( base_set, lambda _: fuzzy_bool( condition.subs(sym, _))) if sifted[None]: return Union(FiniteSet(*sifted[True]), Basic.__new__(cls, sym, condition, FiniteSet(*sifted[None]))) else: return FiniteSet(*sifted[True]) if isinstance(base_set, cls): s, c, base_set = base_set.args if sym == s: condition = And(condition, c) elif sym not in c.free_symbols: condition = And(condition, c.xreplace({s: sym})) elif s not in condition.free_symbols: condition = And(condition.xreplace({sym: s}), c) sym = s else: # user will have to use cls.sym to get symbol dum = Symbol('lambda') if dum in condition.free_symbols or \\ dum in c.free_symbols: dum = Dummy(str(dum)) condition = And( condition.xreplace({sym: dum}), c.xreplace({s: dum})) sym = dum if sym in base_set.free_symbols or \\ not isinstance(sym, Symbol): s = Symbol('lambda') if s in base_set.free_symbols: s = Dummy('lambda') condition = condition.xreplace({sym: s}) know = None if isinstance(base_set, FiniteSet): sifted = sift( base_set, lambda _: fuzzy_bool( condition.subs(sym, _))) if sifted[None]: know = FiniteSet(*sifted[True]) base_set = FiniteSet(*sifted[None]) else: return FiniteSet(*sifted[True]) if isinstance(base_set, cls): s, c, base_set = base_set.args if sym == s: condition = And(condition, c) elif sym not in c.free_symbols: condition = And(condition, c.xreplace({s: sym})) elif s not in condition.free_symbols: condition = And(condition.xreplace({sym: s}), c) sym = s return Basic.__new__(cls, sym, condition, base_set) else: # user will have to use cls.sym to get symbol dum = Symbol('lambda') if dum in condition.free_symbols or \\ dum in c.free_symbols: dum = Dummy(str(dum)) condition = And( condition.xreplace({sym: dum}), c.xreplace({s: dum})) sym = dum if not isinstance(sym, Symbol): s = Dummy('lambda') if s not in condition.xreplace({sym: s}).free_symbols: raise ValueError( 'non-symbol dummy not recognized in condition') rv = Basic.__new__(cls, sym, condition, base_set) return rv if know is None else Union(know, rv) sym = property(lambda self: self.args[0]) condition = property(lambda self: self.args[1])", "commid": "sympy__sympy-14564"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14564-01cd094863e210942b94b8d21a5b06820f94981122e1c6a45f828588a0c8735b", "query": "ambiguous behavior of ConditionSet Does that mean the \"set of all x in S for which condition(x) is True\" or \"the set S if the condition(x) is True\"? Also, should there be a doit method or autoevaluation for something like this? Other fixes: should be S.EmptySet should be unchanged: the dummy is not there to help with the condition, only to test idientify where the element from the base_set should be tested in the condition.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14564-37c749cf307ada052da16e04f42a596d9f31bffeede250ca9a6868b6ad5fe19e", "text": " other), self.base_set.contains(other)) def _eval_subs(self, old, new): if not isinstance(self.sym, Symbol): if not isinstance(self.sym, Expr): # Don't do anything with the equation set syntax; # that should go away, eventually. return self if old == self.sym: if new not in self.free_symbols: if isinstance(new, Symbol): return self.func(*[i.subs(old, new) for i in self.args]) return self.func(self.sym, self.condition, self.base_set.subs(old, new)) return self.func(*([self.sym] + [i.subs(old, new) for i in self.args[1:]])) sym, cond, base = self.args if old == sym: # we try to be as lenient as possible to allow # the dummy symbol to be changed base = base.subs(old, new) if isinstance(new, Symbol): # if the assumptions don't match, the cond # might evaluate or change if (new.assumptions0 == old.assumptions0 or len(new.assumptions0) == 1 and old.is_commutative == new.is_commutative): if base != self.base_set: # it will be aggravating to have the dummy # symbol change if you are trying to target # the base set so if the base set is changed # leave the dummy symbol alone -- a second # subs will be needed to change the dummy return self.func(sym, cond, base) else: return self.func(new, cond.subs(old, new), base) raise ValueError(filldedent(''' A dummy symbol can only be replaced with a symbol having the same assumptions or one having a single assumption having the same commutativity. ''')) # don't target cond: it is there to tell how # the base set should be filtered and if new is not in # the base set then this substitution is ignored return self.func(sym, cond, base) cond = self.condition.subs(old, new) base = self.base_set.subs(old, new) if cond is S.true: return ConditionSet(new, Contains(new, base), base) return self.func(self.sym, cond, base) def dummy_eq(self, other, symbol=None): if not isinstance(other, self.func):", "commid": "sympy__sympy-14564"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14575-52839642d6156bbafb810904c8847ed9d9eeddf739185cd773462d4dd70f7931", "query": "Incorrect binomial documentation The for states: This is the usual definition of the binomial coefficient, but the implementation does not follow this. To be exact, returns , even for negative . See . For example: ` It shouldn't be hard to fix this either way (changing the documentation or the conditionals in ). Is there a preference as to which one should change?", "positive_passages": [{"docid": "doc-en-sympy__sympy-14575-aad0331ca0e48d55ae11dd13e8ee0ccaab5ed8ca1c5b9144ccb049a5cf983b32", "text": " @classmethod def eval(cls, n, k): n, k = map(sympify, (n, k)) d = n - k if d.is_zero or k.is_zero: if k.is_zero: return S.One if (k - 1).is_zero: return n if k.is_integer: if k.is_negative: if k.is_negative or (n.is_integer and n.is_nonnegative and (n - k).is_negative): return S.Zero if n.is_integer and n.is_nonnegative and d.is_negative: return S.Zero if n.is_number: elif n.is_number: res = cls._eval(n, k) return res.expand(basic=True) if res else res elif n.is_negative and n.is_integer and not k.is_integer: elif n.is_negative and n.is_integer: # a special case when binomial evaluates to complex infinity return S.ComplexInfinity elif k.is_number:", "commid": "sympy__sympy-14575"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14627-3889a2112147800e87c351b0e98618df4e31d09337ec2b630c1c79ebc5c34df7", "query": "binomial(n,n) needs simplify to become 1 After , does not become 1. Sure. But even with appropriate assumptions, we need to simplify: was that intentional? Maybe its not important given that DTRT with ... Thoughts?", "positive_passages": [{"docid": "doc-en-sympy__sympy-14627-241e2b192b2e37e3d25f283458e1c13bf8b0658fdbd3852db7d1b9d22d6cc030", "text": " @classmethod def eval(cls, n, k): n, k = map(sympify, (n, k)) if k.is_zero: d = n - k n_nonneg, n_isint = n.is_nonnegative, n.is_integer if k.is_zero or ((n_nonneg or n_isint == False) and d.is_zero): return S.One if (k - 1).is_zero: if (k - 1).is_zero or ((n_nonneg or n_isint == False) and (d - 1).is_zero): return n if k.is_integer: if k.is_negative or (n.is_integer and n.is_nonnegative and (n - k).is_negative): if k.is_negative or (n_nonneg and n_isint and d.is_negative): return S.Zero elif n.is_number: res = cls._eval(n, k) return res.expand(basic=True) if res else res elif n.is_negative and n.is_integer: elif n_nonneg == False and n_isint: # a special case when binomial evaluates to complex infinity return S.ComplexInfinity elif k.is_number:", "commid": "sympy__sympy-14627"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14699-4717f6ade59192c7b38d4a372018ed52af3353dcdb17b13f8fba1cd0f72564d1", "query": "orientnew in sympy.physics.mechanics does not support indices Original issue for : Original author:", "positive_passages": [{"docid": "doc-en-sympy__sympy-14699-1138c3697f34c42bfc88c3bd67cc563ca789734d5769aeb50ce065b5038eb9b3", "text": " \"\"\" newframe = self.__class__(newname, variables, indices, latexs) newframe = self.__class__(newname, variables=variables, indices=indices, latexs=latexs) newframe.orient(self, rot_type, amounts, rot_order) return newframe", "commid": "sympy__sympy-14699"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14774-7541baabcd95b87c31f17654d27b6e5a87dc13c33380e3a00831be965f30dc28", "query": "Latex printer does not support full inverse trig function names for acsc and asec For example works as expected returning But gives instead of A fix seems to be to change line 743 of from to", "positive_passages": [{"docid": "doc-en-sympy__sympy-14774-499d22350bb63311002919e24f6452c577463c89dd4c4f81ee8f37154b544872", "text": " len(args) == 1 and \\ not self._needs_function_brackets(expr.args[0]) inv_trig_table = [\"asin\", \"acos\", \"atan\", \"acot\"] inv_trig_table = [\"asin\", \"acos\", \"atan\", \"acsc\", \"asec\", \"acot\"] # If the function is an inverse trig function, handle the style if func in inv_trig_table:", "commid": "sympy__sympy-14774"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14817-636fb95db85679664a7df69e3d75229226de0ed0f51b5bdda70f0eb1b9ba3485", "query": "Error pretty printing MatAdd The code shouldn't be using sympify to handle string arguments from MatrixSymbol. I don't even understand what the code is doing. Why does it omit the when the first argument is negative? This seems to assume that the arguments of MatAdd have a certain form, and that they will always print a certain way if they are negative.", "positive_passages": [{"docid": "doc-en-sympy__sympy-14817-44fb89463d46964b87b3c65cdd3d50f7224ee04b9891a69e90884bf2a0fb08d1", "text": " if s is None: s = pform # First element else: if S(item.args[0]).is_negative: coeff = item.as_coeff_mmul()[0] if _coeff_isneg(S(coeff)): s = prettyForm(*stringPict.next(s, ' ')) pform = self._print(item) else:", "commid": "sympy__sympy-14817"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-14976-7eff69347dcbef152ad333ac9779f3c52f21e0b89ea25875c8a70e02ec05233d", "query": "lambdify(modules='mpmath') doesn't wrap rationals This results in reduced precision results from , because the 232/3 isn't evaluated at full precision. Originally reported at", "positive_passages": [{"docid": "doc-en-sympy__sympy-14976-ce0aa487e2973e94de36dfedb8068454b80b5bac98375183362052ea29f75855", "text": " return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args) def _print_Rational(self, e): return '{0}({1})/{0}({2})'.format( self._module_format('mpmath.mpf'), e.p, e.q, ) def _print_uppergamma(self, e): return \"{0}({1}, {2}, {3})\".format( self._module_format('mpmath.gammainc'),", "commid": "sympy__sympy-14976"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15011-5513217ea9a0cfe8f5b6bbb382046ef6d89d01457fce70f34ceeb2cf9aee941f", "query": "lambdify does not work with certain MatrixSymbol names even with dummify=True is happy with curly braces in a symbol name and with s, but not with both at the same time, even if is . Here is some basic code that gives the error. The following two lines of code work: The following two lines of code give a :", "positive_passages": [{"docid": "doc-en-sympy__sympy-15011-a15f18b2b0feb6724883303393bd9dda209acf577f49336637cefbb88598d64d", "text": " return isinstance(ident, str) and cls._safe_ident_re.match(ident) \\ and not (keyword.iskeyword(ident) or ident == 'None') def _preprocess(self, args, expr): \"\"\"Preprocess args, expr to replace arguments that do not map to valid Python identifiers. Returns string form of args, and updated expr. \"\"\" from sympy import Dummy, Symbol, Function, flatten from sympy import Dummy, Symbol, MatrixSymbol, Function, flatten from sympy.matrices import DeferredVector dummify = self._dummify", "commid": "sympy__sympy-15011"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15011-5513217ea9a0cfe8f5b6bbb382046ef6d89d01457fce70f34ceeb2cf9aee941f", "query": "lambdify does not work with certain MatrixSymbol names even with dummify=True is happy with curly braces in a symbol name and with s, but not with both at the same time, even if is . Here is some basic code that gives the error. The following two lines of code work: The following two lines of code give a :", "positive_passages": [{"docid": "doc-en-sympy__sympy-15011-684189fecea77aebf3f9fec5acdb5707bd5d170aa532e24131a05de73410aa44", "text": " argstrs.append(nested_argstrs) elif isinstance(arg, DeferredVector): argstrs.append(str(arg)) elif isinstance(arg, Symbol): elif isinstance(arg, Symbol) or isinstance(arg, MatrixSymbol): argrep = self._argrepr(arg) if dummify or not self._is_safe_ident(argrep):", "commid": "sympy__sympy-15011"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15011-5513217ea9a0cfe8f5b6bbb382046ef6d89d01457fce70f34ceeb2cf9aee941f", "query": "lambdify does not work with certain MatrixSymbol names even with dummify=True is happy with curly braces in a symbol name and with s, but not with both at the same time, even if is . Here is some basic code that gives the error. The following two lines of code work: The following two lines of code give a :", "positive_passages": [{"docid": "doc-en-sympy__sympy-15011-4cdb6db641d60d3d0917731c9aee6e2cb2be4805933e47ad90192f45ca2ec3ef", "text": " argstrs.append(self._argrepr(dummy)) expr = self._subexpr(expr, {arg: dummy}) else: argstrs.append(str(arg)) argrep = self._argrepr(arg) if dummify: dummy = Dummy() argstrs.append(self._argrepr(dummy)) expr = self._subexpr(expr, {arg: dummy}) else: argstrs.append(str(arg)) return argstrs, expr", "commid": "sympy__sympy-15011"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15017-99241cecc403fb90e163aa7365d328535416fe9af538899ab76f2e2b8a317c8d", "query": "of rank-0 arrays returns 0 always returns zero for rank-0 arrays (scalars). I believe the correct value should be one, which is the number of elements of the iterator and the observed behaviour in numpy. In numpy we have the following: This was tested in sympy 1.2-rc1 running in Python 3.6.6 of rank-0 arrays returns 0 always returns zero for rank-0 arrays (scalars). I believe the correct value should be one, which is the number of elements of the iterator and the observed behaviour in numpy. In numpy we have the following: This was tested in sympy 1.2-rc1 running in Python 3.6.6", "positive_passages": [{"docid": "doc-en-sympy__sympy-15017-d181c47afea61e075f62f37ff2e43ede497a274abedff3e86f1d74231eb77053", "text": " self._shape = shape self._array = list(flat_list) self._rank = len(shape) self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0 self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1) return self def __setitem__(self, index, value):", "commid": "sympy__sympy-15017"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15085-6c8ab12aab75156b560190085b367c09e64623a9172fa79adbdb5206a866352b", "query": "[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:", "positive_passages": [{"docid": "doc-en-sympy__sympy-15085-202e3489d6102e268b2e6143e9186502a3b41e5d081d655abc2471d05126828f", "text": " 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': True, 'contract': True, 'dereference': set(), 'error_on_reserved': False,diff --git a/sympy/printing/codeprinter.py b/sympy/printing/codeprinter.py-- a/sympy/printing/codeprinter.py++ b/sympy/printing/codeprinter.py", "commid": "sympy__sympy-15085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15085-6c8ab12aab75156b560190085b367c09e64623a9172fa79adbdb5206a866352b", "query": "[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:", "positive_passages": [{"docid": "doc-en-sympy__sympy-15085-afca6768972c98d9e7ead1aa852d06131ae22ad78002915242283165db457586", "text": " 'error_on_reserved': False, 'reserved_word_suffix': '_', 'human': True, 'inline': False 'inline': False, 'allow_unknown_functions': True, } def __init__(self, settings=None):", "commid": "sympy__sympy-15085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15085-6c8ab12aab75156b560190085b367c09e64623a9172fa79adbdb5206a866352b", "query": "[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:", "positive_passages": [{"docid": "doc-en-sympy__sympy-15085-a7f004a991859e67972f766275b67510394b9ecc5dce9a84ce6071ac1bc5b292", "text": " elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda): # inlined function return self._print(expr._imp_(*expr.args)) elif expr.is_Function and self._settings.get('allow_unknown_functions', True): return '%s(%s)' % (self._print(expr.func), ', '.join(map(self._print, expr.args))) else: return self._print_not_supported(expr) diff --git a/sympy/printing/fcode.py b/sympy/printing/fcode.py-- a/sympy/printing/fcode.py++ b/sympy/printing/fcode.py", "commid": "sympy__sympy-15085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15085-6c8ab12aab75156b560190085b367c09e64623a9172fa79adbdb5206a866352b", "query": "[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:", "positive_passages": [{"docid": "doc-en-sympy__sympy-15085-2d99cc8ace2d275b0d174231ff675c8cba4c483713db94b4def0bcfd73551562", "text": " 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': True, 'source_format': 'fixed', 'contract': True, 'standard': 77,diff --git a/sympy/printing/glsl.py b/sympy/printing/glsl.py-- a/sympy/printing/glsl.py++ b/sympy/printing/glsl.py", "commid": "sympy__sympy-15085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15085-6c8ab12aab75156b560190085b367c09e64623a9172fa79adbdb5206a866352b", "query": "[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:", "positive_passages": [{"docid": "doc-en-sympy__sympy-15085-af2d6958b25558d03fc8b10d394d3a3fba537cf483f24d524b70a5696fa09056", "text": " 'precision': 9, 'user_functions': {}, 'human': True, 'allow_unknown_functions': True, 'contract': True, 'error_on_reserved': False, 'reserved_word_suffix': '_'diff --git a/sympy/printing/jscode.py b/sympy/printing/jscode.py-- a/sympy/printing/jscode.py++ b/sympy/printing/jscode.py", "commid": "sympy__sympy-15085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15085-6c8ab12aab75156b560190085b367c09e64623a9172fa79adbdb5206a866352b", "query": "[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:", "positive_passages": [{"docid": "doc-en-sympy__sympy-15085-8e15ef26708603c1dc3dd83248ae257207a4c50f1aa8b361160f4d94319d7a45", "text": " 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': True, 'contract': True } diff --git a/sympy/printing/julia.py b/sympy/printing/julia.py-- a/sympy/printing/julia.py++ b/sympy/printing/julia.py", "commid": "sympy__sympy-15085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15085-6c8ab12aab75156b560190085b367c09e64623a9172fa79adbdb5206a866352b", "query": "[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:", "positive_passages": [{"docid": "doc-en-sympy__sympy-15085-d447be23595e91627f024ea9730046bd21d1fcbd78a16bbdbb371efd1c4d2c1f", "text": " 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': True, 'contract': True, 'inline': True, }diff --git a/sympy/printing/mathematica.py b/sympy/printing/mathematica.py-- a/sympy/printing/mathematica.py++ b/sympy/printing/mathematica.py", "commid": "sympy__sympy-15085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15085-6c8ab12aab75156b560190085b367c09e64623a9172fa79adbdb5206a866352b", "query": "[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:", "positive_passages": [{"docid": "doc-en-sympy__sympy-15085-af052329cae004cb07bfc0709ac9c651c8cab78b71b14e2bde23c565468a6be7", "text": " 'precision': 15, 'user_functions': {}, 'human': True, 'allow_unknown_functions': True, } _number_symbols = set()diff --git a/sympy/printing/octave.py b/sympy/printing/octave.py-- a/sympy/printing/octave.py++ b/sympy/printing/octave.py", "commid": "sympy__sympy-15085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15085-6c8ab12aab75156b560190085b367c09e64623a9172fa79adbdb5206a866352b", "query": "[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:", "positive_passages": [{"docid": "doc-en-sympy__sympy-15085-0944e0b826df0b55c760c7c951647d4f7c2d27c89622efdfd450a5209b8f7f33", "text": " 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': True, 'contract': True, 'inline': True, }", "commid": "sympy__sympy-15085"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15151-3ff81212e3630b069d01dbd23bae48c62ae54c6840831c441003a648f923b298", "query": "not pretty printing indexed(x1, i) not sure if this is expected behavior but i'm expecting x_{1,i} !", "positive_passages": [{"docid": "doc-en-sympy__sympy-15151-46c7546b0f45c10edee8f11804d69683999d9a2fbf75072594cc44ed24088f44", "text": " return outstr def _print_Indexed(self, expr): tex = self._print(expr.base)+'_{%s}' % ','.join( tex_base = self._print(expr.base) tex = '{'+tex_base+'}'+'_{%s}' % ','.join( map(self._print, expr.indices)) return tex", "commid": "sympy__sympy-15151"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15225-49cd256514d6e64e428c2137fb67ad18e4f031036e98f262bf38f6b88ca91cb3", "query": "xor boolmap equivalent to xnor? - Flaw in finger fingerprint results in The simplified functions fro f1 and f2 are correct, and clearly different, yet bool_map returned what it though to be a valid symbol mapping?", "positive_passages": [{"docid": "doc-en-sympy__sympy-15225-8bcb1e4ac34c1d8abdf661da6f7c1d5d82bf056ba06c0d11ba7c2529900f433a", "text": " # of times it appeared as a Not(symbol), # of times it appeared as a Symbol in an And or Or, # of times it appeared as a Not(Symbol) in an And or Or, sum of the number of arguments with which it appeared, counting Symbol as 1 and Not(Symbol) as 2 sum of the number of arguments with which it appeared as a Symbol, counting Symbol as 1 and Not(Symbol) as 2 and counting self as 1 ] >>> from sympy.logic.boolalg import _finger as finger", "commid": "sympy__sympy-15225"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15225-49cd256514d6e64e428c2137fb67ad18e4f031036e98f262bf38f6b88ca91cb3", "query": "xor boolmap equivalent to xnor? - Flaw in finger fingerprint results in The simplified functions fro f1 and f2 are correct, and clearly different, yet bool_map returned what it though to be a valid symbol mapping?", "positive_passages": [{"docid": "doc-en-sympy__sympy-15225-908b7174bd9ef4e87e94b22fc79c4ae1a2d6505bf8b9b0f182de692f5d44d211", "text": " >>> from sympy.abc import a, b, x, y >>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y)) >>> dict(finger(eq)) {(0, 0, 1, 0, 2): [x], (0, 0, 1, 0, 3): [a, b], (0, 0, 1, 2, 8): [y]} {(0, 0, 1, 0, 2): [x], (0, 0, 1, 0, 3): [a, b], (0, 0, 1, 2, 2): [y]} >>> dict(finger(x & ~y)) {(0, 1, 0, 0, 0): [y], (1, 0, 0, 0, 0): [x]} The equation must not have more than one level of nesting: >>> dict(finger(And(Or(x, y), y))) {(0, 0, 1, 0, 2): [x], (1, 0, 1, 0, 2): [y]} >>> dict(finger(And(Or(x, And(a, x)), y))) Traceback (most recent call last): ... NotImplementedError: unexpected level of nesting So y and x have unique fingerprints, but a and b do not. \"\"\"", "commid": "sympy__sympy-15225"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15225-49cd256514d6e64e428c2137fb67ad18e4f031036e98f262bf38f6b88ca91cb3", "query": "xor boolmap equivalent to xnor? - Flaw in finger fingerprint results in The simplified functions fro f1 and f2 are correct, and clearly different, yet bool_map returned what it though to be a valid symbol mapping?", "positive_passages": [{"docid": "doc-en-sympy__sympy-15225-22b56790489f1e06941c2f116f0422146bd6ef27ce8af130d479bdba9d97d385", "text": " if ai.is_Symbol: d[ai][2] += 1 d[ai][-1] += o else: elif ai.is_Not: d[ai.args[0]][3] += 1 d[ai.args[0]][-1] += o else: raise NotImplementedError('unexpected level of nesting') inv = defaultdict(list) for k, v in ordered(iter(d.items())): inv[tuple(v)].append(k)", "commid": "sympy__sympy-15225"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15225-49cd256514d6e64e428c2137fb67ad18e4f031036e98f262bf38f6b88ca91cb3", "query": "xor boolmap equivalent to xnor? - Flaw in finger fingerprint results in The simplified functions fro f1 and f2 are correct, and clearly different, yet bool_map returned what it though to be a valid symbol mapping?", "positive_passages": [{"docid": "doc-en-sympy__sympy-15225-ac901554ed8fbd1b45151abd4ff01a2c24437ce0e25bc43c00dc1e3bdeb74f2d", "text": " # do some quick checks if function1.__class__ != function2.__class__: return None return None # maybe simplification would make them the same if len(function1.args) != len(function2.args): return None return None # maybe simplification would make them the same if function1.is_Symbol: return {function1: function2} ", "commid": "sympy__sympy-15225"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15225-49cd256514d6e64e428c2137fb67ad18e4f031036e98f262bf38f6b88ca91cb3", "query": "xor boolmap equivalent to xnor? - Flaw in finger fingerprint results in The simplified functions fro f1 and f2 are correct, and clearly different, yet bool_map returned what it though to be a valid symbol mapping?", "positive_passages": [{"docid": "doc-en-sympy__sympy-15225-498e3df415623fdf32c675f0e6c786f4fcfcb96d9f7ad452c02c22a1264f531e", "text": " m = match(a, b) if m: return a, m return m is not None return m", "commid": "sympy__sympy-15225"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15231-7316f6b4b27088979ec724a1dd644bdd1474d9a0e0a6eea1deca2d4310d1552a", "query": "autowrap fortran fails with expression containing Mod function twice Minimal example: Error: And here's the generated code. Clearly the problem is that Mod gets imported twice. Hopefully this is an easy fix but I don't know where to start.", "positive_passages": [{"docid": "doc-en-sympy__sympy-15231-8f4f6d91b15a6c8fed1fe22e62e31fb9e36904c6cd19c712c16c2f114a03ba2d", "text": " \"Abs\": \"abs\", \"conjugate\": \"conjg\", \"Max\": \"max\", \"Min\": \"min\" \"Min\": \"min\", } ", "commid": "sympy__sympy-15231"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15231-7316f6b4b27088979ec724a1dd644bdd1474d9a0e0a6eea1deca2d4310d1552a", "query": "autowrap fortran fails with expression containing Mod function twice Minimal example: Error: And here's the generated code. Clearly the problem is that Mod gets imported twice. Hopefully this is an easy fix but I don't know where to start.", "positive_passages": [{"docid": "doc-en-sympy__sympy-15231-faf555f723dd8504e934c4da43d49b8781845c78dafacb416379269d2ace07f9", "text": " else: return CodePrinter._print_Function(self, expr.func(*args)) def _print_Mod(self, expr): # NOTE : Fortran has the functions mod() and modulo(). modulo() behaves # the same wrt to the sign of the arguments as Python and SymPy's # modulus computations (% and Mod()) but is not available in Fortran 66 # or Fortran 77, thus we raise an error. if self._settings['standard'] in [66, 77]: msg = (\"Python % operator and SymPy's Mod() function are not \" \"supported by Fortran 66 or 77 standards.\") raise NotImplementedError(msg) else: x, y = expr.args return \" modulo({}, {})\".format(self._print(x), self._print(y)) def _print_ImaginaryUnit(self, expr): # purpose: print complex numbers nicely in Fortran. return \"cmplx(0,1)\"diff --git a/sympy/utilities/codegen.py b/sympy/utilities/codegen.py-- a/sympy/utilities/codegen.py++ b/sympy/utilities/codegen.py", "commid": "sympy__sympy-15231"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15231-7316f6b4b27088979ec724a1dd644bdd1474d9a0e0a6eea1deca2d4310d1552a", "query": "autowrap fortran fails with expression containing Mod function twice Minimal example: Error: And here's the generated code. Clearly the problem is that Mod gets imported twice. Hopefully this is an easy fix but I don't know where to start.", "positive_passages": [{"docid": "doc-en-sympy__sympy-15231-da135c6931ebace0ec08aab1318d7df77fec6c5372016433c943f38cf31aed44", "text": " assign_to = result.result_var constants, not_fortran, f_expr = self._printer_method_with_settings( 'doprint', dict(human=False, source_format='free'), 'doprint', dict(human=False, source_format='free', standard=95), result.expr, assign_to=assign_to) for obj, v in sorted(constants, key=str):", "commid": "sympy__sympy-15231"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15232-6dedfe521aadd59d9aeda9bb827d84fb5129a2b9e09302956b20139071c7aa97", "query": "factor() function issue for non-commutative objects In commit by from line 652 to line 660 in the file , there are some parts that I couldn't understand: I am trying to add a non-commutative class whose freesymbols are commutative. (e.g., operator with time dependence) In this case, even if the object itself is non-commutative, the factor() function gives the wrong result, because of the lines In my understanding, this line treats a non-commutative object as commutative if all its freesymbols are commutative. What is the purpose of this line?", "positive_passages": [{"docid": "doc-en-sympy__sympy-15232-79ac2269aecf661a2ab62dfd959afc12fe925d42d3da105138a0a85da884c2d0", "text": " if a.is_Symbol: nc_syms.add(a) elif not (a.is_Add or a.is_Mul or a.is_Pow): if all(s.is_commutative for s in a.free_symbols): rep.append((a, Dummy())) else: nc_obj.add(a) nc_obj.add(a) pot.skip() # If there is only one nc symbol or object, it can be factored regularly", "commid": "sympy__sympy-15232"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15241-f1f32dac05439c6fff3681cebabda4445a3040c4b87ac60fbd4dae6457c940cb", "query": "better canonicalization of variables of Derivative Better canonicalization of will be had if any symbols, appearing after functions, that are not in the free symbols of the function, appear before the functions: should equal .", "positive_passages": [{"docid": "doc-en-sympy__sympy-15241-257782251d884cda9fdc8a9861a0c406b5d5253de11153c44d6f2ea04ffee23f", "text": " return [i[0] if i[1] == 1 else i for i in v] @classmethod def _sort_variable_count(cls, varcounts): def _sort_variable_count(cls, vc): \"\"\" Sort (variable, count) pairs by variable, but disallow sorting of non-symbols. Sort (variable, count) pairs into canonical order while retaining order of variables that do not commute during differentiation: The count is not sorted. It is kept in the same order as the input after sorting by variable. When taking derivatives, the following rules usually hold: * Derivative wrt different symbols commute. * Derivative wrt different non-symbols commute. * Derivatives wrt symbols and non-symbols don't commute. * symbols and functions commute with each other * derivatives commute with each other * a derivative doesn't commute with anything it contains * any other object is not allowed to commute if it has free symbols in common with another object Examples ======== >>> from sympy import Derivative, Function, symbols >>> from sympy import Derivative, Function, symbols, cos >>> vsort = Derivative._sort_variable_count >>> x, y, z = symbols('x y z') >>> f, g, h = symbols('f g h', cls=Function) >>> vsort([(x, 3), (y, 2), (z, 1)]) [(x, 3), (y, 2), (z, 1)] >>> vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) [(f(x), 1), (g(x), 1), (h(x), 1)] Contiguous items are collapsed into one pair: >>> vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1), (f(x), 1)]) [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)] >>> vsort([(x, 1), (x, 1)]) [(x, 2)] >>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)]) [(y, 2), (f(x), 2)] >>> vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) [(x, 1), (f(x), 1), (y, 1), (f(y), 1)] Ordering is canonical. >>> vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1), (h(x), 1), (y, 2), (x, 1)]) [(x, 2), (y, 1), (f(x), 1), (g(x), 1), (z, 1), (h(x), 1), (x, 1), (y, 2)] >>> def vsort0(*v): ... # docstring helper to ... # change vi -> (vi, 0), sort, and return vi vals ... return [i[0] for i in vsort([(i, 0) for i in v])] >>> vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1), (g(x), 1)]) [(y, 1), (z, 1), (f(x), 1), (x, 1), (f(x), 1), (g(x), 1)] >>> vsort0(y, x) [x, y] >>> vsort0(g(y), g(x), f(y)) [f(y), g(x), g(y)] >>> vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2), (g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)]) [(y, 2), (z, 1), (f(x), 1), (x, 2), (f(x), 2), (g(x), 1), (x, 1), (y, 1), (z, 2), (z, 1)] Symbols are sorted as far to the left as possible but never move to the left of a derivative having the same symbol in its variables; the same applies to AppliedUndef which are always sorted after Symbols: >>> dfx = f(x).diff(x) >>> assert vsort0(dfx, y) == [y, dfx] >>> assert vsort0(dfx, x) == [dfx, x] \"\"\" sorted_vars = [] symbol_part = [] non_symbol_part = [] for (v, c) in varcounts: if not v.is_symbol: if len(symbol_part) > 0: sorted_vars.extend(sorted(symbol_part, key=lambda i: default_sort_key(i[0]))) symbol_part = [] non_symbol_part.append((v, c)) from sympy.utilities.iterables import uniq, topological_sort if not vc: return [] vc = list(vc) if len(vc) == 1: return [Tuple(*vc[0])] V = list(range(len(vc))) E = [] v = lambda i: vc[i][0] D = Dummy() def _block(d, v, wrt=False): # return True if v should not come before d else False if d == v: return wrt if d.is_Symbol: return False if isinstance(d, Derivative): # a derivative blocks if any of it's variables contain # v; the wrt flag will return True for an exact match # and will cause an AppliedUndef to block if v is in # the arguments if any(_block(k, v, wrt=True) for k, _ in d.variable_count): return True return False if not wrt and isinstance(d, AppliedUndef): return False if v.is_Symbol: return v in d.free_symbols if isinstance(v, AppliedUndef): return _block(d.xreplace({v: D}), D) return d.free_symbols & v.free_symbols for i in range(len(vc)): for j in range(i): if _block(v(j), v(i)): E.append((j,i)) # this is the default ordering to use in case of ties O = dict(zip(ordered(uniq([i for i, c in vc])), range(len(vc)))) ix = topological_sort((V, E), key=lambda i: O[v(i)]) # merge counts of contiguously identical items merged = [] for v, c in [vc[i] for i in ix]: if merged and merged[-1][0] == v: merged[-1][1] += c else: if len(non_symbol_part) > 0: sorted_vars.extend(sorted(non_symbol_part, key=lambda i: default_sort_key(i[0]))) non_symbol_part = [] symbol_part.append((v, c)) if len(non_symbol_part) > 0: sorted_vars.extend(sorted(non_symbol_part, key=lambda i: default_sort_key(i[0]))) if len(symbol_part) > 0: sorted_vars.extend(sorted(symbol_part, key=lambda i: default_sort_key(i[0]))) return [Tuple(*i) for i in sorted_vars] merged.append([v, c]) return [Tuple(*i) for i in merged] def _eval_is_commutative(self): return self.expr.is_commutative", "commid": "sympy__sympy-15241"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-15286-0edc0775dc8f1df47ca350a76b1b01508c44f83513beb76e7264fbbd46bfe004", "query": "recognize elliptical integrals Original issue for : Original author: Added function for finding equation of Ellipse using slope as parameter and faster method for calculation of circumference of ellipse Added function for finding equation of Ellipse using slope as parameter. Added another method for calculation of circumference of ellipse. Added a new method called Pluralized the following methods -- This PR uses the approach to finding equation of ellipse using slope, length of semi minor axis and length of semi major axis as inputs given This could be an functionality to the equation finding method in class . Thanks to for providing the approach. Please take a look at this PR and suggest changes. I will be glad to implement them. Thanks. L_{n-1}(x) if n.could_extract_minus_sign(): if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign(): return legendre(-n - S.One, x) # We can evaluate for some special values of x if x == S.Zero:", "commid": "sympy__sympy-17010"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-17010-3128aeaa1eae457436e159fd4ffb7071c44e21f111f054c97af9caef3dc02310", "query": "Some uses of couldextractminussign can lead to infinite recursion The issue coming from was fixed, but there is another issue has come up in my pull request Several places in use couldextractminussign() in a way that can lead to infinite recursion. For example, in : The problem is that both and could be True, leading to infinite recursion. This happens in my branch for , but probably an example could be found for master too. We need a more robust way to canonicalize this. Ideally we'd want to remove the minus sign from the highest order term. Is there a fast way to do that?", "positive_passages": [{"docid": "doc-en-sympy__sympy-17010-cae5fd4ff040f514694dceffc096fc1848387cfe23573e407154cc71ab7ccc62", "text": " @classmethod def eval(cls, n, x): if n.is_integer is False: raise ValueError(\"Error: n should be an integer.\") if not n.is_Number: # Symbolic result L_n(x) # L_{n}(-x) ---> exp(-x) * L_{-n-1}(x) # L_{-n}(x) ---> exp(x) * L_{n-1}(-x) if n.could_extract_minus_sign(): return exp(x) * laguerre(n - 1, -x) if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign(): return exp(x)*laguerre(-n - 1, -x) # We can evaluate for some special values of x if x == S.Zero: return S.One", "commid": "sympy__sympy-17010"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-17010-3128aeaa1eae457436e159fd4ffb7071c44e21f111f054c97af9caef3dc02310", "query": "Some uses of couldextractminussign can lead to infinite recursion The issue coming from was fixed, but there is another issue has come up in my pull request Several places in use couldextractminussign() in a way that can lead to infinite recursion. For example, in : The problem is that both and could be True, leading to infinite recursion. This happens in my branch for , but probably an example could be found for master too. We need a more robust way to canonicalize this. Ideally we'd want to remove the minus sign from the highest order term. Is there a fast way to do that?", "positive_passages": [{"docid": "doc-en-sympy__sympy-17010-d7129d876b2bf99805d0e6d25fc02d1b8b3dd326bc39bc3435faf776592feac4", "text": " elif x == S.Infinity: return S.NegativeOne**n * S.Infinity else: # n is a given fixed integer, evaluate into polynomial if n.is_negative: raise ValueError( \"The index n must be nonnegative integer (got %r)\" % n) return exp(x)*laguerre(-n - 1, -x) else: return cls._eval_at_order(n, x) ", "commid": "sympy__sympy-17010"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-17010-3128aeaa1eae457436e159fd4ffb7071c44e21f111f054c97af9caef3dc02310", "query": "Some uses of couldextractminussign can lead to infinite recursion The issue coming from was fixed, but there is another issue has come up in my pull request Several places in use couldextractminussign() in a way that can lead to infinite recursion. For example, in : The problem is that both and could be True, leading to infinite recursion. This happens in my branch for , but probably an example could be found for master too. We need a more robust way to canonicalize this. Ideally we'd want to remove the minus sign from the highest order term. Is there a fast way to do that?", "positive_passages": [{"docid": "doc-en-sympy__sympy-17010-d34bfb7845d2e2187e93626be482897ba25da7341188111951e0cbad729a0632", "text": " def _eval_rewrite_as_polynomial(self, n, x, **kwargs): from sympy import Sum # Make sure n \\in N_0 if n.is_negative or n.is_integer is False: raise ValueError(\"Error: n should be a non-negative integer.\") if n.is_negative: return exp(x) * self._eval_rewrite_as_polynomial(-n - 1, -x, **kwargs) if n.is_integer is False: raise ValueError(\"Error: n should be an integer.\") k = Dummy(\"k\") kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k return Sum(kern, (k, 0, n))", "commid": "sympy__sympy-17010"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-17010-3128aeaa1eae457436e159fd4ffb7071c44e21f111f054c97af9caef3dc02310", "query": "Some uses of couldextractminussign can lead to infinite recursion The issue coming from was fixed, but there is another issue has come up in my pull request Several places in use couldextractminussign() in a way that can lead to infinite recursion. For example, in : The problem is that both and could be True, leading to infinite recursion. This happens in my branch for , but probably an example could be found for master too. We need a more robust way to canonicalize this. Ideally we'd want to remove the minus sign from the highest order term. Is there a fast way to do that?", "positive_passages": [{"docid": "doc-en-sympy__sympy-17010-2b1646043891e4bb6c5505ae6974d20fc9df4608a48582af0feebd0c328dd792", "text": " References ========== .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Assoc_laguerre_polynomials .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Generalized_Laguerre_polynomials .. [2] http://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html .. [3] http://functions.wolfram.com/Polynomials/LaguerreL/ .. [4] http://functions.wolfram.com/Polynomials/LaguerreL3/", "commid": "sympy__sympy-17010"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-17022-8442443fcaa2e26f5cbdd0fd9351cfa42be26a5904afd9e1af26b6d16584b415", "query": "Lambdify misinterprets some matrix expressions Using lambdify on an expression containing an identity matrix gives us an unexpected result: Instead, the output should be , since we're adding an identity matrix to the array. Inspecting the globals and source code of shows us why we get the result: The code printer prints , which is currently being interpreted as a Python built-in complex number. The printer should support printing identity matrices, and signal an error for unsupported expressions that might be misinterpreted.", "positive_passages": [{"docid": "doc-en-sympy__sympy-17022-da013ad1412f3fbbba4e2240911c017c5bd6b5e019ceed179af1fa65487709cd", "text": " func = self._module_format('numpy.array') return \"%s(%s)\" % (func, self._print(expr.tolist())) def _print_Identity(self, expr): shape = expr.shape if all([dim.is_Integer for dim in shape]): return \"%s(%s)\" % (self._module_format('numpy.eye'), self._print(expr.shape[0])) else: raise NotImplementedError(\"Symbolic matrix dimensions are not yet supported for identity matrices\") def _print_BlockMatrix(self, expr): return '{0}({1})'.format(self._module_format('numpy.block'), self._print(expr.args[0].tolist()))", "commid": "sympy__sympy-17022"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-17038-df129f2783061ab64f451171fbfd2ddaa01295a3ad007ff2051544044a21ada7", "query": "isqrt gives incorrect results The function in gives incorrect results for some inputs. For example: or Versions: Python 3.7.3, SymPy 1.4, macOS 10.14.5 For small values of , the uses (aliased to ): The main problem is that the bound used for here is much too large, at almost . If (and it's quite a big if) we can assume that Python floats are IEEE 754 binary64 format and that supplies a correctly-rounded (using round-ties-to-even) square root function, then the largest bound that can safely be used here is , or . If we can assume IEEE 754 binary64 s but can't assume a correctly-rounded , then is still safe for smallish , where the definition of \"smallish\" depends on how accurate is. For example, if is known to be accurate to within 2 ulps, then it's possible to show that is safe for . (The is necessary here: wouldn't be safe even for tiny , since e.g. if the result of is off by a single ulp downwards, would produce instead of .) Whether is correctly rounded or not will depend on the platform: Python's just wraps the function from C's math library. On modern x64 hardware, one would expect and hope that C's gets mapped to the appropriate SSE2 instruction, in which case it'll be correctly rounded. But on ARM there may well not be a hardware sqrt instruction to map to, and a hand-implemented libm sqrt could easily be incorrectly rounded for some inputs. In the unlikely (but possible) case of non-IEEE 754 binary64 s, it's probably safer to avoid using at all. But this case is likely to be exceedingly rare, and doesn't seem worth worrying about in practice. I guess one option for fixing this while retaining performance for small would be to continue to use the code, but then to check the result is correct before returning it, falling back to the slow integer-only path if that check doesn't pass.", "positive_passages": [{"docid": "doc-en-sympy__sympy-17038-e48f20b4d775da3efc943a634ca455407615b344d328b3586d2ab145719c34dd", "text": " def isqrt(n): \"\"\"Return the largest integer less than or equal to sqrt(n).\"\"\" if n < 17984395633462800708566937239552: return int(_sqrt(n)) return integer_nthroot(int(n), 2)[0] if n < 0: raise ValueError(\"n must be nonnegative\") n = int(n) # Fast path: with IEEE 754 binary64 floats and a correctly-rounded # math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n < # 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either # IEEE 754 format floats *or* correct rounding of math.sqrt, so check the # answer and fall back to the slow method if necessary. if n < 4503599761588224: s = int(_sqrt(n)) if 0 <= n - s*s <= 2*s: return s return integer_nthroot(n, 2)[0] def integer_nthroot(y, n):", "commid": "sympy__sympy-17038"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-17067-b682fd4385e0394a5c2083137d8d4d18363fd2e4683fb48e1fc6058e70c74f27", "query": "Simplify returns incorrect result with trig functions %0A%23--%0Aexpr%20%3D%20(-sin(beta%2F2)sin(alpha%2F2%20-%20gamma%2F2)sin(alpha%2F2%20%2B%20gamma%2F2)%2F(2cos(beta%2F2)cos(alpha%2F2%20%2B%20gamma%2F2)2)%20%2B%20sin(beta%2F2)cos(alpha%2F2%20-%20gamma%2F2)%2F(2cos(beta%2F2)cos(alpha%2F2%20%2B%20gamma%2F2)))%2F(sin(alpha%2F2%20%2B%20gamma%2F2)2%2Fcos(alpha%2F2%20%2B%20gamma%2F2)2%20%2B%201)%20%2B%20(sin(alpha%2F2%20-%20gamma%2F2)sin(alpha%2F2%20%2B%20gamma%2F2)cos(beta%2F2)%2F(2sin(beta%2F2)cos(alpha%2F2%20-%20gamma%2F2)2)%20-%20cos(beta%2F2)cos(alpha%2F2%20%2B%20gamma%2F2)%2F(2sin(beta%2F2)cos(alpha%2F2%20-%20gamma%2F2)))%2F(sin(alpha%2F2%20-%20gamma%2F2)2%2Fcos(alpha%2F2%20-%20gamma%2F2)2%20%2B%201)%0A%23--%0Aprint(mathematicacode(expr))%0A%23--%0A%23%20Using%20Mathematica%20to%20Simplify%20that%20output%20results%20in%20-Cos%5Balpha%5DCot%5Bbeta%5D%0A%23--%0A%23%20That%20is%20also%20the%20result%20that%20one%20can%20get%20using%20basic%20trig%20identities%0A%23--%0Aexpr%0A%23--%0Asimplify(expr)%0A%23--%0A%23%20That%20is%20the%20incorrect%20result%0A%23--%0A]) shows an incorrect result when applying to a fairly large (but ultimately basic) expression involving lots of trig functions. I get the same result on version 1.4 on my own computer, and was getting this result from 1.3 before I updated today. EDIT: Note that Ethan reduced this to a much simpler expression below, so that's obviously a better MWE. I'm sorry that I haven't been able to cut it down to smaller size and still get an error; I have tried. The MWE is this: The output is [which could be further simplified to ]. It should be as verified by Mathematica (directly using the output of ), and by direct calculation using trig identities. This isn't just a matter of refusing to do something that may not always be true; this is really the wrong result. The expression looks big and ugly, but is actually pretty simple when you stare at it for a minute: \"Screen def f(rv): def f(rv, first=True): if not rv.is_Mul: return rv if first: n, d = rv.as_numer_denom() return f(n, 0)/f(d, 0) args = defaultdict(list) coss = {}", "commid": "sympy__sympy-17067"}], "negative_passages": []} {"query_id": "q-en-sympy__sympy-17115-5cb88b296211c748593a7e18fc4d800104d4803d8dcaf997c34e69ed084a4db5", "query": "Piecewise doesn't works correctly