Question: Re-opening : hexadecimal default arguments are changed to decimal I am experiencing the exact same problem as described in : hexadecimal default arguments are changed to decimal. Autodoc the following function: HTML result looks like this Hexadecimal defaults should not be converted to decimal, or at least there should be an option to enforce this behaviour. I'm afraid this is private No response Linux Ubuntu 20.04 10 0 autodoc, intersphinx, napoleon Chromium 94 No response

for i, param in enumerate(parameters):                 if param.default is not param.empty:                     if param.kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD):                        value = DefaultValue(ast_unparse(defaults.pop(0)))  # type: ignore                        parameters[i] = param.replace(default=value)                        default = defaults.pop(0)                        value = get_default_value(lines, default)                        if value is None:                            value = ast_unparse(default)  # type: ignore                        parameters[i] = param.replace(default=DefaultValue(value))                     else:                        value = DefaultValue(ast_unparse(kw_defaults.pop(0)))  # type: ignore                        parameters[i] = param.replace(default=value)                        default = kw_defaults.pop(0)                        value = get_default_value(lines, default)                        if value is None:                            value = ast_unparse(default)  # type: ignore                        parameters[i] = param.replace(default=DefaultValue(value))             sig = sig.replace(parameters=parameters)             obj.__signature__ = sig     except (AttributeError, TypeError):


Question: Support for fuzzy translations Problem Entries in po files that are currently marked as "fuzzy" are not used in "mo" files. The original source language is used instead of the translated language. Fuzzy translations are translations that in general need to be reviewed by a translator. For example all machine translations could be marked as fuzzy. It would be desirable to let the user decide whether to include these fuzzy translations in the generated documentation. Proposed solution Add a new configuration parameter "usefuzzytranslations". Change in line 72 of the file writemo(filemo, po) to writemo(filemo, po, usefuzzytranslations) Writing mo files with fuzzy translations is supported by the babel package, as can be seen in the documentation:

self.config.language, self.config.source_encoding)             for catalog in repo.catalogs:                 if catalog.domain == 'sphinx' and catalog.is_outdated():                    catalog.write_mo(self.config.language)                    catalog.write_mo(self.config.language,                                     self.config.gettext_allow_fuzzy_translations)              locale_dirs: List[Optional[str]] = list(repo.locale_dirs)             locale_dirs += [None]diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py-- a/sphinx/builders/__init__.py++ b/sphinx/builders/__init__.py


Question: Support for fuzzy translations Problem Entries in po files that are currently marked as "fuzzy" are not used in "mo" files. The original source language is used instead of the translated language. Fuzzy translations are translations that in general need to be reviewed by a translator. For example all machine translations could be marked as fuzzy. It would be desirable to let the user decide whether to include these fuzzy translations in the generated documentation. Proposed solution Add a new configuration parameter "usefuzzytranslations". Change in line 72 of the file writemo(filemo, po) to writemo(filemo, po, usefuzzytranslations) Writing mo files with fuzzy translations is supported by the babel package, as can be seen in the documentation:

for catalog in status_iterator(catalogs, __('writing output... '), "darkgreen",                                        len(catalogs), self.app.verbosity,                                        stringify_func=cat2relpath):            catalog.write_mo(self.config.language)            catalog.write_mo(self.config.language,                             self.config.gettext_allow_fuzzy_translations)      def compile_all_catalogs(self) -> None:         repo = CatalogRepository(self.srcdir, self.config.locale_dirs,diff --git a/sphinx/config.py b/sphinx/config.py-- a/sphinx/config.py++ b/sphinx/config.py


Question: Support for fuzzy translations Problem Entries in po files that are currently marked as "fuzzy" are not used in "mo" files. The original source language is used instead of the translated language. Fuzzy translations are translations that in general need to be reviewed by a translator. For example all machine translations could be marked as fuzzy. It would be desirable to let the user decide whether to include these fuzzy translations in the generated documentation. Proposed solution Add a new configuration parameter "usefuzzytranslations". Change in line 72 of the file writemo(filemo, po) to writemo(filemo, po, usefuzzytranslations) Writing mo files with fuzzy translations is supported by the babel package, as can be seen in the documentation:

'language': (None, 'env', [str]),         'locale_dirs': (['locales'], 'env', []),         'figure_language_filename': ('{root}.{language}{ext}', 'env', [str]),        'gettext_allow_fuzzy_translations': (False, 'gettext', []),          'master_doc': ('index', 'env', []),         'root_doc': (lambda config: config.master_doc, 'env', []),diff --git a/sphinx/util/i18n.py b/sphinx/util/i18n.py-- a/sphinx/util/i18n.py++ b/sphinx/util/i18n.py


Question: Support for fuzzy translations Problem Entries in po files that are currently marked as "fuzzy" are not used in "mo" files. The original source language is used instead of the translated language. Fuzzy translations are translations that in general need to be reviewed by a translator. For example all machine translations could be marked as fuzzy. It would be desirable to let the user decide whether to include these fuzzy translations in the generated documentation. Proposed solution Add a new configuration parameter "usefuzzytranslations". Change in line 72 of the file writemo(filemo, po) to writemo(filemo, po, usefuzzytranslations) Writing mo files with fuzzy translations is supported by the babel package, as can be seen in the documentation:

not path.exists(self.mo_path) or             path.getmtime(self.mo_path) < path.getmtime(self.po_path))     def write_mo(self, locale: str) -> None:    def write_mo(self, locale: str, use_fuzzy: bool = False) -> None:         with open(self.po_path, encoding=self.charset) as file_po:             try:                 po = read_po(file_po, locale)


Question: Support for fuzzy translations Problem Entries in po files that are currently marked as "fuzzy" are not used in "mo" files. The original source language is used instead of the translated language. Fuzzy translations are translations that in general need to be reviewed by a translator. For example all machine translations could be marked as fuzzy. It would be desirable to let the user decide whether to include these fuzzy translations in the generated documentation. Proposed solution Add a new configuration parameter "usefuzzytranslations". Change in line 72 of the file writemo(filemo, po) to writemo(filemo, po, usefuzzytranslations) Writing mo files with fuzzy translations is supported by the babel package, as can be seen in the documentation:

with open(self.mo_path, 'wb') as file_mo:             try:                write_mo(file_mo, po)                write_mo(file_mo, po, use_fuzzy)             except Exception as exc:                 logger.warning(__('writing error: %s, %s'), self.mo_path, exc)


Question: Add a way to defer loading of MathJax Is your feature request related to a problem? Please describe. It is quite tricky to configure MathJax to work with Sphinx currently. Sphinx loads MathJax asynchronously since and While this was fine for MathJax 2, because of the special kind of blocks mentioned in , it doesn't work well with MathJax 3. Indeed, in MathJax 3, MathJax expect a config block to be present before MathJax is loaded. Sphinx 4 parameter: This assumes that the is a simple dictionary, which isn't sufficient: that configuration should be able to contain functions, for example. The only possibility at the moment is to add a separate script file containing a MathJax configuration and to load it with. Describe the solution you'd like There are three possibilities: Allow arbitrary strings for mathjax3config, and in that case don't JSON-serialize them. Change to when loading MathJax. Make it possible for users to change to themselves. At the moment this isn't possible because the flags is unconditionally : The latter two are preferable because they would allow individual pages to use different MathJax config by using a block to override the default MathJax configuration on a given page (the script in that defer` option). CC , the author of . Thanks!

