Repository: sympy/sympy

Issue:
TypeError: __new__() missing 1 required positional argument: 'cond' from solve
From https://stackoverflow.com/questions/36286862/polynomial-function-cannot-be-solved-by-python-sympy

```
In [4]:  def function(omega):
   ...:         return - 0.34*omega**4      \
   ...:                + 7.44*omega**3      \
   ...:                + 4.51*I*omega**3    \
   ...:                + 87705.64*omega**2  \
   ...:                - 53.08*I*omega**2   \
   ...:                - 144140.03*omega    \
   ...:                - 22959.95*I*omega   \
   ...:                + 42357.18 + 50317.77*I
    ...:  sympy.solve(function(omega), omega)
   ...:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-d35936482468> in <module>()
      1 def function(omega):
      2        return - 0.34*omega**4                    + 7.44*omega**3                    + 4.51*I*omega**3                  + 87705.64*omega**2                - 53.08*I*omega**2                 - 144140.03*omega                  - 22959.95*I*omega                 + 42357.18 + 50317.77*I
----> 3 sympy.solve(function(omega), omega)
      4

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/solvers/solvers.py in solve(f, *symbols, **flags)
   1123     # restore floats
   1124     if floats and solution and flags.get('rational', None) is None:
-> 1125         solution = nfloat(solution, exponent=False)
   1126
   1127     if check and solution:  # assumption checking

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/function.py in nfloat(expr, n, exponent)
   2466             return type(expr)([(k, nfloat(v, n, exponent)) for k, v in
   2467                                list(expr.items())])
-> 2468         return type(expr)([nfloat(a, n, exponent) for a in expr])
   2469     rv = sympify(expr)
   2470

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/function.py in <listcomp>(.0)
   2466             return type(expr)([(k, nfloat(v, n, exponent)) for k, v in
   2467                                list(expr.items())])
-> 2468         return type(expr)([nfloat(a, n, exponent) for a in expr])
   2469     rv = sympify(expr)
   2470

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/function.py in nfloat(expr, n, exponent)
   2500     return rv.xreplace(Transform(
   2501         lambda x: x.func(*nfloat(x.args, n, exponent)),
-> 2502         lambda x: isinstance(x, Function)))
   2503
   2504

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/basic.py in xreplace(self, rule)
   1091
   1092         """
-> 1093         value, _ = self._xreplace(rule)
   1094         return value
   1095

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/basic.py in _xreplace(self, rule)
   1099         """
   1100         if self in rule:
-> 1101             return rule[self], True
   1102         elif rule:
   1103             args = []

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/rules.py in __getitem__(self, key)
     57     def __getitem__(self, key):
     58         if self._filter(key):
---> 59             return self._transform(key)
     60         else:
     61             raise KeyError(key)

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/function.py in <lambda>(x)
   2499
   2500     return rv.xreplace(Transform(
-> 2501         lambda x: x.func(*nfloat(x.args, n, exponent)),
   2502         lambda x: isinstance(x, Function)))
   2503

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/function.py in nfloat(expr, n, exponent)
   2466             return type(expr)([(k, nfloat(v, n, exponent)) for k, v in
   2467                                list(expr.items())])
-> 2468         return type(expr)([nfloat(a, n, exponent) for a in expr])
   2469     rv = sympify(expr)
   2470

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/function.py in <listcomp>(.0)
   2466             return type(expr)([(k, nfloat(v, n, exponent)) for k, v in
   2467                                list(expr.items())])
-> 2468         return type(expr)([nfloat(a, n, exponent) for a in expr])
   2469     rv = sympify(expr)
   2470

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/function.py in nfloat(expr, n, exponent)
   2466             return type(expr)([(k, nfloat(v, n, exponent)) for k, v in
   2467                                list(expr.items())])
-> 2468         return type(expr)([nfloat(a, n, exponent) for a in expr])
   2469     rv = sympify(expr)
   2470

TypeError: __new__() missing 1 required positional argument: 'cond'
```


Discussion:
sympy-bot: :white_check_mark:

