Пример #1
0
def test_nfloat():
    from sympy.core.basic import _aresame
    from sympy.polys.rootoftools import RootOf

    x = Symbol("x")
    eq = x**(S(4)/3) + 4*x**(S(1)/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(S(1)/3))
    assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
    eq = x**(S(4)/3) + 4*x**(x/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(x/3))
    big = 12345678901234567890
    Float_big = Float(big)
    assert _aresame(nfloat(x**big, exponent=True),
                    x**Float_big)
    assert _aresame(nfloat(big), 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
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solve(f.subs(x, -0.139)))

    # issue 6632
    assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
        9.99999999800000e-11

    # issue 7122
    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)'
Пример #2
0
def test_nfloat():
    from sympy.core.basic import _aresame
    from sympy.polys.rootoftools import RootOf

    x = Symbol("x")
    eq = x**(S(4) / 3) + 4 * x**(S(1) / 3) / 3
    assert _aresame(nfloat(eq), x**(S(4) / 3) + (4.0 / 3) * x**(S(1) / 3))
    assert _aresame(nfloat(eq, exponent=True),
                    x**(4.0 / 3) + (4.0 / 3) * x**(1.0 / 3))
    eq = x**(S(4) / 3) + 4 * x**(x / 3) / 3
    assert _aresame(nfloat(eq), x**(S(4) / 3) + (4.0 / 3) * x**(x / 3))
    big = 12345678901234567890
    Float_big = Float(big)
    assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
    assert _aresame(nfloat(big), 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
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solve(f.subs(x, -0.139)))

    # issue 6632
    assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
        9.99999999800000e-11

    # issue 7122
    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)'
Пример #3
0
    def _eval_evalf(self, prec):
        """
        Evaluate the parts of self that are numbers; if the whole thing
        was a number with no functions it would have been evaluated, but
        it wasn't so we must judiciously extract the numbers and reconstruct
        the object. This is *not* simply replacing numbers with evaluated
        numbers. Nunmbers should be handled in the largest pure-number
        expression as possible. So the code below separates ``self`` into
        number and non-number parts and evaluates the number parts and
        walks the args of the non-number part recursively (doing the same
        thing).
        """
        from .add import Add
        from .mul import Mul
        from .symbol import Symbol
        from .function import AppliedUndef
        if isinstance(self, (Mul, Add)):
            x, tail = self.as_independent(Symbol, AppliedUndef)
            # if x is an AssocOp Function then the _evalf below will
            # call _eval_evalf (here) so we must break the recursion
            if not (tail is self.identity or
                    isinstance(x, AssocOp) and x.is_Function or
                    x is self.identity and isinstance(tail, AssocOp)):
                # here, we have a number so we just call to _evalf with prec;
                # prec is not the same as n, it is the binary precision so
                # that's why we don't call to evalf.
                x = x._evalf(prec) if x is not self.identity else self.identity
                args = []
                tail_args = tuple(self.func.make_args(tail))
                for a in tail_args:
                    # here we call to _eval_evalf since we don't know what we
                    # are dealing with and all other _eval_evalf routines should
                    # be doing the same thing (i.e. taking binary prec and
                    # finding the evalf-able args)
                    newa = a._eval_evalf(prec)
                    if newa is None:
                        args.append(a)
                    else:
                        args.append(newa)
                if not _aresame(tuple(args), tail_args):
                    tail = self.func(*args)
                return self.func(x, tail)

        # this is the same as above, but there were no pure-number args to
        # deal with
        args = []
        for a in self.args:
            newa = a._eval_evalf(prec)
            if newa is None:
                args.append(a)
            else:
                args.append(newa)
        if not _aresame(tuple(args), self.args):
            return self.func(*args)
        return self
Пример #4
0
    def _eval_evalf(self, prec):
        """
        Evaluate the parts of self that are numbers; if the whole thing
        was a number with no functions it would have been evaluated, but
        it wasn't so we must judiciously extract the numbers and reconstruct
        the object. This is *not* simply replacing numbers with evaluated
        numbers. Nunmbers should be handled in the largest pure-number
        expression as possible. So the code below separates ``self`` into
        number and non-number parts and evaluates the number parts and
        walks the args of the non-number part recursively (doing the same
        thing).
        """
        from .add import Add
        from .mul import Mul
        from .symbol import Symbol
        from .function import AppliedUndef
        if isinstance(self, (Mul, Add)):
            x, tail = self.as_independent(Symbol, AppliedUndef)
            # if x is an AssocOp Function then the _evalf below will
            # call _eval_evalf (here) so we must break the recursion
            if not (tail is self.identity
                    or isinstance(x, AssocOp) and x.is_Function
                    or x is self.identity and isinstance(tail, AssocOp)):
                # here, we have a number so we just call to _evalf with prec;
                # prec is not the same as n, it is the binary precision so
                # that's why we don't call to evalf.
                x = x._evalf(prec) if x is not self.identity else self.identity
                args = []
                tail_args = tuple(self.func.make_args(tail))
                for a in tail_args:
                    # here we call to _eval_evalf since we don't know what we
                    # are dealing with and all other _eval_evalf routines should
                    # be doing the same thing (i.e. taking binary prec and
                    # finding the evalf-able args)
                    newa = a._eval_evalf(prec)
                    if newa is None:
                        args.append(a)
                    else:
                        args.append(newa)
                if not _aresame(tuple(args), tail_args):
                    tail = self.func(*args)
                return self.func(x, tail)

        # this is the same as above, but there were no pure-number args to
        # deal with
        args = []
        for a in self.args:
            newa = a._eval_evalf(prec)
            if newa is None:
                args.append(a)
            else:
                args.append(newa)
        if not _aresame(tuple(args), self.args):
            return self.func(*args)
        return self