domain = cast(MathDomain, app.env.get_domain('math'))     if app.registry.html_assets_policy == 'always' or domain.has_equations(pagename):         # Enable mathjax only if equations exists        options = {'async': 'async'}        options = {'defer': 'defer'}         if app.config.mathjax_options:             options.update(app.config.mathjax_options)         app.add_js_file(app.config.mathjax_path, **options)  # type: ignore


Question: .. py:data:: :type: option does not correctly link to type supplied when using the .. py:data:: directive there is the :type: option to specify the type for the data being stored in the module level attribute. It does not work within the context of the module. What I mean by that is I have to key out the entire module path and the class for the type instead of importing the type into the module and only having to type in the type class name. say I have the following in the module "mylibrary.module1" The output I get when building the docs is this. and "Unit" is not a clickable link. However if I have the following in the module "mylibrary.module1" I get this for an output and "mylibrary.module2.Unit" is a clickable link that brings up the documentation for the Unit class to be able to do the following and have the output be and "Unit" be a clickable link that leads to the class that is specified in :type: No response Windows 8 2 No response No response

deprecated: bool  def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xref:def type_to_xref(target: str, env: BuildEnvironment = None) -> addnodes.pending_xref:     """Convert a type string to a cross reference node."""    if text == 'None':    if target == 'None':         reftype = 'obj'     else:         reftype = 'class'


Question: .. py:data:: :type: option does not correctly link to type supplied when using the .. py:data:: directive there is the :type: option to specify the type for the data being stored in the module level attribute. It does not work within the context of the module. What I mean by that is I have to key out the entire module path and the class for the type instead of importing the type into the module and only having to type in the type class name. say I have the following in the module "mylibrary.module1" The output I get when building the docs is this. and "Unit" is not a clickable link. However if I have the following in the module "mylibrary.module1" I get this for an output and "mylibrary.module2.Unit" is a clickable link that brings up the documentation for the Unit class to be able to do the following and have the output be and "Unit" be a clickable link that leads to the class that is specified in :type: No response Windows 8 2 No response No response

else:         kwargs = {} <ins>    refspecific = False    if target.startswith('.'):        target = target[1:]        text = target        refspecific = True    elif target.startswith('~'):        target = target[1:]        text = target.split('.')[-1]    else:        text = target</ins>     if env.config.python_use_unqualified_type_names:         # Note: It would be better to use qualname to describe the object to support support         # nested classes.  But python domain can't access the real python object because this


Question: .. py:data:: :type: option does not correctly link to type supplied when using the .. py:data:: directive there is the :type: option to specify the type for the data being stored in the module level attribute. It does not work within the context of the module. What I mean by that is I have to key out the entire module path and the class for the type instead of importing the type into the module and only having to type in the type class name. say I have the following in the module "mylibrary.module1" The output I get when building the docs is this. and "Unit" is not a clickable link. However if I have the following in the module "mylibrary.module1" I get this for an output and "mylibrary.module2.Unit" is a clickable link that brings up the documentation for the Unit class to be able to do the following and have the output be and "Unit" be a clickable link that leads to the class that is specified in :type: No response Windows 8 2 No response No response

contnodes = [nodes.Text(text)]      return pending_xref('', *contnodes,                        refdomain='py', reftype=reftype, reftarget=text, **kwargs)                        refdomain='py', reftype=reftype, reftarget=target,                        refspecific=refspecific, **kwargs)   def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Node]:


Question: Different build warnings are colored differently Some types of warnings seem to be different colors than others. An image warning is light red, a transition warning is dark red. This behavior exists regardless of being set. Use the branch specified. I purposely broke an image's path to showcase the differently-colored warning so it's not on main or develop. Based on , I'd expect all warnings to have the same color, and to not match the color of errors. ! macOS 10.15.7 (Catalina) 7 Sphinx v4.1.2 No response No response No response

class SphinxWarningLogRecord(SphinxLogRecord):     """Warning log record class supporting location"""    prefix = 'WARNING: '    @property    def prefix(self) -> str:  # type: ignore        if self.levelno >= logging.CRITICAL:            return 'CRITICAL: '        elif self.levelno >= logging.ERROR:            return 'ERROR: '        else:            return 'WARNING: '   class SphinxLoggerAdapter(logging.LoggerAdapter):


Question: Using position-only parameter syntax in prevents docstrings for attributes from being parsed I'm currently using in most of my functions, including , however this prevents inline, before, and after doc strings from being parsed. Once is open, you will see that only has the property documented. Both classes should have the property documented <img width="636" alt="image" src="https://user-"macOS 11.6.1 10 1 , No response No response

"""Returns the name of the first argument if in a function."""         if self.current_function and self.current_function.args.args:             return self.current_function.args.args[0]<ins>        elif (self.current_function and              getattr(self.current_function.args, 'posonlyargs', None)):            # for py38+            return self.current_function.args.posonlyargs[0]  # type: ignore</ins>         else:             return None


Question: Latex: terms are not separated by a newline I use simple indentations for terms and their explanation: Example: Which results in the following HTML output: Alabaster: ! RTD theme: ! While xelatex output does not contain a new line: ! Build the snippet. No response Build the snippet No response Linux 8 0 No response No response No response Latex: terms are not separated by a newline I use simple indentations for terms and their explanation: Example: Which results in the following HTML output: Alabaster: ! RTD theme: ! While xelatex output does not contain a new line: ! Build the snippet. No response Build the snippet No response Linux 8 0 No response No response No response LaTeX: glossary terms with common definition are rendered with too much vertical whitespace as in title and No response see code snippet ! Mac 0 2 Latex: terms are not separated by a newline I use simple indentations for terms and their explanation: Example: Which results in the following HTML output: Alabaster: ! RTD theme: ! While xelatex output does not contain a new line: ! Build the snippet. No response Build the snippet No response Linux 8 0 No response No response No response

ctx = r'\phantomsection'             for node_id in node['ids']:                 ctx += self.hypertarget(node_id, anchor=False)        ctx += r'}] \leavevmode'        self.body.append(r'\item[{')        ctx += r'}'        self.body.append(r'\sphinxlineitem{')         self.context.append(ctx)      def depart_term(self, node: Element) -> None:


Question: fps should print as a formal power series When I first used , I didn't realize it really was a formal power series as it claims to be, because it prints like a normal series (same as ) But if you look at the string form, you see That is, it really does represent it as the formula (albiet, not simplified). It out to print it like this, so you can see that that's what it's working with. Side question: if you enter something it can't compute, it just returns the function Is that intentional? It seems like it ought to raise an exception in that case.

return self._print_Add(s.truncate()) + self._print(' + \ldots')      def _print_FormalPowerSeries(self, s):        return self._print_Add(s.truncate())        return self._print_Add(s.infinite)      def _print_FiniteField(self, expr):         return r"\mathbb{F}_{%s}" % expr.moddiff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py


Question: fps should print as a formal power series When I first used , I didn't realize it really was a formal power series as it claims to be, because it prints like a normal series (same as ) But if you look at the string form, you see That is, it really does represent it as the formula (albiet, not simplified). It out to print it like this, so you can see that that's what it's working with. Side question: if you enter something it can't compute, it just returns the function Is that intentional? It seems like it ought to raise an exception in that case.

return self._print_Add(s.truncate()) + self._print(dots)      def _print_FormalPowerSeries(self, s):        return self._print_Add(s.truncate())        return self._print_Add(s.infinite)      def _print_SeqFormula(self, s):         if self._use_unicode:


Question: ccode(sinc(x)) doesn't work I don't think has , but it could print