Hi, I am the [SymPy bot](https://github.com/sympy/sympy-bot) (v147). I'm here to help you write a release notes entry. Please read the [guide on how to write release notes](https://github.com/sympy/sympy/wiki/Writing-Release-Notes).



Your release notes are in good order.

Here is what the release notes will look like:
* core
  - nfloat handle containers better ([#16771](https://github.com/sympy/sympy/pull/16771) by [@smichr](https://github.com/smichr))

  - sympify handles containers better (e.g. will convert Float to Rational inside tuple and convert dict to Dict) ([#16771](https://github.com/sympy/sympy/pull/16771) by [@smichr](https://github.com/smichr))

This will be added to https://github.com/sympy/sympy/wiki/Release-Notes-for-1.5.

Note: This comment will be updated with the latest check if you edit the pull request. You need to reload the page to see it. <details><summary>Click here to see the pull request description that was parsed.</summary>

    <!-- Your title above should be a short description of what
    was changed. Do not include the issue number in the title. -->

    #### References to other Issues or PRs
    <!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact
    format, e.g. "Fixes #1234". See
    https://github.com/blog/1506-closing-issues-via-pull-requests . Please also
    write a comment on that issue linking back to this pull request once it is
    open. -->

    closes #10933
    closes #11708 as non-issue but improves handling of objects by sympify
    closes #16769

    #### Brief description of what is fixed or changed


    #### Other comments


    #### Release Notes

    <!-- Write the release notes for this release below. See
    https://github.com/sympy/sympy/wiki/Writing-Release-Notes for more information
    on how to write release notes. The bot will check your release notes
    automatically to see if they are formatted correctly. -->

    <!-- BEGIN RELEASE NOTES -->
    - core
        - nfloat handle containers better
        - sympify handles containers better (e.g. will convert Float to Rational inside tuple and convert dict to Dict)
    <!-- END RELEASE NOTES -->


</details><p>

smichr: ping @czgdp1807 

Patch:
diff --git a/sympy/core/evalf.py b/sympy/core/evalf.py
index 1104b4fd5a..ef053d6cee 100644
--- a/sympy/core/evalf.py
+++ b/sympy/core/evalf.py
@@ -1445,6 +1445,8 @@ def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None,
             v = self._eval_evalf(prec)
             if v is None:
                 return self
+            elif not v.is_number:
+                return v
             try:
                 # If the result is numerical, normalize it
                 result = evalf(v, prec, options)
diff --git a/sympy/core/function.py b/sympy/core/function.py
index 7497d58d60..5586c07035 100644
--- a/sympy/core/function.py
+++ b/sympy/core/function.py
@@ -3056,9 +3056,10 @@ def count_ops(expr, visual=False):
     return sum(int((a.args or [1])[0]) for a in Add.make_args(ops))
 
 
-def nfloat(expr, n=15, exponent=False):
+def nfloat(expr, n=15, exponent=False, dkeys=False):
     """Make all Rationals in expr Floats except those in exponents
-    (unless the exponents flag is set to True).
+    (unless the exponents flag is set to True). When processing
+    dictionaries, don't modify the keys unless ``dkeys=True``.
 
     Examples
     ========
@@ -3071,15 +3072,31 @@ def nfloat(expr, n=15, exponent=False):
     >>> nfloat(x**4 + sqrt(y), exponent=True)
     x**4.0 + y**0.5
 
+    Container types are not modified:
+
+    >>> type(nfloat((1, 2))) is tuple
+    True
     """
     from sympy.core.power import Pow
     from sympy.polys.rootoftools import RootOf
 
+    kw = dict(n=n, exponent=exponent, dkeys=dkeys)
+    # handling of iterable containers
     if iterable(expr, exclude=string_types):
         if isinstance(expr, (dict, Dict)):
-            return type(expr)([(k, nfloat(v, n, exponent)) for k, v in
-                               list(expr.items())])
-        return type(expr)([nfloat(a, n, exponent) for a in expr])
+            if dkeys:
+                args = [tuple(map(lambda i: nfloat(i, **kw), a))
+                    for a in expr.items()]
+            else:
+                args = [(k, nfloat(v, **kw)) for k, v in expr.items()]
+            if isinstance(expr, dict):
+                return type(expr)(args)
+            else:
+                return expr.func(*args)
+        elif isinstance(expr, Basic):
+            return expr.func(*[nfloat(a, **kw) for a in expr.args])
+        return type(expr)([nfloat(a, **kw) for a in expr])
+
     rv = sympify(expr)
 
     if rv.is_Number:
@@ -3092,6 +3109,8 @@ def nfloat(expr, n=15, exponent=False):
         else:
             pass  # pure_complex(rv) is likely True
         return rv
+    elif rv.is_Atom:
+        return rv
 
     # watch out for RootOf instances that don't like to have
     # their exponents replaced with Dummies and also sometimes have
diff --git a/sympy/printing/__init__.py b/sympy/printing/__init__.py
index 2b73f8359d..af94ce739f 100644
--- a/sympy/printing/__init__.py
+++ b/sympy/printing/__init__.py
@@ -5,8 +5,8 @@
 from .pretty import pager_print, pretty, pretty_print, pprint, pprint_use_unicode, pprint_try_use_unicode
 __all__ += ['pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode', 'pprint_try_use_unicode']
 
-from .latex import latex, print_latex, multiline_latex
-__all__ += ['latex', 'print_latex', 'multiline_latex']
+from .latex import latex, print_latex
+__all__ += ['latex', 'print_latex']
 
 from .mathml import mathml, print_mathml
 __all__ += ['mathml', 'print_mathml']
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index b3fc8eeb89..b1bb5c6ffd 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -2586,132 +2586,3 @@ def print_latex(expr, **settings):
     """Prints LaTeX representation of the given expression. Takes the same
     settings as ``latex()``."""
     print(latex(expr, **settings))
-
-
-def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings):
-    r"""
-    This function generates a LaTeX equation with a multiline right-hand side
-    in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment.
-
-    Parameters
-    ==========
-
-    lhs : Expr
-        Left-hand side of equation
-
-    rhs : Expr
-        Right-hand side of equation
-
-    terms_per_line : integer, optional
-        Number of terms per line to print. Default is 1.
-
-    environment : "string", optional
-        Which LaTeX wnvironment to use for the output. Options are "align*"
-        (default), "eqnarray", and "IEEEeqnarray".
-
-    use_dots : boolean, optional
-        If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``.
-
-    Examples
-    ========
-
-    >>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I
-    >>> x, y, alpha = symbols('x y alpha')
-    >>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y))
-    >>> print(multiline_latex(x, expr))
-    \begin{align*}
-    x = & e^{i \alpha} \\
-    & + \sin{\left(\alpha y \right)} \\
-    & - \cos{\left(\log{\left(y \right)} \right)}
-    \end{align*}
-
-    Using at most two terms per line:
-    >>> print(multiline_latex(x, expr, 2))
-    \begin{align*}
-    x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\
-    & - \cos{\left(\log{\left(y \right)} \right)}
-    \end{align*}
-
-    Using ``eqnarray`` and dots:
-    >>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True))
-    \begin{eqnarray}
-    x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\
-    & & - \cos{\left(\log{\left(y \right)} \right)}
-    \end{eqnarray}
-
-    Using ``IEEEeqnarray``:
-    >>> print(multiline_latex(x, expr, environment="IEEEeqnarray"))
-    \begin{IEEEeqnarray}{rCl}
-    x & = & e^{i \alpha} \nonumber\\
-    & & + \sin{\left(\alpha y \right)} \nonumber\\
-    & & - \cos{\left(\log{\left(y \right)} \right)}
-    \end{IEEEeqnarray}
-
-    Notes
-    =====
-
-    All optional parameters from ``latex`` can also be used.
-
-    """
-
-    # Based on code from https://github.com/sympy/sympy/issues/3001
-    l = LatexPrinter(**settings)
-    if environment == "eqnarray":
-        result = r'\begin{eqnarray}' + '\n'
-        first_term = '& = &'
-        nonumber = r'\nonumber'
-        end_term = '\n\\end{eqnarray}'
-        doubleet = True
-    elif environment == "IEEEeqnarray":
-        result = r'\begin{IEEEeqnarray}{rCl}' + '\n'
-        first_term = '& = &'
-        nonumber = r'\nonumber'
-        end_term = '\n\\end{IEEEeqnarray}'
-        doubleet = True
-    elif environment == "align*":
-        result = r'\begin{align*}' + '\n'
-        first_term = '= &'
-        nonumber = ''
-        end_term =  '\n\\end{align*}'
-        doubleet = False
-    else:
-        raise ValueError("Unknown environment: {}".format(environment))
-    dots = ''
-    if use_dots:
-        dots=r'\dots'
-    terms = rhs.as_ordered_terms()
-    n_terms = len(terms)
-    term_count = 1
-    for i in range(n_terms):
-        term = terms[i]
-        term_start = ''
-        term_end = ''
-        sign = '+'
-        if term_count > terms_per_line:
-            if doubleet:
-                term_start = '& & '
-            else:
-                term_start = '& '
-            term_count = 1
-        if term_count == terms_per_line:
-            # End of line
-            if i < n_terms-1:
-                # There are terms remaining
-                term_end = dots + nonumber + r'\\' + '\n'
-            else:
-                term_end = ''
-
-        if term.as_ordered_factors()[0] == -1:
-            term = -1*term
-            sign = r'-'
-        if i == 0: # beginning
-            if sign == '+':
-                sign = ''
-            result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs),
-                        first_term, sign, l.doprint(term), term_end)
-        else:
-            result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign,
-                        l.doprint(term), term_end)
-        term_count += 1
-    result += end_term
-    return result


Test patch:
diff --git a/sympy/core/tests/test_evalf.py b/sympy/core/tests/test_evalf.py
index 1d61bff3a3..4a837ed7d4 100644
--- a/sympy/core/tests/test_evalf.py
+++ b/sympy/core/tests/test_evalf.py
@@ -7,6 +7,7 @@
 from mpmath import inf, ninf
 from mpmath.libmp.libmpf import from_float
 from sympy.core.compatibility import long, range
+from sympy.core.expr import unchanged
 from sympy.utilities.pytest import raises, XFAIL
 from sympy.abc import n, x, y
 
@@ -348,6 +349,12 @@ def test_evaluate_false():
 
 def test_evalf_relational():
     assert Eq(x/5, y/10).evalf() == Eq(0.2*x, 0.1*y)
+    # if this first assertion fails it should be replaced with
+    # one that doesn't
+    assert unchanged(Eq, (3 - I)**2/2 + I, 0)
+    assert Eq((3 - I)**2/2 + I, 0).n() is S.false
+    # note: these don't always evaluate to Boolean
+    assert nfloat(Eq((3 - I)**2 + I, 0)) == Eq((3.0 - I)**2 + I, 0)
 
 
 def test_issue_5486():
diff --git a/sympy/core/tests/test_function.py b/sympy/core/tests/test_function.py
index 8108b378a8..ff2d4a6ed2 100644
--- a/sympy/core/tests/test_function.py
+++ b/sympy/core/tests/test_function.py
@@ -2,7 +2,7 @@
         log, exp, Rational, Float, sin, cos, acos, diff, I, re, im,
         E, expand, pi, O, Sum, S, polygamma, loggamma, expint,
         Tuple, Dummy, Eq, Expr, symbols, nfloat, Piecewise, Indexed,
-        Matrix, Basic)
+        Matrix, Basic, Dict)
 from sympy.utilities.pytest import XFAIL, raises
 from sympy.core.basic import _aresame
 from sympy.core.function import PoleError, _mexpand, arity
