Exemple #1
0
def third_method(func, start, finish, eps):
    left_result = eval(func.replace('x', str(start)))
    x = symbols('x')
    diff2 = diff(func, x, x)
    left_diff2 = eval(str(diff2).replace('x', str(start)))
    if left_result * left_diff2 > 0:
        last_x = start
    else:
        right_diff2 = eval(str(diff2).replace('x', str(finish)))
        right_result = eval(func.replace('x', str(finish)))
        if right_diff2 * right_result > 0:
            last_x = finish
        else:
            last_x = start
            print("approximation is impossible")
    i = 0
    while True:
        i += 1
        diff1 = diff(func, x)
        result_diff1 = eval(str(diff1).replace('x', str(last_x)))
        result_last_x = eval(func.replace('x', str(last_x)))
        new_x = last_x - result_last_x / result_diff1
        new_result_x = eval(func.replace('x', str(new_x)))
        if abs(new_x - last_x) < eps and abs(new_result_x) < eps:
            break
        last_x = new_x

    down = maximum(diff(func, x, x), x, Interval(start, finish)) / \
        (2*minimum(diff(func, x), x, Interval(start, finish)))
    up = 2**i - 1
    error = (down**up) * (abs(finish - start)**(2 * i))
    with open('result.txt', 'w') as f:
        f.write(f'The root of the function is = {new_x}\n')
        f.write(f'The possible inaccuracy = {error}')
Exemple #2
0
def test_is_decreasing():
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.open(1.5, 3))
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.Ropen(-oo,
                                                            S(3) / 2)) is False
    assert is_decreasing(-x**2, Interval(-oo, 0)) is False
    assert is_decreasing(-x**2 * b, Interval(-oo, 0), x) is False
Exemple #3
0
def pow_sets(x, y):
    """
    Powers in interval arithmetic
    https://en.wikipedia.org/wiki/Interval_arithmetic
    """
    exponent = sympify(exponent)
    if exponent.is_odd:
        return Interval(x.start**exponent, x.end**exponent, x.left_open,
                        x.right_open)
    if exponent.is_even:
        if (x.start * x.end).is_negative:
            if -x.start > x.end:
                left_limit = x.start
                left_open = x.right_open
            else:
                left_limit = x.end
                left_open = x.left_open
            return Interval(S.Zero, left_limit**exponent, S.Zero not in x,
                            left_open)
        elif x.start.is_negative and x.end.is_negative:
            return Interval(x.end**exponent, x.start**exponent, x.right_open,
                            x.left_open)
        else:
            return Interval(x.start**exponent, x.end**exponent, x.left_open,
                            x.right_open)
Exemple #4
0
def test_is_increasing():
    assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
    assert is_increasing(-x**2, Interval(-oo, 0))
    assert is_increasing(-x**2, Interval(0, oo)) is False
    assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False
    assert is_increasing(x**2 + y, Interval(1, oo), x) is True
    assert is_increasing(-x**2*a, Interval(1, oo), x) is True
    assert is_increasing(1) is True
Exemple #5
0
def test_is_decreasing():
    """Test whether is_decreasing returns correct value."""
    b = Symbol('b', positive=True)

    assert is_decreasing(1 / (x**2 - 3 * x), Interval.open(1.5, 3))
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert not is_decreasing(1 / (x**2 - 3 * x), Interval.Ropen(-oo, S(3) / 2))
    assert not is_decreasing(-x**2, Interval(-oo, 0))
    assert not is_decreasing(-x**2 * b, Interval(-oo, 0), x)
def test_SetExpr_Intersection():
    x, y, z, w = symbols("x y z w")
    set1 = Interval(x, y)
    set2 = Interval(w, z)
    inter = Intersection(set1, set2)
    se = SetExpr(inter)
    assert exp(se).set == Intersection(ImageSet(Lambda(x, exp(x)), set1),
                                       ImageSet(Lambda(x, exp(x)), set2))
    assert cos(se).set == ImageSet(Lambda(x, cos(x)), inter)
Exemple #7
0
def test_is_decreasing():
    """Test whether is_decreasing returns correct value."""
    b = Symbol("b", positive=True)

    assert is_decreasing(1 / (x**2 - 3 * x), Interval.open(1.5, 3))
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert not is_decreasing(1 / (x**2 - 3 * x),
                             Interval.Ropen(-oo, Rational(3, 2)))
    assert not is_decreasing(-(x**2), Interval(-oo, 0))
    assert not is_decreasing(-(x**2) * b, Interval(-oo, 0), x)
