Ejemplo n.º 1
0
def test_diofant_parser():
    x = Symbol('x')
    inputs = {
        '2*x':
        2 * x,
        '3.00':
        Float(3),
        '22/7':
        Rational(22, 7),
        '2+3j':
        2 + 3 * I,
        'exp(x)':
        exp(x),
        '-(2)':
        -Integer(2),
        '[-1, -2, 3]': [Integer(-1), Integer(-2),
                        Integer(3)],
        'Symbol("x").free_symbols':
        x.free_symbols,
        'Float(Integer(3).evalf(3))':
        3.00,
        'factorint(12, visual=True)':
        Mul(Pow(2, 2, evaluate=False),
            Pow(3, 1, evaluate=False),
            evaluate=False),
        'Limit(sin(x), x, 0, dir="-")':
        Limit(sin(x), x, 0, dir='-'),
    }
    for text, result in inputs.items():
        assert parse_expr(text) == result
Ejemplo n.º 2
0
def test_sympyissue_4149():
    assert (3 + I).is_complex
    assert (3 + I).is_imaginary is False
    assert (3 * I + S.Pi * I).is_imaginary
    y = Symbol('y', real=True)
    assert (3 * I + S.Pi * I + y * I).is_imaginary is True
    p = Symbol('p', positive=True, finite=True)
    assert (3 * I + S.Pi * I + p * I).is_imaginary
    n = Symbol('n', negative=True, finite=True)
    assert (-3 * I - S.Pi * I + n * I).is_imaginary

    i = Symbol('i', imaginary=True)
    assert ([(i**a).is_imaginary
             for a in range(4)] == [False, True, False, True])

    # tests from the PR sympy/sympy#7887:
    e = -sqrt(3) * I / 2 + Float(0.866025403784439) * I
    assert e.is_extended_real is False
    assert e.is_imaginary
Ejemplo n.º 3
0
def test_ipython_printing(monkeypatch):
    app = ipython.terminal.ipapp.TerminalIPythonApp()
    app.display_banner = False
    app.initialize([])
    app = app.shell

    app.run_cell("ip = get_ipython()")
    app.run_cell("inst = ip.instance()")
    app.run_cell("format = inst.display_formatter.format")
    app.run_cell("import warnings")
    app.run_cell("import IPython")
    app.run_cell("import diofant")
    app.run_cell("from diofant import Float, Rational, Symbol, QQ, "
                 "factorial, sqrt, init_printing, pretty, "
                 "Matrix, sstrrepr")

    # Test IntegerDivisionWrapper

    app.run_cell(
        "from diofant.interactive.session import IntegerDivisionWrapper")
    app.run_cell("ip.ast_transformers.clear()")
    app.run_cell("ip.ast_transformers.append(IntegerDivisionWrapper())")

    app.run_cell("a = 1")
    assert isinstance(app.user_ns['a'], int)

    app.run_cell("a = 1/2")
    assert isinstance(app.user_ns['a'], Rational)
    app.run_cell("a = 1")
    assert isinstance(app.user_ns['a'], int)
    app.run_cell("a = int(1)")
    assert isinstance(app.user_ns['a'], int)
    app.run_cell("a = (1/\n2)")
    assert app.user_ns['a'] == Rational(1, 2)

    # Test AutomaticSymbols

    app.run_cell("from diofant.interactive.session import AutomaticSymbols")
    app.run_cell("ip.ast_transformers.clear()")
    app.run_cell("ip.ast_transformers.append(AutomaticSymbols())")

    symbol = "verylongsymbolname"
    assert symbol not in app.user_ns
    app.run_cell("a = %s" % symbol)
    app.run_cell("a = type(%s)" % symbol)
    assert app.user_ns['a'] == Symbol
    app.run_cell("%s = Symbol('%s')" % (symbol, symbol))
    assert symbol in app.user_ns

    # Check that built-in names aren't overridden
    app.run_cell("a = all == __builtin__.all")
    assert "all" not in app.user_ns
    assert app.user_ns['a'] is True

    # Check that diofant names aren't overridden
    app.run_cell("a = factorial == diofant.factorial")
    assert app.user_ns['a'] is True

    # Test FloatRationalizer

    app.run_cell("from diofant.interactive.session import FloatRationalizer")
    app.run_cell("ip.ast_transformers.clear()")
    app.run_cell("ip.ast_transformers.append(FloatRationalizer())")
    app.run_cell("a = 0.3")
    assert isinstance(app.user_ns['a'], Rational)
    app.run_cell("a = float(0.3)")
    assert isinstance(app.user_ns['a'], float)
    app.run_cell("a = Float(1.23)")
    assert isinstance(app.user_ns['a'], Float)
    assert app.user_ns['a'] == Float(1.23)
    app.run_cell("a = 2")
    assert isinstance(app.user_ns['a'], int)

    # General printing tests

    # Initialize and setup IPython session
    app.run_cell("ip.ast_transformers.clear()")

    # Printing by default
    app.run_cell("a = format(Symbol('pi'))")
    app.run_cell("a2 = format(Symbol('pi')**2)")
    app.run_cell("init_printing()")
    assert app.user_ns['a'][0]['text/plain'] in ('\N{GREEK SMALL LETTER PI}',
                                                 'pi')
    assert app.user_ns['a2'][0]['text/plain'] in (
        ' 2\n\N{GREEK SMALL LETTER PI} ', '  2\npi ')

    # Use different printing setup
    app.run_cell("init_printing(use_unicode=False)")
    app.run_cell("a = format(Symbol('pi'))")
    app.run_cell("a2 = format(Symbol('pi')**2)")
    assert app.user_ns['a'][0]['text/plain'] == "pi"
    assert app.user_ns['a2'][0]['text/plain'] == "  2\npi "

    app.run_cell("a = format(int(1))")
    pytest.raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])

    app.run_cell("init_printing()")
    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
    text = app.user_ns['a'][0]['text/plain']
    pytest.raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
    # XXX: How can we make this ignore the terminal width? This test fails if
    # the terminal is too narrow.
    assert text in (
        '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
        '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}'
    )

    # If we enable the default printing, then the dictionary's should render
    # as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
    app.run_cell("init_printing()")
    app.run_cell(
        "inst.display_formatter.formatters['text/latex'].enabled = True")
    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
    text = app.user_ns['a'][0]['text/plain']
    latex = app.user_ns['a'][0]['text/latex']
    assert text in (
        '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
        '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}'
    )
    assert latex == r'\begin{equation*}\left \{ n_{i} : 3, \quad \pi : 3.14\right \}\end{equation*}'

    app.run_cell("a = format([Symbol('x'), Symbol('y')])")
    latex = app.user_ns['a'][0]['text/latex']
    assert latex in (
        r'\begin{equation*}\left [ x, \quad y\right ]\end{equation*}',
        r'\begin{equation*}left [ y, \quad x\right ]\end{equation*}')

    app.run_cell("a = format(False)")
    assert app.user_ns['a'][0]['text/plain'] == r'False'

    app.run_cell("init_printing(no_global=True)")
    app.run_cell("a = format({Symbol('pi')})")
    assert app.user_ns['a'][0]['text/plain'] == '{\N{GREEK SMALL LETTER PI}}'

    app.run_cell("init_printing(use_unicode=False)")
    app.run_cell("a = format(Symbol('pi'))")
    assert app.user_ns['a'][0]['text/plain'] == 'pi'

    app.run_cell("init_printing(order=None)")  # this will fallback to defaults
    app.run_cell("a = format(Symbol('pi'))")
    assert app.user_ns['a'][0]['text/plain'] == 'π'

    app.run_cell("init_printing()")
    app.run_cell(
        "inst.display_formatter.formatters['text/latex'].enabled = False")
    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
    text = app.user_ns['a'][0]['text/plain']
    pytest.raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])

    # something to test default pretty/latex printing
    app.run_cell("init_printing()")
    app.run_cell(
        "inst.display_formatter.formatters['text/latex'].enabled = True")
    app.run_cell("a = format(QQ.algebraic_field(sqrt(2)))")
    text = app.user_ns['a'][0]['text/plain']
    latex = app.user_ns['a'][0]['text/latex']
    assert text == "QQ<sqrt(2)>"
    assert latex == r"\begin{equation}QQ<sqrt(2)>\end{equation}"

    # test_matplotlib_bad_latex

    # Initialize and setup IPython session
    app.run_cell("init_printing()")

    # Make sure no warnings are raised by IPython
    app.run_cell(
        "warnings.simplefilter('error', IPython.core.formatters.FormatterWarning)"
    )

    # This should not raise an exception
    app.run_cell("a = format(Matrix([1, 2, 3]))")

    # Test dumb terminal

    monkeypatch.setenv('TERM', '')
    app.run_cell("init_printing()")
    app.run_cell("a = format(Symbol('pi'))")
    assert app.user_ns['a'][0]['text/plain'] == "pi"