@@ -822,8 +822,6 @@ def test_nfloat():
     assert _aresame(nfloat(big), Float_big)
     assert _aresame(nfloat(big*x), Float_big*x)
     assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
-    assert nfloat({x: sqrt(2)}) == {x: nfloat(sqrt(2))}
-    assert nfloat({sqrt(2): x}) == {sqrt(2): x}
     assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2)))
 
     # issue 6342
@@ -838,6 +836,28 @@ def test_nfloat():
     eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0)
     assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)'
 
+    # issue 10933
+    for t in (dict, Dict):
+        d = t({S.Half: S.Half})
+        n = nfloat(d)
+        assert isinstance(n, t)
+        assert _aresame(list(n.items()).pop(), (S.Half, Float(.5)))
+    for t in (dict, Dict):
+        d = t({S.Half: S.Half})
+        n = nfloat(d, dkeys=True)
+        assert isinstance(n, t)
+        assert _aresame(list(n.items()).pop(), (Float(.5), Float(.5)))
+    d = [S.Half]
+    n = nfloat(d)
+    assert type(n) is list
+    assert _aresame(n[0], Float(.5))
+    assert _aresame(nfloat(Eq(x, S.Half)).rhs, Float(.5))
+    assert _aresame(nfloat(S(True)), S(True))
+    assert _aresame(nfloat(Tuple(S.Half))[0], Float(.5))
+    assert nfloat(Eq((3 - I)**2/2 + I, 0)) == S.false
+    # pass along kwargs
+    assert nfloat([{S.Half: x}], dkeys=True) == [{Float(0.5): x}]
+
 
 def test_issue_7068():
     from sympy.abc import a, b
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index 4bb55ec71e..1d2ed249c1 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -23,12 +23,12 @@
 
 from sympy.abc import mu, tau
 from sympy.printing.latex import (latex, translate, greek_letters_set,
-                                  tex_greek_dictionary, multiline_latex)
+                                  tex_greek_dictionary)
 from sympy.tensor.array import (ImmutableDenseNDimArray,
                                 ImmutableSparseNDimArray,
                                 MutableSparseNDimArray,
-                                MutableDenseNDimArray,
-                                tensorproduct)
+                                MutableDenseNDimArray)
+from sympy.tensor.array import tensorproduct
 from sympy.utilities.pytest import XFAIL, raises
 from sympy.functions import DiracDelta, Heaviside, KroneckerDelta, LeviCivita
 from sympy.functions.combinatorial.numbers import bernoulli, bell, lucas, \