Пример #5
0
def test_nfloat():
    from sympy.core.basic import _aresame
    x = Symbol("x")
    eq = x**(S(4)/3) + 4*x**(S(1)/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(S(1)/3))
    assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
    eq = x**(S(4)/3) + 4*x**(x/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(x/3))
    big = 12345678901234567890
    Float_big = Float(big, '')
    assert _aresame(nfloat(x**big, exponent=True),
                           x**Float_big)
    assert _aresame(nfloat(big), Float_big)
Пример #6
0
    def convert(self, elem, M=None):
        """
        Convert ``elem`` into the internal representation.

        This method is called implicitly whenever computations involve elements
        not in the internal representation.

        Examples
        ========

        >>> from sympy.abc import x
        >>> from sympy import QQ
        >>> F = QQ.old_poly_ring(x).free_module(2)
        >>> F.convert([1, 0])
        [1, 0]
        """
        if isinstance(elem, FreeModuleElement):
            if elem.module is self:
                return elem
            if elem.module.rank != self.rank:
                raise CoercionFailed
            return FreeModuleElement(self,
                     tuple(self.ring.convert(x, elem.module.ring) for x in elem.data))
        elif iterable(elem):
            tpl = tuple(self.ring.convert(x) for x in elem)
            if len(tpl) != self.rank:
                raise CoercionFailed
            return FreeModuleElement(self, tpl)
        elif _aresame(elem, 0):
            return FreeModuleElement(self, (self.ring.convert(0),)*self.rank)
        else:
            raise CoercionFailed
Пример #7
0
def test_nfloat():
    from sympy.core.basic import _aresame
    x = Symbol("x")
    eq = x**(S(4)/3) + 4*x**(S(1)/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(S(1)/3))
    assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
    eq = x**(S(4)/3) + 4*x**(x/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(x/3))
    big = 12345678901234567890
    Float_big = Float(big, '')
    assert _aresame(nfloat(x**big, exponent=True),
                           x**Float_big)
    assert _aresame(nfloat(big), Float_big)

    # issues 3243
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solve(f.subs(x, -0.139)))
Пример #8
0
def test_nfloat():
    from sympy.core.basic import _aresame
    x = Symbol("x")
    eq = x**(S(4) / 3) + 4 * x**(S(1) / 3) / 3
    assert _aresame(nfloat(eq), x**(S(4) / 3) + (4.0 / 3) * x**(S(1) / 3))
    assert _aresame(nfloat(eq, exponent=True),
                    x**(4.0 / 3) + (4.0 / 3) * x**(1.0 / 3))
    eq = x**(S(4) / 3) + 4 * x**(x / 3) / 3
    assert _aresame(nfloat(eq), x**(S(4) / 3) + (4.0 / 3) * x**(x / 3))
    big = 12345678901234567890
    Float_big = Float(big, '')
    assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
    assert _aresame(nfloat(big), Float_big)

    # issues 3243
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solve(f.subs(x, -0.139)))
Пример #9
0
def test_issue_6079():
    # since x + 2.0 == x + 2 we can't do a simple equality test
    assert _aresame((x + 2.0).subs(2, 3), x + 2.0)
    assert _aresame((x + 2.0).subs(2.0, 3), x + 3)
    assert not _aresame(x + 2, x + 2.0)
    assert not _aresame(Basic(cos, 1), Basic(cos, 1.))
    assert _aresame(cos, cos)
    assert not _aresame(1, S(1))
    assert not _aresame(x, symbols('x', positive=True))
Пример #10
0
def test_issue_6079():
    # since x + 2.0 == x + 2 we can't do a simple equality test
    assert _aresame((x + 2.0).subs(2, 3), x + 2.0)
    assert _aresame((x + 2.0).subs(2.0, 3), x + 3)
    assert not _aresame(x + 2, x + 2.0)
    assert not _aresame(Basic(cos, 1), Basic(cos, 1.))
    assert _aresame(cos, cos)
    assert not _aresame(1, S(1))
    assert not _aresame(x, symbols('x', positive=True))