else:             return name <ins>    def _print_Relational(self, expr):        lhs_code = self._print(expr.lhs)        rhs_code = self._print(expr.rhs)        op = expr.rel_op        return ("{0} {1} {2}").format(lhs_code, op, rhs_code)    def _print_sinc(self, expr):        from sympy.functions.elementary.trigonometric import sin        from sympy.core.relational import Ne        from sympy.functions import Piecewise        _piecewise = Piecewise(            (sin(expr.args[0]) / expr.args[0], Ne(expr.args[0], 0)), (1, True))        return self._print(_piecewise)</ins>     def _print_AugmentedAssignment(self, expr):         lhs_code = self._print(expr.lhs)         op = expr.rel_op


Question: diophantine: misclassification A check should be made that all powers are the same (not only that they are even).

diop_type = "cubic_thue"      elif (total_degree > 3 and total_degree % 2 == 0 and            all(k.is_Pow for k in coeff if k != 1)):            all(k.is_Pow and k.exp == total_degree for k in coeff if k != 1)):         if all(coeff[k] == 1 for k in coeff if k != 1):             diop_type = 'general_sum_of_even_powers'


Question: distance calculation wrong The 3rd dimension is being ignored when the Points are zipped together to calculate the distance so is being computed instead of .

sqrt(x**2 + y**2)          """<ins>        if type(p) is not type(self):            if len(p) == len(self):                return sqrt(sum([(a - b)**2 for a, b in zip(                    self.args, p.args if isinstance(p, Point) else p)]))            else:                p1 = [0] * max(len(p), len(self))                p2 = p.args if len(p.args) > len(self.args) else self.args                for i in range(min(len(p), len(self))):                    p1[i] = p.args[i] if len(p) < len(self) else self.args[i]                return sqrt(sum([(a - b)**2 for a, b in zip(                    p1, p2)]))</ins>         return sqrt(sum([(a - b)**2 for a, b in zip(             self.args, p.args if isinstance(p, Point) else p)]))


Question: nsolve wrong result Here's a plot of the function in question. As you can see, the root should be around 0.7. !

>>> cos(_)     0.73908513321516064165531208767387340401341175890076     mpmath.findroot is used, you can find there more extensive documentation,    especially concerning keyword parameters and available solvers. Note,    however, that this routine works only with the numerator of the function    in the one-dimensional case, and for very steep functions near the root    this may lead to a failure in the verification of the root. In this case    you should use the flag `verify=False` and independently verify the    solution.    mpmath.findroot is used and you can find there more extensive    documentation, especially concerning keyword parameters and    available solvers. Note, however, that functions which are very    steep near the root the verification of the solution may fail. In    this case you should use the flag `verify=False` and    independently verify the solution.      >>> from sympy import cos, cosh     >>> from sympy.abc import i


Question: nsolve wrong result Here's a plot of the function in question. As you can see, the root should be around 0.7. !

>>> bounds = lambda i: (3.14*i, 3.14*(i + 1))     >>> nsolve(f, bounds(100), solver='bisect', verify=False)     315.730061685774<ins>    Alternatively, a function may be better behaved when the    denominator is ignored. Since this is not always the case, however,    the decision of what function to use is left to the discretion of    the user.    >>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100    >>> nsolve(eq, 0.46)    Traceback (most recent call last):    ...    ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19)    Try another starting point or tweak arguments.    >>> nsolve(eq.as_numer_denom()[0], 0.46)    0.46792545969349058</ins>     """     # there are several other SymPy functions that use method= so     # guard against that here


Question: nsolve wrong result Here's a plot of the function in question. As you can see, the root should be around 0.7. !