@@ -2116,58 +2116,6 @@ def test_latex_printer_tensor():
     assert latex(expr) == 'K{}^{i=3,j}{}_{kl}'
 
 
-def test_multiline_latex():
-    a, b, c, d, e, f = symbols('a b c d e f')
-    expr = -a + 2*b -3*c +4*d -5*e
-    expected = r"\begin{eqnarray}" + "\n"\
-    r"f & = &- a \nonumber\\" + "\n"\
-    r"& & + 2 b \nonumber\\" + "\n"\
-    r"& & - 3 c \nonumber\\" + "\n"\
-    r"& & + 4 d \nonumber\\" + "\n"\
-    r"& & - 5 e " + "\n"\
-    r"\end{eqnarray}"
-    assert multiline_latex(f, expr, environment="eqnarray") == expected
-
-    expected2 = r'\begin{eqnarray}' + '\n'\
-    r'f & = &- a + 2 b \nonumber\\' + '\n'\
-    r'& & - 3 c + 4 d \nonumber\\' + '\n'\
-    r'& & - 5 e ' + '\n'\
-    r'\end{eqnarray}'
-
-    assert multiline_latex(f, expr, 2, environment="eqnarray") == expected2
-
-    expected3 = r'\begin{eqnarray}' + '\n'\
-    r'f & = &- a + 2 b - 3 c \nonumber\\'+ '\n'\
-    r'& & + 4 d - 5 e ' + '\n'\
-    r'\end{eqnarray}'
-
-    assert multiline_latex(f, expr, 3, environment="eqnarray") == expected3
-
-    expected3dots = r'\begin{eqnarray}' + '\n'\
-    r'f & = &- a + 2 b - 3 c \dots\nonumber\\'+ '\n'\
-    r'& & + 4 d - 5 e ' + '\n'\
-    r'\end{eqnarray}'
-
-    assert multiline_latex(f, expr, 3, environment="eqnarray", use_dots=True) == expected3dots
-
-    expected3align = r'\begin{align*}' + '\n'\
-    r'f = &- a + 2 b - 3 c \\'+ '\n'\
-    r'& + 4 d - 5 e ' + '\n'\
-    r'\end{align*}'
-
-    assert multiline_latex(f, expr, 3) == expected3align
-    assert multiline_latex(f, expr, 3, environment='align*') == expected3align
-
-    expected2ieee = r'\begin{IEEEeqnarray}{rCl}' + '\n'\
-    r'f & = &- a + 2 b \nonumber\\' + '\n'\
-    r'& & - 3 c + 4 d \nonumber\\' + '\n'\
-    r'& & - 5 e ' + '\n'\
-    r'\end{IEEEeqnarray}'
-
-    assert multiline_latex(f, expr, 2, environment="IEEEeqnarray") == expected2ieee
-
-    raises(ValueError, lambda: multiline_latex(f, expr, environment="foo"))
-
 def test_issue_15353():
     from sympy import ConditionSet, Tuple, FiniteSet, S, sin, cos
     a, x = symbols('a x')