def test_scalar_funcs():
    assert SetExpr(Interval(0, 1)).set == Interval(0, 1)
    a, b = Symbol('a', real=True), Symbol('b', real=True)
    a, b = 1, 2
    # TODO: add support for more functions in the future:
    for f in [exp, log]:
        input_se = f(SetExpr(Interval(a, b)))
        output = input_se.set
        expected = Interval(Min(f(a), f(b)), Max(f(a), f(b)))
        assert output == expected
Exemple #9
0
def div_sets(x, y):
    """
    Divisions in interval arithmetic
    https://en.wikipedia.org/wiki/Interval_arithmetic
    """
    if (y.start * y.end).is_negative:
        from sympy import oo
        return Interval(-oo, oo)
    return mul_sets(
        x, Interval(1 / y.end, 1 / y.start, y.right_open, y.left_open))
def test_is_increasing():
    """Test whether is_increasing returns correct value."""
    a = Symbol('a', negative=True)

    assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
    assert is_increasing(-x**2, Interval(-oo, 0))
    assert not is_increasing(-x**2, Interval(0, oo))
    assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
    assert is_increasing(x**2 + y, Interval(1, oo), x)
    assert is_increasing(-x**2*a, Interval(1, oo), x)
    assert is_increasing(1)
Exemple #11
0
def solve_univariate_inequality(expr, gen, assume=True, relational=True):
    """Solves a real univariate inequality.

    Examples
    ========

    >>> from sympy.solvers.inequalities import solve_univariate_inequality
    >>> from sympy.core.symbol import Symbol
    >>> x = Symbol('x', real=True)

    >>> solve_univariate_inequality(x**2 >= 4, x)
    Or(And(-oo < x, x <= -2), And(2 <= x, x < oo))

    >>> solve_univariate_inequality(x**2 >= 4, x, relational=False)
    (-oo, -2] U [2, oo)

    """

    # Implementation for continous functions

    from sympy.solvers.solvers import solve

    solns = solve(expr.lhs - expr.rhs, gen, assume=assume)
    oo = S.Infinity

    start = -oo

    sol_sets = [S.EmptySet]

    for x in sorted(s for s in solns if s.is_real):
        end = x
        if simplify(
                expr.subs(gen,
                          (start + end) / 2 if start != -oo else end - 1)):
            sol_sets.append(Interval(start, end, True, True))

        if simplify(expr.subs(gen, x)):
            sol_sets.append(FiniteSet(x))

        start = end

    end = oo

    if simplify(expr.subs(gen, start + 1)):
        sol_sets.append(Interval(start, end, True, True))

    rv = Union(*sol_sets)
    return rv if not relational else rv.as_relational(gen)
Exemple #12
0
def _(x, y):
    """
    Subtractions in interval arithmetic
    https://en.wikipedia.org/wiki/Interval_arithmetic
    """
    return Interval(x.start - y.end, x.end - y.start, x.left_open
                    or y.right_open, x.right_open or y.left_open)
Exemple #13
0
def mul_sets(x, y):
    """
    Multiplications in interval arithmetic
    https://en.wikipedia.org/wiki/Interval_arithmetic
    """
    comvals = (
        (x.start * y.start, bool(x.left_open or y.left_open)),
        (x.start * y.end, bool(x.left_open or y.right_open)),
        (x.end * y.start, bool(x.right_open or y.left_open)),
        (x.end * y.end, bool(x.right_open or y.right_open)),
    )
    # TODO: handle symbolic intervals
    minval, minopen = min(comvals)
    maxval, maxopen = max(comvals)
    return Interval(minval, maxval, minopen, maxopen)
    return SetExpr(Interval(start, end))