expected a one-dimensional and numerical function'''))          # the function is much better behaved if there is no denominator        f = f.as_numer_denom()[0]        # but sending the numerator is left to the user since sometimes        # the function is better behaved when the denominator is present        # e.g., issue 11768          f = lambdify(fargs, f, modules)         return Float(findroot(f, x0, **kwargs))


Question: ASCII printing for Singularity Function. Implementation of ASCII printing for Singularity Functions is needed.

pform = base**n             return pform         else:            return self._print_Function(e)            n = self._print(e.args[2])            shift = self._print(e.args[0]-e.args[1])            base = self._print_seq(shift, "<", ">", ' ')            return base**n      def _print_gamma(self, e):         if self._use_unicode:


Question: Where oo belongs? (Concept) Hi again, well, i'm little confuse of the conditions to take or not in some sets: First the means the interval is created excluding and , and interval interpret it in that way, but now: Here is a little conflict, in first place Interval show don't take but now it is there? in some way is fine to have a way to can represent the from Interval. Now from this point we have some points: How they will interpret the limit concept? basically two options, limit is: or ? This point is very important, because define the behavior for sets, and affects directly like this issue: so, for now only to match the math in all sets we can say the limit is calculated via now, what is the effect of this in Sympy?, first this enable the limit concept in every unbounded set, for now i found this two issues: for example, actually we have this: this return should be something like... ? because in the limit we don't know what is the proportion of and , so we can't calc it. actually this concept is applied in some way like: Now the next question, will represent the infinite, as a integer, real or what? i know this question don't have sense, but let me try explain it: if the oo represent the infinite without form, it can exist in S.Naturals, and S.Reals, but if you represent the infinite like the interval between it, where is the limit of x to infinite while always , in other way where A go to and B do to , but it need always will respect this condition so between and can exist any type of numbers, so can't exist in because can contains a real number for example, but the extension of that concept says can't exist in any set, because always will exist a bigger set, in sympy you have an approximation of it, is , but don't will be true completely, because, why is it the limit set?, can represent two things, the limit of the actually human knowledge (or applied to Sympy), or the 'master' set, thinking its like the perfection of the sets knowledge. Obvs, to make some sense in the actual system the option is interpret without limit or form, and take the second interpretation of (if you take the first. can't exist in any place). If you disagree you always can discuss and change the behavior. Objetives of this issue: Get a clear definitions in Sympy of: Infinite Limit UniversalSet Then, clear the behavior of this concepts in Sympy, and to finish, set the behavior in Sympy. Thx. Cya.

if end == start and (left_open or right_open):             return S.EmptySet         if end == start and not (left_open or right_open):<ins>            if start == S.Infinity or start == S.NegativeInfinity:                return S.EmptySet</ins>             return FiniteSet(end)          # Make sure infinite interval end points are open.


Question: Union(FiniteSet(oo), S.Complexes) gives S.Complexes (should remain unevaluated) Hi, well searching i found this: i don't know with this where belongs, is part of Complexes or not? Thx. Cya.

"""         return self.sets._measure <ins>    @classmethod    def from_real(cls, sets):        """        Converts given subset of real numbers to a complex region.        Examples        ========        >>> from sympy import Interval, ComplexRegion        >>> unit = Interval(0,1)        >>> ComplexRegion.from_real(unit)        ComplexRegion([0, 1] x {0}, False)        """        if not sets.is_subset(S.Reals):            raise ValueError("sets must be a subset of the real line")        return cls(sets * FiniteSet(0))</ins>     def _contains(self, other):         from sympy.functions import arg, Abs         from sympy.core.containers import Tuple


Question: Union(FiniteSet(oo), S.Complexes) gives S.Complexes (should remain unevaluated) Hi, well searching i found this: i don't know with this where belongs, is part of Complexes or not? Thx. Cya.

return ComplexRegion(new_r_interval*new_theta_interval,                                     polar=True) <del>        if other is S.Reals:            return other</del>          if other.is_subset(S.Reals):             new_interval = []


Question: Union(FiniteSet(oo), S.Complexes) gives S.Complexes (should remain unevaluated) Hi, well searching i found this: i don't know with this where belongs, is part of Complexes or not? Thx. Cya.

def _union(self, other): <ins>        if other.is_subset(S.Reals):            # treat a subset of reals as a complex region            other = ComplexRegion.from_real(other)</ins>         if other.is_ComplexRegion:              # self in rectangular form


Question: Union(FiniteSet(oo), S.Complexes) gives S.Complexes (should remain unevaluated) Hi, well searching i found this: i don't know with this where belongs, is part of Complexes or not? Thx. Cya.

elif self.polar and other.polar:                 return ComplexRegion(Union(self.sets, other.sets), polar=True)         if self == S.Complexes:            return self         return None  diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py-- a/sympy/sets/sets.py++ b/sympy/sets/sets.py


Question: Union(FiniteSet(oo), S.Complexes) gives S.Complexes (should remain unevaluated) Hi, well searching i found this: i don't know with this where belongs, is part of Complexes or not? Thx. Cya.

for a, b in zip(self.sets, other.sets))      def _union(self, other):<ins>        if other.is_subset(self):            return self</ins>         if not other.is_ProductSet:             return None         if len(other.args) != len(self.args):


Question: Exception when printing Symbol('') It has something to do with the unicode pretty printer. works.

('var', ['sup'], ['sub1', 'sub2'])      """<ins>    if len(text) == 0:        return text, [], []</ins>     pos = 0     name = None     supers = []


Question: set intersection gives TypeError: object of type 'Naturals0' has no len() This is from Optimistically marking this as easy to fix (I could be wrong).

def __len__(self):         return Mul(*[len(s) for s in self.args]) <ins>    def __bool__(self):        return all([bool(s) for s in self.args])    __nonzero__ = __bool__</ins>  class Interval(Set, EvalfMixin):     """


Question: lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).

# don't change anything; this should already             # be a well formed mpf tuple             return mpf    rv = mpf_normalize(sign, man, expt, bc, prec, rnd)    # Necessary if mpmath is using the gmpy backend    from mpmath.libmp.backend import MPZ    rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd)     return rv  # TODO: we should use the warnings module


Question: lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).

elif num is S.NegativeInfinity:             num = '-inf'         elif isinstance(num, mpmath.mpf):<ins>            if prec == None:                prec = num.context.dps</ins>             num = num._mpf_          if prec is None:


Question: lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).

num[1] = long(num[1], 16)                 _mpf_ = tuple(num)             else:                if not num[1] and len(num) == 4:                if len(num) == 4:                     # handle normalization hack                     return Float._new(num, prec)                 else:                    _mpf_ = mpmath.mpf(                        S.NegativeOne**num[0]*num[1]*2**num[2])._mpf_                    return (S.NegativeOne**num[0]*num[1]*S(2)**num[2]).evalf(prec)         elif isinstance(num, Float):             _mpf_ = num._mpf_             if prec < num._prec:                 _mpf_ = mpf_norm(_mpf_, prec)         else:            # XXX: We lose precision here.             _mpf_ = mpmath.mpf(num)._mpf_          # special cases


Question: lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).

obj = Expr.__new__(cls)         obj._mpf_ = mpf_norm(_mpf_, _prec)        # XXX: Should this be obj._prec = obj._mpf_[3]?         obj._prec = _prec         return obj diff --git a/sympy/printing/lambdarepr.py b/sympy/printing/lambdarepr.py-- a/sympy/printing/lambdarepr.py++ b/sympy/printing/lambdarepr.py


Question: lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).

lstr = super(NumExprPrinter, self).doprint(expr)         return "evaluate('%s', truediv=True)" % lstr class MpmathPrinter(LambdaPrinter):    """    Lambda printer for mpmath which maintains precision for floats    """    def _print_Float(self, e):        # XXX: This does not handle setting mpmath.mp.dps. It is assumed that        # the caller of the lambdified function will have set it to sufficient        # precision to match the Floats in the expression.        # Remove 'mpz' if gmpy is installed.        args = str(tuple(map(int, e._mpf_)))        return 'mpf(%s)' % args def lambdarepr(expr, **settings):     """     Returns a string usable for lambdifying.diff --git a/sympy/solvers/solvers.py b/sympy/solvers/solvers.py-- a/sympy/solvers/solvers.py++ b/sympy/solvers/solvers.py


Question: lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).

# assume it's a sympy expression         if isinstance(f, Equality):             f = f.lhs - f.rhs        f = f.evalf()         syms = f.free_symbols         if fargs is None:             fargs = syms.copy().pop()diff --git a/sympy/utilities/decorator.py b/sympy/utilities/decorator.py-- a/sympy/utilities/decorator.py++ b/sympy/utilities/decorator.py


Question: lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).

import functools     import mpmath     def func_wrapper():    def func_wrapper(*args, **kwargs):         dps = mpmath.mp.dps         try:            func()            return func(*args, **kwargs)         finally:             mpmath.mp.dps = dps diff --git a/sympy/utilities/lambdify.py b/sympy/utilities/lambdify.py-- a/sympy/utilities/lambdify.py++ b/sympy/utilities/lambdify.py


Question: lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).

for term in syms:             namespace.update({str(term): term})     if _module_present('mpmath',namespaces) and printer is None:        #XXX: This has to be done here because of circular imports        from sympy.printing.lambdarepr import MpmathPrinter as printer     if _module_present('numpy',namespaces) and printer is None:         #XXX: This has to be done here because of circular imports         from sympy.printing.lambdarepr import NumPyPrinter as printerdiff --git a/sympy/utilities/runtests.py b/sympy/utilities/runtests.py-- a/sympy/utilities/runtests.py++ b/sympy/utilities/runtests.py


Question: lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).

clear_cache()             self._count += 1             random.seed(self._seed)            pytestfile = ""            if "XFAIL" in gl:                pytestfile = inspect.getsourcefile(gl["XFAIL"])            pytestfile2 = ""            if "slow" in gl:                pytestfile2 = inspect.getsourcefile(gl["slow"])             disabled = gl.get("disabled", False)             if not disabled:                 # we need to filter only those functions that begin with 'test_'                # that are defined in the testing file or in the file where                # is defined the XFAIL decorator                funcs = [gl[f] for f in gl.keys() if f.startswith("test_") and                    (inspect.isfunction(gl[f]) or inspect.ismethod(gl[f])) and                    (inspect.getsourcefile(gl[f]) == filename or                     inspect.getsourcefile(gl[f]) == pytestfile or                     inspect.getsourcefile(gl[f]) == pytestfile2)]                # We have to be careful about decorated functions. As long as                # the decorator uses functools.wraps, we can detect it.                funcs = []                for f in gl:                    if (f.startswith("test_") and (inspect.isfunction(gl[f])                        or inspect.ismethod(gl[f]))):                        func = gl[f]                        # Handle multiple decorators                        while hasattr(func, '__wrapped__'):                            func = func.__wrapped__                        if inspect.getsourcefile(func) == filename:                            funcs.append(gl[f])                 if slow:                     funcs = [f for f in funcs if getattr(f, '_slow', False)]                 # Sorting of XFAILed functions isn't fixed yet :-(


Question: simplifying exponential -trig identities Ideally, this would yield . Is there a way to do this? As a corollary, it would be awesome if could yield . Thank you for your consideration!

from sympy.sets.sets import FiniteSet from sympy.utilities.iterables import numbered_symbols from sympy.core.compatibility import range<ins>from sympy.core.relational import Nefrom sympy.functions.elementary.piecewise import Piecewise</ins>  ############################################################################### ########################## TRIGONOMETRIC FUNCTIONS ############################


Question: simplifying exponential -trig identities Ideally, this would yield . Is there a way to do this? As a corollary, it would be awesome if could yield . Thank you for your consideration!

def _eval_rewrite_as_sec(self, arg):         return 1 / sec(arg - S.Pi / 2, evaluate=False) <ins>    def _eval_rewrite_as_sinc(self, arg):        return arg*sinc(arg)</ins>     def _eval_conjugate(self):         return self.func(self.args[0].conjugate())


Question: simplifying exponential -trig identities Ideally, this would yield . Is there a way to do this? As a corollary, it would be awesome if could yield . Thank you for your consideration!

return jn(0, arg)      def _eval_rewrite_as_sin(self, arg):        return sin(arg) / arg        return Piecewise((sin(arg)/arg, Ne(arg, 0)), (1, True))   ###############################################################################


Question: LaTeX printer inconsistent with pretty printer The LaTeX printer should always give the same output as the pretty printer, unless better output is possible from LaTeX. In some cases it is inconsistent. For instance: (I also don't think the assumptions should affect printing).

elif expr.is_Mul:             if not first and _coeff_isneg(expr):                 return True        if expr.is_Piecewise:            return True         if any([expr.has(x) for x in (Mod,)]):             return True         if (not last and            any([expr.has(x) for x in (Integral, Piecewise, Product, Sum)])):            any([expr.has(x) for x in (Integral, Product, Sum)])):             return True          return False


Question: diophantine doesn't find solutions for 2x2+y2-16 Diophantine returns the empty set but and are solutions. I suspect there is some issue with the solving of the elliptic case, as for example also doesn't return all solutions: it returns and but fails to find and

>>> diop_solve(x + 3*y - 4*z + w - 6)     (t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6)     >>> diop_solve(x**2 + y**2 - 5)    {(-1, 2), (1, 2)}    {(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)}      See Also     ========


Question: diophantine doesn't find solutions for 2x2+y2-16 Diophantine returns the empty set but and are solutions. I suspect there is some issue with the solving of the elliptic case, as for example also doesn't return all solutions: it returns and but fails to find and

This method is generalised for many variables, below.      '''<del></del>     solutions = []     for i in range(len(B)):         tot_x, tot_y = [], []