diff --git a/sympy/simplify/tests/test_simplify.py b/sympy/simplify/tests/test_simplify.py
index be3311ee77..25734cbf17 100644
--- a/sympy/simplify/tests/test_simplify.py
+++ b/sympy/simplify/tests/test_simplify.py
@@ -399,6 +399,7 @@ def test_nsimplify():
     # Make sure nsimplify on expressions uses full precision
     assert nsimplify(pi.evalf(100)*x, rational_conversion='exact').evalf(100) == pi.evalf(100)*x
 
+
 def test_issue_9448():
     tmp = sympify("1/(1 - (-1)**(2/3) - (-1)**(1/3)) + 1/(1 + (-1)**(2/3) + (-1)**(1/3))")
     assert nsimplify(tmp) == S(1)/2
diff --git a/sympy/solvers/tests/test_solvers.py b/sympy/solvers/tests/test_solvers.py
index f7fa9ef0a1..38020f4157 100644
--- a/sympy/solvers/tests/test_solvers.py
+++ b/sympy/solvers/tests/test_solvers.py
@@ -2038,3 +2038,8 @@ def test_issue_15731():
     b = Symbol('b', positive=True)
     assert solve(b**x - b**2, x) == [2]
     assert solve(b**x - 1/b, x) == [-1]
+
+
+def test_issue_10933():
+    assert solve(x**4 + y*(x + 0.1), x)  # doesn't fail
+    assert solve(I*x**4 + x**3 + x**2 + 1.)  # doesn't fail