Exemple #14
0
def test_is_strictly_decreasing():
    """Test whether is_strictly_decreasing returns correct value."""
    assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
    assert not is_strictly_decreasing(
        1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
    assert not is_strictly_decreasing(-x**2, Interval(-oo, 0))
    assert not is_strictly_decreasing(1)
Exemple #15
0
def test_is_monotonic():
    """Test whether is_monotonic returns correct value."""
    assert is_monotonic(1 / (x**2 - 3 * x), Interval.open(1.5, 3))
    assert is_monotonic(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert is_monotonic(x**3 - 3 * x**2 + 4 * x, S.Reals)
    assert not is_monotonic(-x**2, S.Reals)
    assert is_monotonic(x**2 + y + 1, Interval(1, 2), x)
Exemple #16
0
def test_is_strictly_decreasing():
    assert is_strictly_decreasing(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert is_strictly_decreasing(1 / (x**2 - 3 * x),
                                  Interval.Ropen(-oo,
                                                 S(3) / 2)) is False
    assert is_strictly_decreasing(-x**2, Interval(-oo, 0)) is False
    assert is_strictly_decreasing(1) is False
Exemple #17
0
def test_singularities():
    x = Symbol('x')
    assert singularities(x**2, x) == S.EmptySet
    assert singularities(x / (x**2 + 3 * x + 2), x) == FiniteSet(-2, -1)
    assert singularities(1 / (x**2 + 1), x) == FiniteSet(I, -I)
    assert singularities(x/(x**3 + 1), x) == \
        FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2)
    assert singularities(1/(y**2 + 2*I*y + 1), y) == \
        FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I)

    x = Symbol('x', real=True)
    assert singularities(1 / (x**2 + 1), x) == S.EmptySet
    assert singularities(exp(1 / x), x, S.Reals) == FiniteSet(0)
    assert singularities(exp(1 / x), x, Interval(1, 2)) == S.EmptySet
    assert singularities(log((x - 2)**2), x, Interval(1, 3)) == FiniteSet(2)
    raises(NotImplementedError, lambda: singularities(x**-oo, x))
Exemple #18
0
def _set_add(x, y):
    """
    Additions in interval arithmetic
    https://en.wikipedia.org/wiki/Interval_arithmetic
    """
    return Interval(x.start + y.start, x.end + y.end, x.left_open
                    or y.left_open, x.right_open or y.right_open)
Exemple #19
0
def test_is_monotonic():
    """Test whether is_monotonic returns correct value."""
    assert is_monotonic(1 / (x**2 - 3 * x), Interval.open(1.5, 3))
    assert is_monotonic(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert is_monotonic(x**3 - 3 * x**2 + 4 * x, S.Reals)
    assert not is_monotonic(-(x**2), S.Reals)
    assert is_monotonic(x**2 + y + 1, Interval(1, 2), x)
    raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1))