Question: diophantine doesn't find solutions for 2x2+y2-16 Diophantine returns the empty set but and are solutions. I suspect there is some issue with the solving of the elliptic case, as for example also doesn't return all solutions: it returns and but fails to find and

solns_pell = diop_DN(D, N)          if D < 0:            for solution in solns_pell:                s1 = P*Matrix([solution[0], solution[1]]) + Q                s2 = P*Matrix([-solution[0], solution[1]]) + Q                try:                    sol.add(tuple([as_int(_) for _ in s1]))                    sol.add(tuple([as_int(_) for _ in s2]))                except ValueError:                    pass            for x0, y0 in solns_pell:                for x in [-x0, x0]:                    for y in [-y0, y0]:                        s = P*Matrix([x, y]) + Q                        try:                            sol.add(tuple([as_int(_) for _ in s]))                        except ValueError:                            pass         else:             # In this case equation can be transformed into a Pell equation


Question: diophantine doesn't find solutions for 2x2+y2-16 Diophantine returns the empty set but and are solutions. I suspect there is some issue with the solving of the elliptic case, as for example also doesn't return all solutions: it returns and but fails to find and

if sols:                     for x, y in sols:                         sol.append((d*x, d*y))                        if D == -1:                            sol.append((d*y, d*x))             return sol      elif D == 0:


Question: diophantine doesn't find solutions for 2x2+y2-16 Diophantine returns the empty set but and are solutions. I suspect there is some issue with the solving of the elliptic case, as for example also doesn't return all solutions: it returns and but fails to find and

>>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35     {(2, 3), (4, 1)}     >>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25    {(3, 4)}    {(4, 3)}      References     ===========


Question: diophantine doesn't find solutions for 2x2+y2-16 Diophantine returns the empty set but and are solutions. I suspect there is some issue with the solving of the elliptic case, as for example also doesn't return all solutions: it returns and but fails to find and

m1 = m1 // b             s, _exact = integer_nthroot(m1, 2)             if _exact:                if a == b and r > s:                if a == b and r < s:                     r, s = s, r                 sols.add((int(r), int(s)))


Question: evalf does not call imp recursively Example from The code for this is in . It isn't calling evalf recursively on the return of .

func = getattr(mpmath, fname)         except (AttributeError, KeyError):             try:                return Float(self._imp_(*self.args), prec)                return Float(self._imp_(*[i.evalf(prec) for i in self.args]), prec)             except (AttributeError, TypeError, ValueError):                 return


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

else:                 return Derivative(self, self.args[argindex - 1], evaluate=False)         # See issue 4624 and issue 4719 and issue 5600        arg_dummy = Dummy('xi_%i' % argindex)        arg_dummy.dummy_index = hash(self.args[argindex - 1])        arg_dummy = Dummy('xi_%i' % argindex, dummy_index=hash(self.args[argindex - 1]))         new_args = [arg for arg in self.args]         new_args[argindex-1] = arg_dummy         return Subs(Derivative(self.func(*new_args), arg_dummy),


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

obj = None             else:                 if not is_symbol:                    new_v = Dummy('xi_%i' % i)                    new_v.dummy_index = hash(v)                    new_v = Dummy('xi_%i' % i, dummy_index=hash(v))                     expr = expr.xreplace({v: new_v})                     old_v = v                     v = new_vdiff --git a/sympy/core/symbol.py b/sympy/core/symbol.py-- a/sympy/core/symbol.py++ b/sympy/core/symbol.py


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

import string import re as _re<ins>import random</ins>   class Symbol(AtomicExpr, Boolean):


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

class Dummy(Symbol):    """Dummy symbols are each unique, identified by an internal count index:    """Dummy symbols are each unique, even if they have the same name:      >>> from sympy import Dummy     >>> bool(Dummy("x") == Dummy("x")) == True     False     If a name is not supplied then a string value of the count index will be    If a name is not supplied then a string value of an internal count will be     used. This is useful when a temporary variable is needed and the name     of the variable used in the expression is not important.


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