Пример #11
0
 def xreplace(self, rule):
     if self in rule:
         return rule[self]
     elif rule:
         args = []
         for a in self.args:
             try:
                 args.append(a.xreplace(rule))
             except AttributeError:
                 args.append(a)
         args = tuple(args)
         if not _aresame(args, self.args):
             return self.func(*args, evaluate=False)
     return self
Пример #12
0
 def xreplace(self, rule):
     if self in rule:
         return rule[self]
     elif rule:
         args = []
         for a in self.args:
             try:
                 args.append(a.xreplace(rule))
             except AttributeError:
                 args.append(a)
         args = tuple(args)
         if not _aresame(args, self.args):
             return self.func(*args, evaluate=False)
     return self
Пример #13
0
def test_nfloat():
    from sympy.core.basic import _aresame
    x = Symbol("x")
    eq = x**(S(4) / 3) + 4 * x**(S(1) / 3) / 3
    assert _aresame(nfloat(eq), x**(S(4) / 3) + (4.0 / 3) * x**(S(1) / 3))
    assert _aresame(nfloat(eq, exponent=True),
                    x**(4.0 / 3) + (4.0 / 3) * x**(1.0 / 3))
    eq = x**(S(4) / 3) + 4 * x**(x / 3) / 3
    assert _aresame(nfloat(eq), x**(S(4) / 3) + (4.0 / 3) * x**(x / 3))
    big = 12345678901234567890
    Float_big = Float(big)
    assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
    assert _aresame(nfloat(big), 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)))

    # issues 3243
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solve(f.subs(x, -0.139)))

    # issue 3533
    assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
        9.99999999800000e-11
Пример #14
0
def test_nfloat():
    from sympy.core.basic import _aresame
    x = Symbol("x")
    eq = x**(S(4)/3) + 4*x**(S(1)/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(S(1)/3))
    assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
    eq = x**(S(4)/3) + 4*x**(x/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(x/3))
    big = 12345678901234567890
    Float_big = Float(big)
    assert _aresame(nfloat(x**big, exponent=True),
                    x**Float_big)
    assert _aresame(nfloat(big), 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)))

    # issues 3243
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solve(f.subs(x, -0.139)))

    # issue 3533
    assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
        9.99999999800000e-11
Пример #15
0
def test_Float():
    def eq(a, b):
        t = Float("1.0E-15")
        return (-t < a - b < t)

    a = Float(2) ** Float(3)
    assert eq(a.evalf(), Float(8))
    assert eq((pi ** -1).evalf(), Float("0.31830988618379067"))
    a = Float(2) ** Float(4)
    assert eq(a.evalf(), Float(16))
    assert (S(.3) == S(.5)) is False
    x_str = Float((0, '13333333333333', -52, 53))
    x2_str = Float((0, '26666666666666', -53, 53))
    x_hex = Float((0, long(0x13333333333333), -52, 53))
    x_dec = Float((0, 5404319552844595, -52, 53))
    x2_hex = Float((0, long(0x13333333333333)*2, -53, 53))
    assert x_str == x_hex == x_dec == x2_hex == Float(1.2)
    # x2_str and 1.2 are superficially the same
    assert str(x2_str) == str(Float(1.2))
    # but are different at the mpf level
    assert Float(1.2)._mpf_ == (0, long(5404319552844595), -52, 53)
    assert x2_str._mpf_ == (0, long(10808639105689190), -53, 53)

    assert Float((0, long(0), -123, -1)) == Float('nan')
    assert Float((0, long(0), -456, -2)) == Float('inf') == Float('+inf')
    assert Float((1, long(0), -789, -3)) == Float('-inf')

    raises(ValueError, lambda: Float((0, 7, 1, 3), ''))

    assert Float('+inf').is_bounded is False
    assert Float('+inf').is_negative is False
    assert Float('+inf').is_positive is True
    assert Float('+inf').is_unbounded is True
    assert Float('+inf').is_zero is False

    assert Float('-inf').is_bounded is False
    assert Float('-inf').is_negative is True
    assert Float('-inf').is_positive is False
    assert Float('-inf').is_unbounded is True
    assert Float('-inf').is_zero is False

    assert Float('0.0').is_bounded is True
    assert Float('0.0').is_negative is False
    assert Float('0.0').is_positive is False
    assert Float('0.0').is_unbounded is False
    assert Float('0.0').is_zero is True

    # rationality properties
    assert Float(1).is_rational is None
    assert Float(1).is_irrational is None
    assert sqrt(2).n(15).is_rational is None
    assert sqrt(2).n(15).is_irrational is None

    # do not automatically evalf
    def teq(a):
        assert (a.evalf() == a) is False
        assert (a.evalf() != a) is True
        assert (a == a.evalf()) is False
        assert (a != a.evalf()) is True

    teq(pi)
    teq(2*pi)
    teq(cos(0.1, evaluate=False))

    i = 12345678901234567890
    assert _aresame(Float(12, ''), Float('12', ''))
    assert _aresame(Float(Integer(i), ''), Float(i, ''))
    assert _aresame(Float(i, ''), Float(str(i), 20))
    assert not _aresame(Float(str(i)), Float(i, ''))

    # inexact floats (repeating binary = denom not multiple of 2)
    # cannot have precision greater than 15
    assert Float(.125, 22) == .125
    assert Float(2.0, 22) == 2
    assert float(Float('.12500000000000001', '')) == .125
    raises(ValueError, lambda: Float(.12500000000000001, ''))

    # allow spaces
    Float('123 456.123 456') == Float('123456.123456')
    Integer('123 456') == Integer('123456')
    Rational('123 456.123 456') == Rational('123456.123456')
    assert Float(' .3e2') == Float('0.3e2')

    # allow auto precision detection
    assert Float('.1', '') == Float(.1, 1)
    assert Float('.125', '') == Float(.125, 3)
    assert Float('.100', '') == Float(.1, 3)
    assert Float('2.0', '') == Float('2', 2)

    raises(ValueError, lambda: Float("12.3d-4", ""))
    raises(ValueError, lambda: Float(12.3, ""))
    raises(ValueError, lambda: Float('.'))
    raises(ValueError, lambda: Float('-.'))

    zero = Float('0.0')
    assert Float('-0') == zero
    assert Float('.0') == zero
    assert Float('-.0') == zero
    assert Float('-0.0') == zero
    assert Float(0.0) == zero
    assert Float(0) == zero
    assert Float(0, '') == Float('0', '')
    assert Float(1) == Float(1.0)
    assert Float(S.Zero) == zero
    assert Float(S.One) == Float(1.0)

    assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3)

    assert '{0:.3f}'.format(Float(4.236622)) == '4.237'
    assert '{0:.35f}'.format(Float(pi.n(40), 40)) == '3.14159265358979323846264338327950288'