Exemple #20
0
def test_is_strictly_decreasing():
    """Test whether is_strictly_decreasing returns correct value."""
    assert is_strictly_decreasing(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert not is_strictly_decreasing(1 / (x**2 - 3 * x),
                                      Interval.Ropen(-oo, Rational(3, 2)))
    assert not is_strictly_decreasing(-(x**2), Interval(-oo, 0))
    assert not is_strictly_decreasing(1)
    assert is_strictly_decreasing(1 / (x**2 - 3 * x), Interval.open(1.5, 3))
Exemple #21
0
def _set_mul(x, y):
    """
    Multiplications in interval arithmetic
    https://en.wikipedia.org/wiki/Interval_arithmetic
    """
    # TODO: some intervals containing 0 and oo will fail as 0*oo returns nan.
    comvals = (
        (x.start * y.start, bool(x.left_open or y.left_open)),
        (x.start * y.end, bool(x.left_open or y.right_open)),
        (x.end * y.start, bool(x.right_open or y.left_open)),
        (x.end * y.end, bool(x.right_open or y.right_open)),
    )
    # TODO: handle symbolic intervals
    minval, minopen = min(comvals)
    maxval, maxopen = max(comvals)
    return Interval(minval, maxval, minopen, maxopen)
    return SetExpr(Interval(start, end))
Exemple #22
0
def test_is_strictly_increasing():
    assert is_strictly_increasing(4 * x**3 - 6 * x**2 - 72 * x + 30,
                                  Interval.Ropen(-oo, -2))
    assert is_strictly_increasing(4 * x**3 - 6 * x**2 - 72 * x + 30,
                                  Interval.Lopen(3, oo))
    assert is_strictly_increasing(4 * x**3 - 6 * x**2 - 72 * x + 30,
                                  Interval.open(-2, 3)) is False
    assert is_strictly_increasing(-x**2, Interval(0, oo)) is False
Exemple #23
0
def _set_div(x, y):
    """
    Divisions in interval arithmetic
    https://en.wikipedia.org/wiki/Interval_arithmetic
    """
    from sympy.sets.setexpr import set_mul
    from sympy import oo
    if (y.start * y.end).is_negative:
        return Interval(-oo, oo)
    if y.start == 0:
        s2 = oo
    else:
        s2 = 1 / y.start
    if y.end == 0:
        s1 = -oo
    else:
        s1 = 1 / y.end
    return set_mul(x, Interval(s1, s2, y.right_open, y.left_open))
Exemple #24
0
def test_is_strictly_increasing():
    """Test whether is_strictly_increasing returns correct value."""
    assert is_strictly_increasing(4 * x**3 - 6 * x**2 - 72 * x + 30,
                                  Interval.Ropen(-oo, -2))
    assert is_strictly_increasing(4 * x**3 - 6 * x**2 - 72 * x + 30,
                                  Interval.Lopen(3, oo))
    assert not is_strictly_increasing(4 * x**3 - 6 * x**2 - 72 * x + 30,
                                      Interval.open(-2, 3))
    assert not is_strictly_increasing(-x**2, Interval(0, oo))
    assert not is_strictly_decreasing(1)
Exemple #25
0
def _set_pow(b, e):  # noqa:F811
    # TODO: add logic for open intervals?
    if b.start.is_nonnegative:
        if b.end < 1:
            return FiniteSet(S.Zero)
        if b.start > 1:
            return FiniteSet(S.Infinity)
        return Interval(0, oo)
    elif b.end.is_negative:
        if b.start > -1:
            return FiniteSet(S.Zero)
        if b.end < -1:
            return FiniteSet(-oo, oo)
        return Interval(-oo, oo)
    else:
        if b.start > -1:
            if b.end < 1:
                return FiniteSet(S.Zero)
            return Interval(0, oo)
        return Interval(-oo, oo)
Exemple #26
0
def solve_univariate_inequality(expr,
                                gen,
                                relational=True,
                                domain=S.Reals,
                                continuous=False):
    """Solves a real univariate inequality.

    Parameters
    ==========

    expr : Relational
        The target inequality
    gen : Symbol
        The variable for which the inequality is solved
    relational : bool
        A Relational type output is expected or not
    domain : Set
        The domain over which the equation is solved
    continuous: bool
        True if expr is known to be continuous over the given domain
        (and so continuous_domain() doesn't need to be called on it)

    Raises
    ======

    NotImplementedError
        The solution of the inequality cannot be determined due to limitation
        in `solvify`.

    Notes
    =====

    Currently, we cannot solve all the inequalities due to limitations in
    `solvify`. Also, the solution returned for trigonometric inequalities
    are restricted in its periodic interval.

    See Also
    ========

    solvify: solver returning solveset solutions with solve's output API

    Examples
    ========

    >>> from sympy.solvers.inequalities import solve_univariate_inequality
    >>> from sympy import Symbol, sin, Interval, S
    >>> x = Symbol('x')

    >>> solve_univariate_inequality(x**2 >= 4, x)
    ((2 <= x) & (x < oo)) | ((x <= -2) & (-oo < x))

    >>> solve_univariate_inequality(x**2 >= 4, x, relational=False)
    Union(Interval(-oo, -2), Interval(2, oo))

    >>> domain = Interval(0, S.Infinity)
    >>> solve_univariate_inequality(x**2 >= 4, x, False, domain)
    Interval(2, oo)

    >>> solve_univariate_inequality(sin(x) > 0, x, relational=False)
    Interval.open(0, pi)

    """
    from sympy import im
    from sympy.calculus.util import (continuous_domain, periodicity,
                                     function_range)
    from sympy.solvers.solvers import denoms
    from sympy.solvers.solveset import solveset_real, solvify, solveset
    from sympy.solvers.solvers import solve

    # This keeps the function independent of the assumptions about `gen`.
    # `solveset` makes sure this function is called only when the domain is
    # real.
    _gen = gen
    _domain = domain
    if gen.is_real is False:
        rv = S.EmptySet
        return rv if not relational else rv.as_relational(_gen)
    elif gen.is_real is None:
        gen = Dummy('gen', real=True)
        try:
            expr = expr.xreplace({_gen: gen})
        except TypeError:
            raise TypeError(
                filldedent('''
                When gen is real, the relational has a complex part
                which leads to an invalid comparison like I < 0.
                '''))

    rv = None

    if expr is S.true:
        rv = domain

    elif expr is S.false:
        rv = S.EmptySet

    else:
        e = expr.lhs - expr.rhs
        period = periodicity(e, gen)
        if period is S.Zero:
            e = expand_mul(e)
            const = expr.func(e, 0)
            if const is S.true:
                rv = domain
            elif const is S.false:
                rv = S.EmptySet
        elif period is not None:
            frange = function_range(e, gen, domain)

            rel = expr.rel_op
            if rel == '<' or rel == '<=':
                if expr.func(frange.sup, 0):
                    rv = domain
                elif not expr.func(frange.inf, 0):
                    rv = S.EmptySet

            elif rel == '>' or rel == '>=':
                if expr.func(frange.inf, 0):
                    rv = domain
                elif not expr.func(frange.sup, 0):
                    rv = S.EmptySet

            inf, sup = domain.inf, domain.sup
            if sup - inf is S.Infinity:
                domain = Interval(0, period, False, True)

        if rv is None:
            n, d = e.as_numer_denom()
            try:
                if gen not in n.free_symbols and len(e.free_symbols) > 1:
                    raise ValueError
                # this might raise ValueError on its own
                # or it might give None...
                solns = solvify(e, gen, domain)
                if solns is None:
                    # in which case we raise ValueError
                    raise ValueError
            except (ValueError, NotImplementedError):
                # replace gen with generic x since it's
                # univariate anyway
                raise NotImplementedError(
                    filldedent('''
                    The inequality, %s, cannot be solved using
                    solve_univariate_inequality.
                    ''' % expr.subs(gen, Symbol('x'))))

            expanded_e = expand_mul(e)

            def valid(x):
                # this is used to see if gen=x satisfies the
                # relational by substituting it into the
                # expanded form and testing against 0, e.g.
                # if expr = x*(x + 1) < 2 then e = x*(x + 1) - 2
                # and expanded_e = x**2 + x - 2; the test is
                # whether a given value of x satisfies
                # x**2 + x - 2 < 0
                #
                # expanded_e, expr and gen used from enclosing scope
                v = expanded_e.subs(gen, expand_mul(x))
                try:
                    r = expr.func(v, 0)
                except TypeError:
                    r = S.false
                if r in (S.true, S.false):
                    return r
                if v.is_real is False:
                    return S.false
                else:
                    v = v.n(2)
                    if v.is_comparable:
                        return expr.func(v, 0)
                    # not comparable or couldn't be evaluated
                    raise NotImplementedError(
                        'relationship did not evaluate: %s' % r)

            singularities = []
            for d in denoms(expr, gen):
                singularities.extend(solvify(d, gen, domain))
            if not continuous:
                domain = continuous_domain(expanded_e, gen, domain)

            include_x = '=' in expr.rel_op and expr.rel_op != '!='

            try:
                discontinuities = set(domain.boundary -
                                      FiniteSet(domain.inf, domain.sup))
                # remove points that are not between inf and sup of domain
                critical_points = FiniteSet(
                    *(solns + singularities +
                      list(discontinuities))).intersection(
                          Interval(domain.inf, domain.sup, domain.inf
                                   not in domain, domain.sup not in domain))
                if all(r.is_number for r in critical_points):
                    reals = _nsort(critical_points, separated=True)[0]
                else:
                    from sympy.utilities.iterables import sift
                    sifted = sift(critical_points, lambda x: x.is_real)
                    if sifted[None]:
                        # there were some roots that weren't known
                        # to be real
                        raise NotImplementedError
                    try:
                        reals = sifted[True]
                        if len(reals) > 1:
                            reals = list(sorted(reals))
                    except TypeError:
                        raise NotImplementedError
            except NotImplementedError:
                raise NotImplementedError(
                    'sorting of these roots is not supported')

            # If expr contains imaginary coefficients, only take real
            # values of x for which the imaginary part is 0
            make_real = S.Reals
            if im(expanded_e) != S.Zero:
                check = True
                im_sol = FiniteSet()
                try:
                    a = solveset(im(expanded_e), gen, domain)
                    if not isinstance(a, Interval):
                        for z in a:
                            if z not in singularities and valid(
                                    z) and z.is_real:
                                im_sol += FiniteSet(z)
                    else:
                        start, end = a.inf, a.sup
                        for z in _nsort(critical_points + FiniteSet(end)):
                            valid_start = valid(start)
                            if start != end:
                                valid_z = valid(z)
                                pt = _pt(start, z)
                                if pt not in singularities and pt.is_real and valid(
                                        pt):
                                    if valid_start and valid_z:
                                        im_sol += Interval(start, z)
                                    elif valid_start:
                                        im_sol += Interval.Ropen(start, z)
                                    elif valid_z:
                                        im_sol += Interval.Lopen(start, z)
                                    else:
                                        im_sol += Interval.open(start, z)
                            start = z
                        for s in singularities:
                            im_sol -= FiniteSet(s)
                except (TypeError):
                    im_sol = S.Reals
                    check = False

                if isinstance(im_sol, EmptySet):
                    raise ValueError(
                        filldedent('''
                        %s contains imaginary parts which cannot be
                        made 0 for any value of %s satisfying the
                        inequality, leading to relations like I < 0.
                        ''' % (expr.subs(gen, _gen), _gen)))

                make_real = make_real.intersect(im_sol)

            empty = sol_sets = [S.EmptySet]

            start = domain.inf
            if valid(start) and start.is_finite:
                sol_sets.append(FiniteSet(start))

            for x in reals:
                end = x

                if valid(_pt(start, end)):
                    sol_sets.append(Interval(start, end, True, True))

                if x in singularities:
                    singularities.remove(x)
                else:
                    if x in discontinuities:
                        discontinuities.remove(x)
                        _valid = valid(x)
                    else:  # it's a solution
                        _valid = include_x
                    if _valid:
                        sol_sets.append(FiniteSet(x))

                start = end

            end = domain.sup
            if valid(end) and end.is_finite:
                sol_sets.append(FiniteSet(end))

            if valid(_pt(start, end)):
                sol_sets.append(Interval.open(start, end))

            if im(expanded_e) != S.Zero and check:
                rv = (make_real).intersect(_domain)
            else:
                rv = Intersection((Union(*sol_sets)), make_real,
                                  _domain).subs(gen, _gen)

    return rv if not relational else rv.as_relational(_gen)
Exemple #27
0
def solve_poly_inequality(poly, rel):
    """Solve a polynomial inequality with rational coefficients.

    Examples
    ========

    >>> from sympy import Poly
    >>> from sympy.abc import x
    >>> from sympy.solvers.inequalities import solve_poly_inequality

    >>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==')
    [{0}]

    >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=')
    [Interval.open(-oo, -1), Interval.open(-1, 1), Interval.open(1, oo)]

    >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==')
    [{-1}, {1}]

    See Also
    ========
    solve_poly_inequalities
    """
    if not isinstance(poly, Poly):
        raise ValueError(
            'For efficiency reasons, `poly` should be a Poly instance')
    if poly.is_number:
        t = Relational(poly.as_expr(), 0, rel)
        if t is S.true:
            return [S.Reals]
        elif t is S.false:
            return [S.EmptySet]
        else:
            raise NotImplementedError("could not determine truth value of %s" %
                                      t)

    reals, intervals = poly.real_roots(multiple=False), []

    if rel == '==':
        for root, _ in reals:
            interval = Interval(root, root)
            intervals.append(interval)
    elif rel == '!=':
        left = S.NegativeInfinity

        for right, _ in reals + [(S.Infinity, 1)]:
            interval = Interval(left, right, True, True)
            intervals.append(interval)
            left = right
    else:
        if poly.LC() > 0:
            sign = +1
        else:
            sign = -1

        eq_sign, equal = None, False

        if rel == '>':
            eq_sign = +1
        elif rel == '<':
            eq_sign = -1
        elif rel == '>=':
            eq_sign, equal = +1, True
        elif rel == '<=':
            eq_sign, equal = -1, True
        else:
            raise ValueError("'%s' is not a valid relation" % rel)

        right, right_open = S.Infinity, True

        for left, multiplicity in reversed(reals):
            if multiplicity % 2:
                if sign == eq_sign:
                    intervals.insert(
                        0, Interval(left, right, not equal, right_open))

                sign, right, right_open = -sign, left, not equal
            else:
                if sign == eq_sign and not equal:
                    intervals.insert(0, Interval(left, right, True,
                                                 right_open))
                    right, right_open = left, True
                elif sign != eq_sign and equal:
                    intervals.insert(0, Interval(left, left))

        if sign == eq_sign:
            intervals.insert(
                0, Interval(S.NegativeInfinity, right, True, right_open))

    return intervals
Exemple #28
0
def solve_rational_inequalities(eqs):
    """Solve a system of rational inequalities with rational coefficients.

    Examples
    ========

    >>> from sympy.abc import x
    >>> from sympy import Poly
    >>> from sympy.solvers.inequalities import solve_rational_inequalities

    >>> solve_rational_inequalities([[
    ... ((Poly(-x + 1), Poly(1, x)), '>='),
    ... ((Poly(-x + 1), Poly(1, x)), '<=')]])
    {1}

    >>> solve_rational_inequalities([[
    ... ((Poly(x), Poly(1, x)), '!='),
    ... ((Poly(-x + 1), Poly(1, x)), '>=')]])
    Union(Interval.open(-oo, 0), Interval.Lopen(0, 1))

    See Also
    ========
    solve_poly_inequality
    """
    result = S.EmptySet

    for _eqs in eqs:
        if not _eqs:
            continue

        global_intervals = [Interval(S.NegativeInfinity, S.Infinity)]

        for (numer, denom), rel in _eqs:
            numer_intervals = solve_poly_inequality(numer * denom, rel)
            denom_intervals = solve_poly_inequality(denom, '==')

            intervals = []

            for numer_interval in numer_intervals:
                for global_interval in global_intervals:
                    interval = numer_interval.intersect(global_interval)

                    if interval is not S.EmptySet:
                        intervals.append(interval)

            global_intervals = intervals

            intervals = []

            for global_interval in global_intervals:
                for denom_interval in denom_intervals:
                    global_interval -= denom_interval

                if global_interval is not S.EmptySet:
                    intervals.append(global_interval)

            global_intervals = intervals

            if not global_intervals:
                break

        for interval in global_intervals:
            result = result.union(interval)

    return result
def test_Interval_arithmetic():
    i12cc = SetExpr(Interval(1, 2))
    i12lo = SetExpr(Interval.Lopen(1, 2))
    i12ro = SetExpr(Interval.Ropen(1, 2))
    i12o = SetExpr(Interval.open(1, 2))

    n23cc = SetExpr(Interval(-2, 3))
    n23lo = SetExpr(Interval.Lopen(-2, 3))
    n23ro = SetExpr(Interval.Ropen(-2, 3))
    n23o = SetExpr(Interval.open(-2, 3))

    n3n2cc = SetExpr(Interval(-3, -2))

    assert i12cc + i12cc == SetExpr(Interval(2, 4))
    assert i12cc - i12cc == SetExpr(Interval(-1, 1))
    assert i12cc * i12cc == SetExpr(Interval(1, 4))
    assert i12cc / i12cc == SetExpr(Interval(S.Half, 2))
    assert i12cc**2 == SetExpr(Interval(1, 4))
    assert i12cc**3 == SetExpr(Interval(1, 8))

    assert i12lo + i12ro == SetExpr(Interval.open(2, 4))
    assert i12lo - i12ro == SetExpr(Interval.Lopen(-1, 1))
    assert i12lo * i12ro == SetExpr(Interval.open(1, 4))
    assert i12lo / i12ro == SetExpr(Interval.Lopen(S.Half, 2))
    assert i12lo + i12lo == SetExpr(Interval.Lopen(2, 4))
    assert i12lo - i12lo == SetExpr(Interval.open(-1, 1))
    assert i12lo * i12lo == SetExpr(Interval.Lopen(1, 4))
    assert i12lo / i12lo == SetExpr(Interval.open(S.Half, 2))
    assert i12lo + i12cc == SetExpr(Interval.Lopen(2, 4))
    assert i12lo - i12cc == SetExpr(Interval.Lopen(-1, 1))
    assert i12lo * i12cc == SetExpr(Interval.Lopen(1, 4))
    assert i12lo / i12cc == SetExpr(Interval.Lopen(S.Half, 2))
    assert i12lo + i12o == SetExpr(Interval.open(2, 4))
    assert i12lo - i12o == SetExpr(Interval.open(-1, 1))
    assert i12lo * i12o == SetExpr(Interval.open(1, 4))
    assert i12lo / i12o == SetExpr(Interval.open(S.Half, 2))
    assert i12lo**2 == SetExpr(Interval.Lopen(1, 4))
    assert i12lo**3 == SetExpr(Interval.Lopen(1, 8))

    assert i12ro + i12ro == SetExpr(Interval.Ropen(2, 4))
    assert i12ro - i12ro == SetExpr(Interval.open(-1, 1))
    assert i12ro * i12ro == SetExpr(Interval.Ropen(1, 4))
    assert i12ro / i12ro == SetExpr(Interval.open(S.Half, 2))
    assert i12ro + i12cc == SetExpr(Interval.Ropen(2, 4))
    assert i12ro - i12cc == SetExpr(Interval.Ropen(-1, 1))
    assert i12ro * i12cc == SetExpr(Interval.Ropen(1, 4))
    assert i12ro / i12cc == SetExpr(Interval.Ropen(S.Half, 2))
    assert i12ro + i12o == SetExpr(Interval.open(2, 4))
    assert i12ro - i12o == SetExpr(Interval.open(-1, 1))
    assert i12ro * i12o == SetExpr(Interval.open(1, 4))
    assert i12ro / i12o == SetExpr(Interval.open(S.Half, 2))
    assert i12ro**2 == SetExpr(Interval.Ropen(1, 4))
    assert i12ro**3 == SetExpr(Interval.Ropen(1, 8))

    assert i12o + i12lo == SetExpr(Interval.open(2, 4))
    assert i12o - i12lo == SetExpr(Interval.open(-1, 1))
    assert i12o * i12lo == SetExpr(Interval.open(1, 4))
    assert i12o / i12lo == SetExpr(Interval.open(S.Half, 2))
    assert i12o + i12ro == SetExpr(Interval.open(2, 4))
    assert i12o - i12ro == SetExpr(Interval.open(-1, 1))
    assert i12o * i12ro == SetExpr(Interval.open(1, 4))
    assert i12o / i12ro == SetExpr(Interval.open(S.Half, 2))
    assert i12o + i12cc == SetExpr(Interval.open(2, 4))
    assert i12o - i12cc == SetExpr(Interval.open(-1, 1))
    assert i12o * i12cc == SetExpr(Interval.open(1, 4))
    assert i12o / i12cc == SetExpr(Interval.open(S.Half, 2))
    assert i12o**2 == SetExpr(Interval.open(1, 4))
    assert i12o**3 == SetExpr(Interval.open(1, 8))

    assert n23cc + n23cc == SetExpr(Interval(-4, 6))
    assert n23cc - n23cc == SetExpr(Interval(-5, 5))
    assert n23cc * n23cc == SetExpr(Interval(-6, 9))
    assert n23cc / n23cc == SetExpr(Interval.open(-oo, oo))
    assert n23cc + n23ro == SetExpr(Interval.Ropen(-4, 6))
    assert n23cc - n23ro == SetExpr(Interval.Lopen(-5, 5))
    assert n23cc * n23ro == SetExpr(Interval.Ropen(-6, 9))
    assert n23cc / n23ro == SetExpr(Interval.Lopen(-oo, oo))
    assert n23cc + n23lo == SetExpr(Interval.Lopen(-4, 6))
    assert n23cc - n23lo == SetExpr(Interval.Ropen(-5, 5))
    assert n23cc * n23lo == SetExpr(Interval(-6, 9))
    assert n23cc / n23lo == SetExpr(Interval.open(-oo, oo))
    assert n23cc + n23o == SetExpr(Interval.open(-4, 6))
    assert n23cc - n23o == SetExpr(Interval.open(-5, 5))
    assert n23cc * n23o == SetExpr(Interval.open(-6, 9))
    assert n23cc / n23o == SetExpr(Interval.open(-oo, oo))
    assert n23cc**2 == SetExpr(Interval(0, 9))
    assert n23cc**3 == SetExpr(Interval(-8, 27))

    n32cc = SetExpr(Interval(-3, 2))
    n32lo = SetExpr(Interval.Lopen(-3, 2))
    n32ro = SetExpr(Interval.Ropen(-3, 2))
    assert n32cc * n32lo == SetExpr(Interval.Ropen(-6, 9))
    assert n32cc * n32cc == SetExpr(Interval(-6, 9))
    assert n32lo * n32cc == SetExpr(Interval.Ropen(-6, 9))
    assert n32cc * n32ro == SetExpr(Interval(-6, 9))
    assert n32lo * n32ro == SetExpr(Interval.Ropen(-6, 9))
    assert n32cc / n32lo == SetExpr(Interval.Ropen(-oo, oo))
    assert i12cc / n32lo == SetExpr(Interval.Ropen(-oo, oo))

    assert n3n2cc**2 == SetExpr(Interval(4, 9))
    assert n3n2cc**3 == SetExpr(Interval(-27, -8))

    assert n23cc + i12cc == SetExpr(Interval(-1, 5))
    assert n23cc - i12cc == SetExpr(Interval(-4, 2))
    assert n23cc * i12cc == SetExpr(Interval(-4, 6))
    assert n23cc / i12cc == SetExpr(Interval(-2, 3))
def test_Many_Sets():
    assert (SetExpr(Interval(0, 1)) + SetExpr(Interval(2, 3)) +
            SetExpr(FiniteSet(10, 11, 12))).set == Interval(12, 16)