Ejemplo n.º 4
0
def test_negative_real():
    def feq(a, b):
        return abs(a - b) < 1E-10

    assert feq(S.One / Float(-0.5), -Integer(2))
Ejemplo n.º 5
0
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision. """
        with workprec(prec):
            g = self.poly.gen
            if not g.is_Symbol:
                d = Dummy('x')
                func = lambdify(d, self.expr.subs(g, d))
            else:
                func = lambdify(g, self.expr)

            interval = self._get_interval()
            if not self.is_extended_real:
                # For complex intervals, we need to keep refining until the
                # imaginary interval is disjunct with other roots, that is,
                # until both ends get refined.
                ay = interval.ay
                by = interval.by
                while interval.ay == ay or interval.by == by:
                    interval = interval.refine()

            while True:
                if self.is_extended_real:
                    a = mpf(str(interval.a))
                    b = mpf(str(interval.b))
                    if a == b:
                        root = a
                        break
                    x0 = mpf(str(interval.center))
                else:
                    ax = mpf(str(interval.ax))
                    bx = mpf(str(interval.bx))
                    ay = mpf(str(interval.ay))
                    by = mpf(str(interval.by))
                    if ax == bx and ay == by:
                        # the sign of the imaginary part will be assigned
                        # according to the desired index using the fact that
                        # roots are sorted with negative imag parts coming
                        # before positive (and all imag roots coming after real
                        # roots)
                        deg = self.poly.degree()
                        i = self.index  # a positive attribute after creation
                        if (deg - i) % 2:
                            if ay < 0:
                                ay = -ay
                        else:
                            if ay > 0:
                                ay = -ay
                        root = mpc(ax, ay)
                        break
                    x0 = mpc(*map(str, interval.center))

                try:
                    root = findroot(func, x0)
                    # If the (real or complex) root is not in the 'interval',
                    # then keep refining the interval. This happens if findroot
                    # accidentally finds a different root outside of this
                    # interval because our initial estimate 'x0' was not close
                    # enough. It is also possible that the secant method will
                    # get trapped by a max/min in the interval; the root
                    # verification by findroot will raise a ValueError in this
                    # case and the interval will then be tightened -- and
                    # eventually the root will be found.
                    if self.is_extended_real:
                        if (a <= root <= b):
                            break
                    elif (ax <= root.real <= bx and ay <= root.imag <= by):
                        break
                except ValueError:
                    pass
                interval = interval.refine()

        return Float._new(root.real._mpf_,
                          prec) + I * Float._new(root.imag._mpf_, prec)