Пример #16
0
def test_sort_variable():
    vsort = Derivative._sort_variable_count
    def vsort0(*v, **kw):
        reverse = kw.get('reverse', False)
        return [i[0] for i in vsort([(i, 0) for i in (
            reversed(v) if reverse else v)])]

    for R in range(2):
        assert vsort0(y, x, reverse=R) == [x, y]
        assert vsort0(f(x), x, reverse=R) == [x, f(x)]
        assert vsort0(f(y), f(x), reverse=R) == [f(x), f(y)]
        assert vsort0(g(x), f(y), reverse=R) == [f(y), g(x)]
        assert vsort0(f(x, y), f(x), reverse=R) == [f(x), f(x, y)]
        fx = f(x).diff(x)
        assert vsort0(fx, y, reverse=R) == [y, fx]
        fy = f(y).diff(y)
        assert vsort0(fy, fx, reverse=R) == [fx, fy]
        fxx = fx.diff(x)
        assert vsort0(fxx, fx, reverse=R) == [fx, fxx]
        assert vsort0(Basic(x), f(x), reverse=R) == [f(x), Basic(x)]
        assert vsort0(Basic(y), Basic(x), reverse=R) == [Basic(x), Basic(y)]
        assert vsort0(Basic(y, z), Basic(x), reverse=R) == [
            Basic(x), Basic(y, z)]
        assert vsort0(fx, x, reverse=R) == [
            x, fx] if R else [fx, x]
        assert vsort0(Basic(x), x, reverse=R) == [
            x, Basic(x)] if R else [Basic(x), x]
        assert vsort0(Basic(f(x)), f(x), reverse=R) == [
            f(x), Basic(f(x))] if R else [Basic(f(x)), f(x)]
        assert vsort0(Basic(x, z), Basic(x), reverse=R) == [
            Basic(x), Basic(x, z)] if R else [Basic(x, z), Basic(x)]
    assert vsort([]) == []
    assert _aresame(vsort([(x, 1)]), [Tuple(x, 1)])
    assert vsort([(x, y), (x, z)]) == [(x, y + z)]
    assert vsort([(y, 1), (x, 1 + y)]) == [(x, 1 + y), (y, 1)]
    # coverage complete; legacy tests below
    assert vsort([(x, 3), (y, 2), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
    assert vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) == [
        (f(x), 1), (g(x), 1), (h(x), 1)]
    assert vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1),
        (f(x), 1)]) == [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1),
        (h(x), 1)]
    assert vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) == [(x, 1),
        (y, 1), (f(x), 1), (f(y), 1)]
    assert vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1),
        (h(x), 1), (y, 2), (x, 1)]) == [(x, 3), (y, 3), (z, 1),
        (f(x), 1), (g(x), 1), (h(x), 1)]
    assert vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1),
        (g(x), 1)]) == [(x, 1), (y, 1), (z, 1), (f(x), 2), (g(x), 1)]
    assert vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2),
        (g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)]) == [(x, 3), (y, 3),
        (z, 4), (f(x), 3), (g(x), 1)]
    assert vsort(((y, 2), (x, 1), (y, 1), (x, 1))) == [(x, 2), (y, 3)]
    assert isinstance(vsort([(x, 3), (y, 2), (z, 1)])[0], Tuple)
    assert vsort([(x, 1), (f(x), 1), (x, 1)]) == [(x, 2), (f(x), 1)]
    assert vsort([(y, 2), (x, 3), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
    assert vsort([(h(y), 1), (g(x), 1), (f(x), 1)]) == [
        (f(x), 1), (g(x), 1), (h(y), 1)]
    assert vsort([(x, 1), (y, 1), (x, 1)]) == [(x, 2), (y, 1)]
    assert vsort([(f(x), 1), (f(y), 1), (f(x), 1)]) == [
        (f(x), 2), (f(y), 1)]
    dfx = f(x).diff(x)
    self = [(dfx, 1), (x, 1)]
    assert vsort(self) == self
    assert vsort([
        (dfx, 1), (y, 1), (f(x), 1), (x, 1), (f(y), 1), (x, 1)]) == [
        (y, 1), (f(x), 1), (f(y), 1), (dfx, 1), (x, 2)]
    dfy = f(y).diff(y)
    assert vsort([(dfy, 1), (dfx, 1)]) == [(dfx, 1), (dfy, 1)]
    d2fx = dfx.diff(x)
    assert vsort([(d2fx, 1), (dfx, 1)]) == [(dfx, 1), (d2fx, 1)]
Пример #17
0
def test_Float():
    def eq(a, b):
        t = Float("1.0E-15")
        return -t < a - b < t

    a = Float(2) ** Float(3)
    assert eq(a.evalf(), Float(8))
    assert eq((pi ** -1).evalf(), Float("0.31830988618379067"))
    a = Float(2) ** Float(4)
    assert eq(a.evalf(), Float(16))
    assert (S(0.3) == S(0.5)) is False
    x_str = Float((0, "13333333333333", -52, 53))
    x2_str = Float((0, "26666666666666", -53, 53))
    x_hex = Float((0, 0x13333333333333L, -52, 53))
    x_dec = Float((0, 5404319552844595L, -52, 53))
    x2_hex = Float((0, 0x13333333333333L * 2, -53, 53))
    assert x_str == x_hex == x_dec == x2_hex == Float(1.2)
    # x2_str and 1.2 are superficially the same
    assert str(x2_str) == str(Float(1.2))
    # but are different at the mpf level
    assert Float(1.2)._mpf_ == (0, 5404319552844595L, -52, 53)
    assert x2_str._mpf_ == (0, 10808639105689190L, -53, 53)

    assert Float((0, 0L, -123, -1)) == Float("nan")
    assert Float((0, 0L, -456, -2)) == Float("inf") == Float("+inf")
    assert Float((1, 0L, -789, -3)) == Float("-inf")

    raises(ValueError, lambda: Float((0, 7, 1, 3), ""))

    assert Float("+inf").is_bounded is False
    assert Float("+inf").is_finite is False
    assert Float("+inf").is_negative is False
    assert Float("+inf").is_positive is True
    assert Float("+inf").is_unbounded is True
    assert Float("+inf").is_zero is False

    assert Float("-inf").is_bounded is False
    assert Float("-inf").is_finite is False
    assert Float("-inf").is_negative is True
    assert Float("-inf").is_positive is False
    assert Float("-inf").is_unbounded is True
    assert Float("-inf").is_zero is False

    assert Float("0.0").is_bounded is True
    assert Float("0.0").is_finite is False
    assert Float("0.0").is_negative is False
    assert Float("0.0").is_positive is False
    assert Float("0.0").is_unbounded is False
    assert Float("0.0").is_zero is True

    # do not automatically evalf
    def teq(a):
        assert (a.evalf() == a) is False
        assert (a.evalf() != a) is True
        assert (a == a.evalf()) is False
        assert (a != a.evalf()) is True

    teq(pi)
    teq(2 * pi)
    teq(cos(0.1, evaluate=False))

    i = 12345678901234567890
    assert _aresame(Float(12, ""), Float("12", ""))
    assert _aresame(Float(Integer(i), ""), Float(i, ""))
    assert _aresame(Float(i, ""), Float(str(i), 20))
    assert not _aresame(Float(str(i)), Float(i, ""))

    # inexact floats (repeating binary = denom not multiple of 2)
    # cannot have precision greater than 15
    assert Float(0.125, 22) == 0.125
    assert Float(2.0, 22) == 2
    assert float(Float(".12500000000000001", "")) == 0.125
    raises(ValueError, lambda: Float(0.12500000000000001, ""))

    # allow spaces
    Float("123 456.123 456") == Float("123456.123456")
    Integer("123 456") == Integer("123456")
    Rational("123 456.123 456") == Rational("123456.123456")
    assert Float(" .3e2") == Float("0.3e2")

    # allow auto precision detection
    assert Float(".1", "") == Float(0.1, 1)
    assert Float(".125", "") == Float(0.125, 3)
    assert Float(".100", "") == Float(0.1, 3)
    assert Float("2.0", "") == Float("2", 2)

    raises(ValueError, lambda: Float("12.3d-4", ""))
    raises(ValueError, lambda: Float(12.3, ""))
    raises(ValueError, lambda: Float("."))
    raises(ValueError, lambda: Float("-."))

    zero = Float("0.0")
    assert Float("-0") == zero
    assert Float(".0") == zero
    assert Float("-.0") == zero
    assert Float("-0.0") == zero
    assert Float(0.0) == zero
    assert Float(0) == zero
    assert Float(0, "") == Float("0", "")
    assert Float(1) == Float(1.0)
    assert Float(S.Zero) == zero
    assert Float(S.One) == Float(1.0)

    assert Float(decimal.Decimal("0.1"), 3) == Float(".1", 3)
Пример #18
0
def test_sort_variable():
    vsort = Derivative._sort_variable_count

    def vsort0(*v, **kw):
        reverse = kw.get('reverse', False)
        return [
            i[0]
            for i in vsort([(i, 0) for i in (reversed(v) if reverse else v)])
        ]

    for R in range(2):
        assert vsort0(y, x, reverse=R) == [x, y]
        assert vsort0(f(x), x, reverse=R) == [x, f(x)]
        assert vsort0(f(y), f(x), reverse=R) == [f(x), f(y)]
        assert vsort0(g(x), f(y), reverse=R) == [f(y), g(x)]
        assert vsort0(f(x, y), f(x), reverse=R) == [f(x), f(x, y)]
        fx = f(x).diff(x)
        assert vsort0(fx, y, reverse=R) == [y, fx]
        fy = f(y).diff(y)
        assert vsort0(fy, fx, reverse=R) == [fx, fy]
        fxx = fx.diff(x)
        assert vsort0(fxx, fx, reverse=R) == [fx, fxx]
        assert vsort0(Basic(x), f(x), reverse=R) == [f(x), Basic(x)]
        assert vsort0(Basic(y), Basic(x), reverse=R) == [Basic(x), Basic(y)]
        assert vsort0(Basic(y, z), Basic(x),
                      reverse=R) == [Basic(x), Basic(y, z)]
        assert vsort0(fx, x, reverse=R) == [x, fx] if R else [fx, x]
        assert vsort0(Basic(x), x, reverse=R) == [x, Basic(x)
                                                  ] if R else [Basic(x), x]
        assert vsort0(Basic(f(x)), f(x), reverse=R) == [
            f(x), Basic(f(x))
        ] if R else [Basic(f(x)), f(x)]
        assert vsort0(Basic(x, z), Basic(x), reverse=R) == [
            Basic(x), Basic(x, z)
        ] if R else [Basic(x, z), Basic(x)]
    assert vsort([]) == []
    assert _aresame(vsort([(x, 1)]), [Tuple(x, 1)])
    assert vsort([(x, y), (x, z)]) == [(x, y + z)]
    assert vsort([(y, 1), (x, 1 + y)]) == [(x, 1 + y), (y, 1)]
    # coverage complete; legacy tests below
    assert vsort([(x, 3), (y, 2), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
    assert vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) == [(f(x), 1), (g(x), 1),
                                                        (h(x), 1)]
    assert vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1),
                  (f(x), 1)]) == [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1),
                                  (h(x), 1)]
    assert vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) == [(x, 1), (y, 1),
                                                             (f(x), 1),
                                                             (f(y), 1)]
    assert vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1), (h(x), 1),
                  (y, 2), (x, 1)]) == [(x, 3), (y, 3), (z, 1), (f(x), 1),
                                       (g(x), 1), (h(x), 1)]
    assert vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1),
                  (g(x), 1)]) == [(x, 1), (y, 1), (z, 1), (f(x), 2), (g(x), 1)]
    assert vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2), (g(x), 1),
                  (z, 2), (z, 1), (y, 1), (x, 1)]) == [(x, 3), (y, 3), (z, 4),
                                                       (f(x), 3), (g(x), 1)]
    assert vsort(((y, 2), (x, 1), (y, 1), (x, 1))) == [(x, 2), (y, 3)]
    assert isinstance(vsort([(x, 3), (y, 2), (z, 1)])[0], Tuple)
    assert vsort([(x, 1), (f(x), 1), (x, 1)]) == [(x, 2), (f(x), 1)]
    assert vsort([(y, 2), (x, 3), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
    assert vsort([(h(y), 1), (g(x), 1), (f(x), 1)]) == [(f(x), 1), (g(x), 1),
                                                        (h(y), 1)]
    assert vsort([(x, 1), (y, 1), (x, 1)]) == [(x, 2), (y, 1)]
    assert vsort([(f(x), 1), (f(y), 1), (f(x), 1)]) == [(f(x), 2), (f(y), 1)]
    dfx = f(x).diff(x)
    self = [(dfx, 1), (x, 1)]
    assert vsort(self) == self
    assert vsort([(dfx, 1), (y, 1), (f(x), 1), (x, 1), (f(y), 1),
                  (x, 1)]) == [(y, 1), (f(x), 1), (f(y), 1), (dfx, 1), (x, 2)]
    dfy = f(y).diff(y)
    assert vsort([(dfy, 1), (dfx, 1)]) == [(dfx, 1), (dfy, 1)]
    d2fx = dfx.diff(x)
    assert vsort([(d2fx, 1), (dfx, 1)]) == [(dfx, 1), (d2fx, 1)]
Пример #19
0
def test__aresame():
    assert not _aresame(Basic([]), Basic())
    assert not _aresame(Basic([]), Basic(()))
    assert not _aresame(Basic(2), Basic(2.))
Пример #20
0
def test_Float():
    def eq(a, b):
        t = Float("1.0E-15")
        return (-t < a - b < t)

    a = Float(2)**Float(3)
    assert eq(a.evalf(), Float(8))
    assert eq((pi**-1).evalf(), Float("0.31830988618379067"))
    a = Float(2)**Float(4)
    assert eq(a.evalf(), Float(16))
    assert (S(.3) == S(.5)) is False
    x_str = Float((0, '13333333333333', -52, 53))
    x2_str = Float((0, '26666666666666', -53, 53))
    x_hex = Float((0, 0x13333333333333L, -52, 53))
    x_dec = Float((0, 5404319552844595L, -52, 53))
    x2_hex = Float((0, 0x13333333333333L * 2, -53, 53))
    assert x_str == x_hex == x_dec == x2_hex == Float(1.2)
    # x2_str and 1.2 are superficially the same
    assert str(x2_str) == str(Float(1.2))
    # but are different at the mpf level
    assert Float(1.2)._mpf_ == (0, 5404319552844595L, -52, 53)
    assert x2_str._mpf_ == (0, 10808639105689190L, -53, 53)

    assert Float((0, 0L, -123, -1)) == Float('nan')
    assert Float((0, 0L, -456, -2)) == Float('inf') == Float('+inf')
    assert Float((1, 0L, -789, -3)) == Float('-inf')

    # do not automatically evalf
    def teq(a):
        assert (a.evalf() == a) is False
        assert (a.evalf() != a) is True
        assert (a == a.evalf()) is False
        assert (a != a.evalf()) is True

    teq(pi)
    teq(2 * pi)
    teq(cos(0.1, evaluate=False))

    assert Float(0) is S.Zero
    assert Float(1) is S.One

    assert Float(S.Zero) is S.Zero
    assert Float(S.One) is S.One

    i = 12345678901234567890
    assert _aresame(Float(12), Integer(12))
    assert _aresame(Float(12, ''), Float('12', ''))
    assert _aresame(Float(i), Integer(i))
    assert _aresame(Float(Integer(i), ''), Float(i, ''))
    assert _aresame(Float(i, ''), Float(str(i), 20))
    assert not _aresame(Float(str(i)), Float(i, ''))

    # inexact floats (repeating binary = denom not multiple of 2)
    # cannot have precision greater than 15
    assert Float(.125, 22) == .125
    assert Float(2.0, 22) == 2
    assert float(Float('.12500000000000001', '')) == .125
    raises(ValueError, lambda: Float(.12500000000000001, ''))

    # allow spaces
    Float('123 456.123 456') == Float('123456.123456')
    Integer('123 456') == Integer('123456')
    Rational('123 456.123 456') == Rational('123456.123456')

    # allow auto precision detection
    assert Float('.1', '') == Float(.1, 1)
    assert Float('.125', '') == Float(.125, 3)
    assert Float('.100', '') == Float(.1, 3)
    assert Float('2.0', '') == Float('2', 2)

    raises(ValueError, lambda: Float("12.3d-4", ""))
    raises(ValueError, lambda: Float(12.3, ""))
    raises(ValueError, lambda: Float('.'))
    raises(ValueError, lambda: Float('-.'))
    assert Float('-0') == Float('0.0')
    assert Float('.0') == Float('0.0')
    assert Float('-.0') == Float('-0.0')
    assert Float(' .3e2') == Float('0.3e2')
Пример #21
0
def test_nfloat():
    from sympy.core.basic import _aresame
    from sympy.polys.rootoftools import rootof

    x = Symbol("x")
    eq = x**Rational(4, 3) + 4 * x**(S.One / 3) / 3
    assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0 / 3) * x**(S.One / 3))
    assert _aresame(nfloat(eq, exponent=True),
                    x**(4.0 / 3) + (4.0 / 3) * x**(1.0 / 3))
    eq = x**Rational(4, 3) + 4 * x**(x / 3) / 3
    assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0 / 3) * x**(x / 3))
    big = 12345678901234567890
    # specify precision to match value used in nfloat
    Float_big = Float(big, 15)
    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(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2)))

    # issue 6342
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139)))

    # issue 6632
    assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
        9.99999999800000e-11

    # issue 7122
    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 ti in (dict, Dict):
        d = ti({S.Half: S.Half})
        n = nfloat(d)
        assert isinstance(n, ti)
        assert _aresame(list(n.items()).pop(), (S.Half, Float(.5)))
    for ti in (dict, Dict):
        d = ti({S.Half: S.Half})
        n = nfloat(d, dkeys=True)
        assert isinstance(n, ti)
        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}]

    # Issue 17706
    A = MutableMatrix([[1, 2], [3, 4]])
    B = MutableMatrix(
        [[Float('1.0', precision=53),
          Float('2.0', precision=53)],
         [Float('3.0', precision=53),
          Float('4.0', precision=53)]])
    assert _aresame(nfloat(A), B)
    A = ImmutableMatrix([[1, 2], [3, 4]])
    B = ImmutableMatrix(
        [[Float('1.0', precision=53),
          Float('2.0', precision=53)],
         [Float('3.0', precision=53),
          Float('4.0', precision=53)]])
    assert _aresame(nfloat(A), B)