"""     # In the rare event that a Dummy object needs to be recreated, both the    # `name` and `dummy_index` should be passed.  This is used by `srepr` for    # example:    # >>> d1 = Dummy()    # >>> d2 = eval(srepr(d1))    # >>> d2 == d1    # True    #    # If a new session is started between `srepr` and `eval`, there is a very    # small chance that `d2` will be equal to a previously-created Dummy.     _count = 0    _dummyorder = {}    _prng = random.Random()      __slots__ = ['dummy_index']      is_Dummy = True     def __new__(cls, name=None, **assumptions):    def __new__(cls, name=None, dummy_index=None, **assumptions):        if dummy_index is not None:            assert name is not None, "If you specify a dummy_index, you must also provide a name"         if name is None:             name = "Dummy_" + str(Dummy._count)          cls._sanitize(assumptions, cls)         obj = Symbol.__xnew__(cls, name, **assumptions)         while dummy_index is None:            # The dummy_index that *we* generate will be a smallish positive            # integers (at least Codeprinter assumes this).  But we do not            # impose this if dummy_index was passed in.            dummy_index = Dummy._prng.randint(10**6, 10**7-1)            if dummy_index in Dummy._dummyorder:                dummy_index = None        # Store count but don't update it if we already made this Dummy        Dummy._dummyorder.setdefault(dummy_index, Dummy._count)        obj.dummy_index = dummy_index         Dummy._count += 1        obj.dummy_index = Dummy._count         return obj      def __getstate__(self):


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

@cacheit     def sort_key(self, order=None):        # some tests depend on order of creation of Dummys         return self.class_key(), (            2, (str(self), self.dummy_index)), S.One.sort_key(), S.One            2, (str(self), Dummy._dummyorder[self.dummy_index])), S.One.sort_key(), S.One      def _hashable_content(self):         return Symbol._hashable_content(self) + (self.dummy_index,)diff --git a/sympy/printing/repr.py b/sympy/printing/repr.py-- a/sympy/printing/repr.py++ b/sympy/printing/repr.py


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

def _print_Symbol(self, expr):         d = expr._assumptions.generator<ins>        # print the dummy_index like it was an assumption        if expr.is_Dummy:            d['dummy_index'] = expr.dummy_index</ins>         if d == {}:             return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name))         else:


Question: matematica code printer does not handle floats and derivatives correctly In its current state the mathematica code printer does not handle Derivative(func(vars), deriver) e.g. Derivative(f(t), t) yields Derivative(f(t), t) instead of D[f[t],t] Also floats with exponents are not handled correctly e.g. 1.0e-4 is not converted to 1.0^-4 This has an easy fix by adding the following lines to MCodePrinter: def printDerivative(self, expr): return "D[%s]" % (self.stringify(, ", ")) def printFloat(self, expr): res =str(expr) return res.replace('e','^')

def _print_Sum(self, expr):         return "Hold[Sum[" + ', '.join(self.doprint(a) for a in expr.args) + "]]" <ins>    def _print_Derivative(self, expr):        return "Hold[D[" + ', '.join(self.doprint(a) for a in expr.args) + "]]"</ins>  def mathematica_code(expr, **settings):     r"""Converts an expr to a string of the Wolfram Mathematica code


Question: Empty intersection should be UniversalSet It should be . See (settheory)#Nullary_intersection

args = flatten(args)          if len(args) == 0:            return S.EmptySet            return S.UniversalSet          # args can't be ordered for Partition see issue #9608         if 'Partition' not in [type(a).__name__ for a in args]:


Question: List of prime factors including multiplicity is missing The vast majority of the time when using prime factorization in algorithms I'm interested in a list of prime factors. E.g. for 24 it's . However sympy (to my knowledge) only provides which returns a dictionary. I always end up writing a helper function: factorlist = lambda fac: sum(([p] * fac[p] for p in sorted(fac)), []) It would be really nice if factorizations in this format were directly provided by sympy, either by an option to (e.g. ) or under a new function name entirely.

def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,              verbose=False, visual=None):              verbose=False, visual=None, multiple=False):     r"""     Given a positive integer ``n``, ``factorint(n)`` returns a dict containing     the prime factors of ``n`` as keys and their respective multiplicities


Question: List of prime factors including multiplicity is missing The vast majority of the time when using prime factorization in algorithms I'm interested in a list of prime factors. E.g. for 24 it's . However sympy (to my knowledge) only provides which returns a dictionary. I always end up writing a helper function: factorlist = lambda fac: sum(([p] * fac[p] for p in sorted(fac)), []) It would be really nice if factorizations in this format were directly provided by sympy, either by an option to (e.g. ) or under a new function name entirely.

>>> factorint(3*101**7, limit=5)     {3: 1, 101: 7} <ins>    List of Factors:    If ``multiple`` is set to ``True`` then a list containing the    prime factors including multiplicities is returned.    >>> factorint(24, multiple=True)    [2, 2, 2, 3]</ins>     Visual Factorization:      If ``visual`` is set to ``True``, then it will return a visual


Question: List of prime factors including multiplicity is missing The vast majority of the time when using prime factorization in algorithms I'm interested in a list of prime factors. E.g. for 24 it's . However sympy (to my knowledge) only provides which returns a dictionary. I always end up writing a helper function: factorlist = lambda fac: sum(([p] * fac[p] for p in sorted(fac)), []) It would be really nice if factorizations in this format were directly provided by sympy, either by an option to (e.g. ) or under a new function name entirely.

smoothness, smoothness_p, divisors      """<ins>    if multiple:        fac = factorint(n, limit=limit, use_trial=use_trial,                           use_rho=use_rho, use_pm1=use_pm1,                           verbose=verbose, visual=False, multiple=False)        factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S(1)/p]*(-1*fac[p])                               for p in sorted(fac)), [])        return factorlist</ins>     factordict = {}     if visual and not isinstance(n, Mul) and not isinstance(n, dict):         factordict = factorint(n, limit=limit, use_trial=use_trial,


Question: List of prime factors including multiplicity is missing The vast majority of the time when using prime factorization in algorithms I'm interested in a list of prime factors. E.g. for 24 it's . However sympy (to my knowledge) only provides which returns a dictionary. I always end up writing a helper function: factorlist = lambda fac: sum(([p] * fac[p] for p in sorted(fac)), []) It would be really nice if factorizations in this format were directly provided by sympy, either by an option to (e.g. ) or under a new function name entirely.

def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,              verbose=False, visual=None):              verbose=False, visual=None, multiple=False):     r"""     Given a Rational ``r``, ``factorrat(r)`` returns a dict containing     the prime factors of ``r`` as keys and their respective multiplicities


Question: List of prime factors including multiplicity is missing The vast majority of the time when using prime factorization in algorithms I'm interested in a list of prime factors. E.g. for 24 it's . However sympy (to my knowledge) only provides which returns a dictionary. I always end up writing a helper function: factorlist = lambda fac: sum(([p] * fac[p] for p in sorted(fac)), []) It would be really nice if factorizations in this format were directly provided by sympy, either by an option to (e.g. ) or under a new function name entirely.

- ``use_rho``: Toggle use of Pollard's rho method         - ``use_pm1``: Toggle use of Pollard's p-1 method         - ``verbose``: Toggle detailed printing of progress        - ``multiple``: Toggle returning a list of factors or dict         - ``visual``: Toggle product form of output     """     from collections import defaultdict    if multiple:        fac = factorrat(rat, limit=limit, use_trial=use_trial,                  use_rho=use_rho, use_pm1=use_pm1,                  verbose=verbose, visual=False,multiple=False)        factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S(1)/p]*(-1*fac[p])                               for p, _ in sorted(fac.items(),                                                        key=lambda elem: elem[0]                                                        if elem[1] > 0                                                        else 1/elem[0])), [])        return factorlist     f = factorint(rat.p, limit=limit, use_trial=use_trial,                   use_rho=use_rho, use_pm1=use_pm1,                   verbose=verbose).copy()


Question: b splines of degree 1? Looking at the spline_basis function: This seems to break while the following is fine: I can tweak in extra knots, i.e. placing them at (0.1,0.2, 10.1,10.2 in the example) but this is still not really giving the desired basis matrix. Or am I just missing something very obvious? I always generated knots for bspline basis matrix by taking the list of knots and:

new_args = []         n_intervals = len(b1.args)         if n_intervals != len(b2.args):            raise ValueError("Args of b1 and b2 are not equal")        new_args.append((c*b1.args[0].expr, b1.args[0].cond))        for i in range(1, n_intervals - 1):            new_args.append((                c*b1.args[i].expr + d*b2.args[i - 1].expr,                b1.args[i].cond            ))        new_args.append((d*b2.args[-2].expr, b2.args[-2].cond))        new_args.append(b2.args[-1])            # Args of b1 and b2 are not equal. Just combining the Piecewise without any fancy optimisation            p1 = piecewise_fold(c*b1)            p2 = piecewise_fold(d*b2)            # Search all Piecewise arguments except (0, True)            p2args = list(p2.args[:-1])            # This merging algorithm assume the conditions in p1 and p2 are sorted            for arg in p1.args[:-1]:                # Conditional of Piecewise are And objects                # the args of the And object is a tuple of two Relational objects                # the numerical value is in the .rhs of the Relational object                expr = arg.expr                cond = arg.cond                lower = cond.args[0].rhs                # Check p2 for matching conditions that can be merged                for i, arg2 in enumerate(p2args):                    expr2 = arg2.expr                    cond2 = arg2.cond                    lower_2 = cond2.args[0].rhs                    upper_2 = cond2.args[1].rhs                    if cond2 == cond:                        # Conditions match, join expressions                        expr += expr2                        # Remove matching element                        del p2args[i]                        # No need to check the rest                        break                    elif lower_2 < lower and upper_2 <= lower:                        # Check if arg2 condition smaller than arg1, add to new_args by itself (no match expected in p1)                        new_args.append(arg2)                        del p2args[i]                        break                # Checked all, add expr and cond                new_args.append((expr, cond))            # Add remaining items from p2args            new_args.extend(p2args)            # Add final (0, True)            new_args.append((0, True))        else:            new_args.append((c*b1.args[0].expr, b1.args[0].cond))            for i in range(1, n_intervals - 1):                new_args.append((                    c*b1.args[i].expr + d*b2.args[i - 1].expr,                    b1.args[i].cond                ))            new_args.append((d*b2.args[-2].expr, b2.args[-2].cond))            new_args.append(b2.args[-1])         rv = Piecewise(*new_args)      return rv.expand()  def bspline_basis(d, knots, n, x, close=True):def bspline_basis(d, knots, n, x):     """The `n`-th B-spline at `x` of degree `d` with knots.      B-Splines are piecewise polynomials of degree `d` [1]_.  They are defined on


Question: b splines of degree 1? Looking at the spline_basis function: This seems to break while the following is fine: I can tweak in extra knots, i.e. placing them at (0.1,0.2, 10.1,10.2 in the example) but this is still not really giving the desired basis matrix. Or am I just missing something very obvious? I always generated knots for bspline basis matrix by taking the list of knots and:

Here is an example of a cubic B-spline:          >>> bspline_basis(3, range(5), 0, x)        Piecewise((x**3/6, (x >= 0) & (x < 1)),        Piecewise((x**3/6, (x >= 0) & (x <= 1)),                   (-x**3/2 + 2*x**2 - 2*x + 2/3,                  (x >= 1) & (x < 2)),                  (x >= 1) & (x <= 2)),                   (x**3/2 - 4*x**2 + 10*x - 22/3,                  (x >= 2) & (x < 3)),                  (x >= 2) & (x <= 3)),                   (-x**3/6 + 2*x**2 - 8*x + 32/3,                   (x >= 3) & (x <= 4)),                   (0, True))


Question: b splines of degree 1? Looking at the spline_basis function: This seems to break while the following is fine: I can tweak in extra knots, i.e. placing them at (0.1,0.2, 10.1,10.2 in the example) but this is still not really giving the desired basis matrix. Or am I just missing something very obvious? I always generated knots for bspline basis matrix by taking the list of knots and:

raise ValueError('n + d + 1 must not exceed len(knots) - 1')     if d == 0:         result = Piecewise(            (S.One, Interval(knots[n], knots[n + 1], False,             not close).contains(x)),            (S.One, Interval(knots[n], knots[n + 1]).contains(x)),             (0, True)         )     elif d > 0:         denom = knots[n + d + 1] - knots[n + 1]         if denom != S.Zero:             B = (knots[n + d + 1] - x)/denom            b2 = bspline_basis(d - 1, knots, n + 1, x, close)            b2 = bspline_basis(d - 1, knots, n + 1, x)         else:             b2 = B = S.Zero          denom = knots[n + d] - knots[n]         if denom != S.Zero:             A = (x - knots[n])/denom            b1 = bspline_basis(                d - 1, knots, n, x, close and (B == S.Zero or b2 == S.Zero))            b1 = bspline_basis(d - 1, knots, n, x)         else:             b1 = A = S.Zero


Question: b splines of degree 1? Looking at the spline_basis function: This seems to break while the following is fine: I can tweak in extra knots, i.e. placing them at (0.1,0.2, 10.1,10.2 in the example) but this is still not really giving the desired basis matrix. Or am I just missing something very obvious? I always generated knots for bspline basis matrix by taking the list of knots and:

>>> knots = range(5)     >>> splines = bspline_basis_set(d, knots, x)     >>> splines    [Piecewise((x**2/2, (x >= 0) & (x < 1)),               (-x**2 + 3*x - 3/2, (x >= 1) & (x < 2)),    [Piecewise((x**2/2, (x >= 0) & (x <= 1)),               (-x**2 + 3*x - 3/2, (x >= 1) & (x <= 2)),                (x**2/2 - 3*x + 9/2, (x >= 2) & (x <= 3)),                (0, True)),    Piecewise((x**2/2 - x + 1/2, (x >= 1) & (x < 2)),              (-x**2 + 5*x - 11/2, (x >= 2) & (x < 3)),    Piecewise((x**2/2 - x + 1/2, (x >= 1) & (x <= 2)),              (-x**2 + 5*x - 11/2, (x >= 2) & (x <= 3)),               (x**2/2 - 4*x + 8, (x >= 3) & (x <= 4)),               (0, True))]


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

import decimal import fractions import math<ins>import warnings</ins> import re as regex from collections import defaultdict


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

from sympy.utilities.misc import debug, filldedent from .evaluate import global_evaluate <ins>from sympy.utilities.exceptions import SymPyDeprecationWarning</ins> rnd = mlib.round_nearest  _LOG2 = math.log(2)


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

is_Float = True     def __new__(cls, num, prec=None):    def __new__(cls, num, dps=None, prec=None, precision=None):        if prec is not None:            SymPyDeprecationWarning(                            feature="Using 'prec=XX' to denote decimal precision",                            useinstead="'dps=XX' to denote decimal and 'precision=XX' "\                                              "for binary precision",                            value="This is an effort to improve functionality "\                                       "of Float class. ").warn()            dps = prec        if dps is not None and precision is not None:            raise ValueError('Both decimal and binary precision supplied. '                             'Supply only one. ')         if isinstance(num, string_types):             num = num.replace(' ', '')             if num.startswith('.') and len(num) > 1:


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

elif num is S.NegativeInfinity:             num = '-inf'         elif isinstance(num, mpmath.mpf):            if prec == None:                prec = num.context.dps            if precision is None:                if dps is None:                    precision = num.context.prec             num = num._mpf_         if prec is None:        if dps is None and precision is None:             dps = 15             if isinstance(num, Float):                 return num


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

if num.is_Integer and isint:                         dps = max(dps, len(str(num).lstrip('-')))                     dps = max(15, dps)        elif prec == '':                    precision = mlib.libmpf.dps_to_prec(dps)        elif precision == '' and dps is None or precision is None and dps == '':             if not isinstance(num, string_types):                 raise ValueError('The null string can only be used when '                 'the number to Float is passed as a string or an integer.')


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

num, dps = _decimal_to_Rational_prec(Num)                     if num.is_Integer and isint:                         dps = max(dps, len(str(num).lstrip('-')))                        precision = mlib.libmpf.dps_to_prec(dps)                     ok = True             if ok is None:                 raise ValueError('string-float not recognized: %s' % num)        else:            dps = prec         prec = mlib.libmpf.dps_to_prec(dps)        # decimal precision(dps) is set and maybe binary precision(precision)        # as well.From here on binary precision is used to compute the Float.        # Hence, if supplied use binary precision else translate from decimal        # precision.        if precision is None or precision == '':            precision = mlib.libmpf.dps_to_prec(dps)         if isinstance(num, float):            _mpf_ = mlib.from_float(num, prec, rnd)            _mpf_ = mlib.from_float(num, precision, rnd)         elif isinstance(num, string_types):            _mpf_ = mlib.from_str(num, prec, rnd)            _mpf_ = mlib.from_str(num, precision, rnd)         elif isinstance(num, decimal.Decimal):             if num.is_finite():                _mpf_ = mlib.from_str(str(num), prec, rnd)                _mpf_ = mlib.from_str(str(num), precision, rnd)             elif num.is_nan():                 _mpf_ = _mpf_nan             elif num.is_infinite():


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

else:                 raise ValueError("unexpected decimal value %s" % str(num))         elif isinstance(num, Rational):            _mpf_ = mlib.from_rational(num.p, num.q, prec, rnd)            _mpf_ = mlib.from_rational(num.p, num.q, precision, rnd)         elif isinstance(num, tuple) and len(num) in (3, 4):             if type(num[1]) is str:                 # it's a hexadecimal (coming from a pickled object)


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

else:                 if len(num) == 4:                     # handle normalization hack                    return Float._new(num, prec)                    return Float._new(num, precision)                 else:                    return (S.NegativeOne**num[0]*num[1]*S(2)**num[2]).evalf(prec)                    return (S.NegativeOne**num[0]*num[1]*S(2)**num[2]).evalf(precision)         elif isinstance(num, Float):             _mpf_ = num._mpf_            if prec < num._prec:                _mpf_ = mpf_norm(_mpf_, prec)            if precision < num._prec:                _mpf_ = mpf_norm(_mpf_, precision)         else:             # XXX: We lose precision here.             _mpf_ = mpmath.mpf(num)._mpf_


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

obj = Expr.__new__(cls)         obj._mpf_ = _mpf_        obj._prec = prec        obj._prec = precision         return obj      @classmethoddiff --git a/sympy/printing/repr.py b/sympy/printing/repr.py-- a/sympy/printing/repr.py++ b/sympy/printing/repr.py


Question: Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.

return 'Fraction(%s, %s)' % (self._print(expr.numerator), self._print(expr.denominator))      def _print_Float(self, expr):        dps = prec_to_dps(expr._prec)         r = mlib.to_str(expr._mpf_, repr_dps(expr._prec))        return "%s('%s', prec=%i)" % (expr.__class__.__name__, r, dps)        return "%s('%s', precision=%i)" % (expr.__class__.__name__, r, expr._prec)      def _print_Sum2(self, expr):         return "Sum2(%s, (%s, %s, %s))" % (self._print(expr.f), self._print(expr.i),


Question: cannot extract_multiplicatively(-2) from (-2x - 2y) I think this might be a bug. similarly: Assuming it is indeed a bug, here is why it happens: Look in where: which is then made into a non-evaluated , from which cannot be multiplicatively extracted; for example: do you think this is bug? (see your commit : not clear whether we still need this special case anyway)

from collections import defaultdict <del></del> class Expr(Basic, EvalfMixin):     """     Base class for algebraic expressions.


Question: cannot extract_multiplicatively(-2) from (-2x - 2y) I think this might be a bug. similarly: Assuming it is indeed a bug, here is why it happens: Look in where: which is then made into a non-evaluated , from which cannot be multiplicatively extracted; for example: do you think this is bug? (see your commit : not clear whether we still need this special case anyway)

x/6          """<ins>        from .function import _coeff_isneg</ins>         c = sympify(c)         if self is S.NaN:             return None


Question: cannot extract_multiplicatively(-2) from (-2x - 2y) I think this might be a bug. similarly: Assuming it is indeed a bug, here is why it happens: Look in where: which is then made into a non-evaluated , from which cannot be multiplicatively extracted; for example: do you think this is bug? (see your commit : not clear whether we still need this special case anyway)

return self         elif c == self:             return S.One         if c.is_Add:             cc, pc = c.primitive()             if cc is not S.One:                 c = Mul(cc, pc, evaluate=False)         if c.is_Mul:             a, b = c.as_two_terms()             x = self.extract_multiplicatively(a)             if x is not None:                 return x.extract_multiplicatively(b)         quotient = self / c         if self.is_Number:             if self is S.Infinity:


Question: cannot extract_multiplicatively(-2) from (-2x - 2y) I think this might be a bug. similarly: Assuming it is indeed a bug, here is why it happens: Look in where: which is then made into a non-evaluated , from which cannot be multiplicatively extracted; for example: do you think this is bug? (see your commit : not clear whether we still need this special case anyway)

return quotient         elif self.is_Add:             cs, ps = self.primitive()            if cs is not S.One:                return Mul(cs, ps, evaluate=False).extract_multiplicatively(c)            # assert cs >= 1            if c.is_Number and c is not S.NegativeOne:                # assert c != 1 (handled at top)                if cs is not S.One:                    if c.is_negative:                        xc = -(cs.extract_multiplicatively(-c))                    else:                        xc = cs.extract_multiplicatively(c)                    if xc is not None:                        return xc*ps  # rely on 2-arg Mul to restore Add                return  # |c| != 1 can only be extracted from cs            if c == ps:                return cs            # check args of ps             newargs = []            for arg in self.args:            for arg in ps.args:                 newarg = arg.extract_multiplicatively(c)                if newarg is not None:                    newargs.append(newarg)                else:                    return None            return Add(*newargs)                if newarg is None:                    return  # all or nothing                newargs.append(newarg)            # args should be in same order so use unevaluated return            if cs is not S.One:                return Add._from_args([cs*t for t in newargs])            else:                return Add._from_args(newargs)         elif self.is_Mul:             args = list(self.args)             for i, arg in enumerate(args):


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

else:                 return Derivative(self, self.args[argindex - 1], evaluate=False)         # See issue 4624 and issue 4719 and issue 5600        arg_dummy = Dummy('xi_%i' % argindex)        arg_dummy.dummy_index = hash(self.args[argindex - 1])        arg_dummy = Dummy('xi_%i' % argindex, dummy_index=hash(self.args[argindex - 1]))         new_args = [arg for arg in self.args]         new_args[argindex-1] = arg_dummy         return Subs(Derivative(self.func(*new_args), arg_dummy),


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

obj = None             else:                 if not is_symbol:                    new_v = Dummy('xi_%i' % i)                    new_v.dummy_index = hash(v)                    new_v = Dummy('xi_%i' % i, dummy_index=hash(v))                     expr = expr.xreplace({v: new_v})                     old_v = v                     v = new_vdiff --git a/sympy/core/symbol.py b/sympy/core/symbol.py-- a/sympy/core/symbol.py++ b/sympy/core/symbol.py


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

import string import re as _re<ins>import random</ins>   class Symbol(AtomicExpr, Boolean):


Question: Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.

class Dummy(Symbol):    """Dummy symbols are each unique, identified by an internal count index:    """Dummy symbols are each unique, even if they have the same name:      >>> from sympy import Dummy    >>> bool(Dummy("x") == Dummy("x")) == True    >>> Dummy("x") == Dummy("x")     False     If a name is not supplied then a string value of the count index will be    If a name is not supplied then a string value of an internal count will be     used. This is useful when a temporary variable is needed and the name     of the variable used in the expression is not important.