Пример #22
0
def test_Float():
    def eq(a, b):
        t = Float("1.0E-15")
        return (-t < a-b < t)

    a = Float(2) ** Float(3)
    assert eq(a.evalf(), Float(8))
    assert eq((pi ** -1).evalf(), Float("0.31830988618379067"))
    a = Float(2) ** Float(4)
    assert eq(a.evalf(), Float(16))
    assert (S(.3) == S(.5)) is False
    x_str = Float((0, '13333333333333', -52, 53))
    x2_str = Float((0, '26666666666666', -53, 53))
    x_hex = Float((0, 0x13333333333333L, -52, 53))
    x_dec = Float((0, 5404319552844595L, -52, 53))
    x2_hex = Float((0, 0x13333333333333L*2, -53, 53))
    assert x_str == x_hex == x_dec == x2_hex == Float(1.2)
    # x2_str and 1.2 are superficially the same
    assert str(x2_str) == str(Float(1.2))
    # but are different at the mpf level
    assert Float(1.2)._mpf_ == (0, 5404319552844595L, -52, 53)
    assert x2_str._mpf_ == (0, 10808639105689190L, -53, 53)

    assert Float((0, 0L, -123, -1)) == Float('nan')
    assert Float((0, 0L, -456, -2)) == Float('inf') == Float('+inf')
    assert Float((1, 0L, -789, -3)) == Float('-inf')

    # do not automatically evalf
    def teq(a):
        assert (a.evalf () == a) is False
        assert (a.evalf () != a) is True
        assert (a == a.evalf()) is False
        assert (a != a.evalf()) is True

    teq(pi)
    teq(2*pi)
    teq(cos(0.1, evaluate=False))

    assert Float(0) is S.Zero
    assert Float(1) is S.One

    assert Float(S.Zero) is S.Zero
    assert Float(S.One) is S.One

    i = 12345678901234567890
    assert _aresame(Float(12), Integer(12))
    assert _aresame(Float(12, ''), Float('12', ''))
    assert _aresame(Float(i), Integer(i))
    assert _aresame(Float(Integer(i), ''), Float(i, ''))
    assert _aresame(Float(i, ''), Float(str(i), 20))
    assert not _aresame(Float(str(i)), Float(i, ''))

    # inexact floats (repeating binary = denom not multiple of 2)
    # cannot have precision greater than 15
    assert Float(.125, 22) == .125
    assert Float(2.0, 22) == 2
    assert float(Float('.12500000000000001', '')) == .125
    raises(ValueError, lambda: Float(.12500000000000001, ''))

    # allow spaces
    Float('123 456.123 456') == Float('123456.123456')
    Integer('123 456') == Integer('123456')
    Rational('123 456.123 456') == Rational('123456.123456')

    # allow auto precision detection
    assert Float('.1', '') == Float(.1, 1)
    assert Float('.125', '') == Float(.125, 3)
    assert Float('.100', '') == Float(.1, 3)
    assert Float('2.0', '') == Float('2', 2)

    raises(ValueError, lambda: Float("12.3d-4", ""))
    raises(ValueError, lambda:Float(12.3, ""))
    raises(ValueError, lambda:Float('.'))
    raises(ValueError, lambda:Float('-.'))
    assert Float('-0') == Float('0.0')
    assert Float('.0') == Float('0.0')
    assert Float('-.0') == Float('-0.0')
    assert Float(' .3e2') == Float('0.3e2')