コード例 #1
0
def test_RootOf___eval_Eq__():
    f = Function('f')
    r = RootOf(x**3 + x + 3, 2)
    r1 = RootOf(x**3 + x + 3, 1)
    assert Eq(r, r1) is false
    assert Eq(r, r) is true
    assert Eq(r, x) is false
    assert Eq(r, 0) is false
    assert Eq(r, oo) is false
    assert Eq(r, I) is false
    assert Eq(r, f(0)) is false
    assert Eq(r, f(0)) is false
    sol = solve(r.expr, x)
    for s in sol:
        if s[x].is_real:
            assert Eq(r, s[x]) is false
    r = RootOf(r.expr, 0)
    for s in sol:
        if s[x].is_real:
            assert Eq(r, s[x]) is true
    eq = x**3 + x + 1
    assert ([Eq(RootOf(eq, i), j[x])
             for i in range(3) for j in solve(eq)] ==
            [False, False, True, False, True, False, True, False, False])
    assert Eq(RootOf(eq, 0), 1 + I) is false
コード例 #2
0
def test_unrad_fail():
    # this only works if we check real_root(eq.subs(x, Rational(1, 3)))
    # but checksol doesn't work like that
    assert solve(root(x**3 - 3 * x**2, 3) + 1 - x) == [Rational(1, 3)]
    assert solve(root(x + 1, 3) + root(x**2 - 2, 5) + 1) == [
        -1, -1 + RootOf(x**5 + x**4 + 5 * x**3 + 8 * x**2 + 10 * x + 5, 0)**3
    ]
コード例 #3
0
ファイル: test_piecewise.py プロジェクト: fagan2888/diofant
def test_piecewise_solve():
    abs2 = Piecewise((-x, x <= 0), (x, x > 0))
    f = abs2.subs({x: x - 2})
    assert solve(f, x) == [{x: 2}]
    assert solve(f - 1, x) == [{x: 1}, {x: 3}]

    f = Piecewise(((x - 2)**2, x >= 0), (1, True))
    assert solve(f, x) == [{x: 2}]

    g = Piecewise(((x - 5)**5, x >= 4), (f, True))
    assert solve(g, x) == [{x: 2}, {x: 5}]

    g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
    assert solve(g, x) == [{x: 2}, {x: 5}]

    g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2))
    assert solve(g, x) == [{x: 5}]

    g = Piecewise(((x - 5)**5, x >= 2), (f, True))
    assert solve(g, x) == [{x: 5}]

    g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False))
    assert solve(g, x) == [{x: 5}]

    g = Piecewise(((x - 5)**5, x >= 2), (-x + 2, x - 2 <= 0),
                  (x - 2, x - 2 > 0))
    assert solve(g, x) == [{x: 5}]
コード例 #4
0
ファイル: test_piecewise.py プロジェクト: skirpichev/diofant
def test_piecewise_solve():
    abs2 = Piecewise((-x, x <= 0), (x, x > 0))
    f = abs2.subs({x: x - 2})
    assert solve(f, x) == [{x: 2}]
    assert solve(f - 1, x) == [{x: 1}, {x: 3}]

    f = Piecewise(((x - 2)**2, x >= 0), (1, True))
    assert solve(f, x) == [{x: 2}]

    g = Piecewise(((x - 5)**5, x >= 4), (f, True))
    assert solve(g, x) == [{x: 2}, {x: 5}]

    g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
    assert solve(g, x) == [{x: 2}, {x: 5}]

    g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2))
    assert solve(g, x) == [{x: 5}]

    g = Piecewise(((x - 5)**5, x >= 2), (f, True))
    assert solve(g, x) == [{x: 5}]

    g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False))
    assert solve(g, x) == [{x: 5}]

    g = Piecewise(((x - 5)**5, x >= 2),
                  (-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0))
    assert solve(g, x) == [{x: 5}]
コード例 #5
0
def test_piecewise_solve():
    abs2 = Piecewise((-x, x <= 0), (x, x > 0))
    f = abs2.subs(x, x - 2)
    assert solve(f, x) == [2]
    assert solve(f - 1, x) == [1, 3]

    f = Piecewise(((x - 2)**2, x >= 0), (1, True))
    assert solve(f, x) == [2]

    g = Piecewise(((x - 5)**5, x >= 4), (f, True))
    assert solve(g, x) == [2, 5]

    g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
    assert solve(g, x) == [2, 5]

    g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2))
    assert solve(g, x) == [5]

    g = Piecewise(((x - 5)**5, x >= 2), (f, True))
    assert solve(g, x) == [5]

    g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False))
    assert solve(g, x) == [5]

    g = Piecewise(((x - 5)**5, x >= 2), (-x + 2, x - 2 <= 0),
                  (x - 2, x - 2 > 0))
    assert solve(g, x) == [5]
コード例 #6
0
ファイル: test_geometry.py プロジェクト: naveensaigit/diofant
def test_idiff():
    # the use of idiff in ellipse also provides coverage
    circ = x**2 + y**2 - 4
    ans = -3 * x * (x**2 + y**2) / y**5
    assert ans == idiff(circ, y, x, 3).simplify()
    assert ans == idiff(circ, [y], x, 3).simplify()
    assert idiff(circ, y, x, 3).simplify() == ans
    explicit = 12 * x / sqrt(-x**2 + 4)**5
    assert ans.subs(solve(circ, y)[0]).equals(explicit)
    assert True in (sol[y].diff(x, 3).equals(explicit)
                    for sol in solve(circ, y))
    assert idiff(x + t + y, [y, t], x) == -Derivative(t, x) - 1
コード例 #7
0
def test_nfloat():
    x = Symbol('x')
    eq = x**Rational(4, 3) + 4*cbrt(x)/3
    assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*cbrt(x))
    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({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 sympy/sympy#6342
    lamda = Symbol('lamda')
    f = x*lamda + lamda**3*(x/2 + Rational(1, 2)) + lamda**2 + Rational(1, 4)
    assert not any(a[lamda].free_symbols
                   for a in solve(f.subs({x: -0.139})))

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

    # issue sympy/sympy#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)'
コード例 #8
0
def idiff(eq, y, x, n=1):
    """Return ``dy/dx`` assuming that ``eq == 0``.

    Parameters
    ==========

    y : the dependent variable or a list of dependent variables (with y first)
    x : the variable that the derivative is being taken with respect to
    n : the order of the derivative (default is 1)

    Examples
    ========

    >>> from diofant.abc import x, y, a
    >>> from diofant.geometry.util import idiff

    >>> circ = x**2 + y**2 - 4
    >>> idiff(circ, y, x)
    -x/y
    >>> idiff(circ, y, x, 2).simplify()
    -(x**2 + y**2)/y**3

    Here, ``a`` is assumed to be independent of ``x``:

    >>> idiff(x + a + y, y, x)
    -1

    Now the x-dependence of ``a`` is made explicit by listing ``a`` after
    ``y`` in a list.

    >>> idiff(x + a + y, [y, a], x)
    -Derivative(a, x) - 1

    See Also
    ========

    diofant.core.function.Derivative: represents unevaluated derivatives
    diofant.core.function.diff: explicitly differentiates wrt symbols

    """
    if is_sequence(y):
        dep = set(y)
        y = y[0]
    elif isinstance(y, (Dummy, Symbol)):
        dep = {y}
    else:
        raise ValueError("expecting x-dependent symbol(s) but got: %s" % y)

    f = {s: Function(s.name)(x) for s in eq.free_symbols if s != x and s in dep}
    dydx = Function(y.name)(x).diff(x)
    eq = eq.subs(f)
    derivs = {}
    for i in range(n):
        yp = solve(eq.diff(x), dydx)[0].subs(derivs)
        if i == n - 1:
            return yp.subs([(v, k) for k, v in f.items()])
        derivs[dydx] = yp
        eq = dydx - yp
        dydx = dydx.diff(x)
コード例 #9
0
def ratint_ratpart(f, g, x):
    """
    Horowitz-Ostrogradsky algorithm.

    Given a field K and polynomials f and g in K[x], such that f and g
    are coprime and deg(f) < deg(g), returns fractions A and B in K(x),
    such that f/g = A' + B and B has square-free denominator.

    Examples
    ========

        >>> from diofant.integrals.rationaltools import ratint_ratpart
        >>> from diofant.abc import x, y
        >>> from diofant import Poly
        >>> ratint_ratpart(Poly(1, x, domain='ZZ'),
        ... Poly(x + 1, x, domain='ZZ'), x)
        (0, 1/(x + 1))
        >>> ratint_ratpart(Poly(1, x, domain='EX'),
        ... Poly(x**2 + y**2, x, domain='EX'), x)
        (0, 1/(x**2 + y**2))
        >>> ratint_ratpart(Poly(36, x, domain='ZZ'),
        ... Poly(x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2, x, domain='ZZ'), x)
        ((12*x + 6)/(x**2 - 1), 12/(x**2 - x - 2))

    See Also
    ========

    diofant.integrals.rationaltools.ratint
    diofant.integrals.rationaltools.ratint_logpart
    """
    from diofant import solve

    f = Poly(f, x)
    g = Poly(g, x)

    u, v, _ = g.cofactors(g.diff())

    n = u.degree()
    m = v.degree()

    A_coeffs = [Dummy('a' + str(n - i)) for i in range(0, n)]
    B_coeffs = [Dummy('b' + str(m - i)) for i in range(0, m)]

    C_coeffs = A_coeffs + B_coeffs

    A = Poly(A_coeffs, x, domain=ZZ[C_coeffs])
    B = Poly(B_coeffs, x, domain=ZZ[C_coeffs])

    H = f - A.diff() * v + A * (u.diff() * v).quo(u) - B * u

    result = solve(H.coeffs(), C_coeffs)

    A = A.as_expr().subs(result)
    B = B.as_expr().subs(result)

    rat_part = cancel(A / u.as_expr(), x)
    log_part = cancel(B / v.as_expr(), x)

    return rat_part, log_part
コード例 #10
0
def given(expr, condition=None, **kwargs):
    """ Conditional Random Expression
    From a random expression and a condition on that expression creates a new
    probability space from the condition and returns the same expression on that
    conditional probability space.

    Examples
    ========

    >>> from diofant.stats import given, density, Die
    >>> X = Die('X', 6)
    >>> Y = given(X, X > 3)
    >>> density(Y).dict
    {4: 1/3, 5: 1/3, 6: 1/3}

    Following convention, if the condition is a random symbol then that symbol
    is considered fixed.

    >>> from diofant.stats import Normal
    >>> from diofant import pprint
    >>> from diofant.abc import z

    >>> X = Normal('X', 0, 1)
    >>> Y = Normal('Y', 0, 1)
    >>> pprint(density(X + Y, Y)(z), use_unicode=False)
                    2
           -(-Y + z)
           -----------
      ___       2
    \/ 2 *E
    ------------------
             ____
         2*\/ pi
    """

    if not random_symbols(condition) or pspace_independent(expr, condition):
        return expr

    if isinstance(condition, RandomSymbol):
        condition = Eq(condition, condition.symbol)

    condsymbols = random_symbols(condition)
    if (isinstance(condition, Equality) and len(condsymbols) == 1 and
            not isinstance(pspace(expr).domain, ConditionalDomain)):
        rv = tuple(condsymbols)[0]
        results = solve(condition, rv)
        return sum(expr.subs(rv, res) for res in results)

    # Get full probability space of both the expression and the condition
    fullspace = pspace(Tuple(expr, condition))
    # Build new space given the condition
    space = fullspace.conditional_space(condition, **kwargs)
    # Dictionary to swap out RandomSymbols in expr with new RandomSymbols
    # That point to the new conditional space
    swapdict = rs_swap(fullspace.values, space.values)
    # Swap random variables in the expression
    expr = expr.xreplace(swapdict)
    return expr
コード例 #11
0
def test_diofantissue_453():
    x = Symbol('x', real=True)
    assert isolve(abs((x - 1) / (x - 5)) <= Rational(1, 3),
                  x) == And(Integer(-1) <= x, x <= 2)
    assert solve(abs((x - 1) / (x - 5)) - Rational(1, 3), x) == [{
        x: -1
    }, {
        x: 2
    }]
コード例 #12
0
ファイル: test_simplify.py プロジェクト: cbm755/diofant
def test_sympyissue_3557():
    f_1 = x * a + y * b + z * c - 1
    f_2 = x * d + y * e + z * f - 1
    f_3 = x * g + y * h + z * i - 1

    solutions = solve([f_1, f_2, f_3], x, y, z, simplify=False)

    assert simplify(solutions[0][y]) == \
        (a*i + c*d + f*g - a*f - c*g - d*i) / \
        (a*e*i + b*f*g + c*d*h - a*f*h - b*d*i - c*e*g)
コード例 #13
0
ファイル: test_rootoftools.py プロジェクト: goretkin/diofant
def test_RootOf___eval_Eq__():
    f = Function('f')
    r = RootOf(x**3 + x + 3, 2)
    r1 = RootOf(x**3 + x + 3, 1)
    assert Eq(r, r1) is S.false
    assert Eq(r, r) is S.true
    assert Eq(r, x) is S.false
    assert Eq(r, 0) is S.false
    assert Eq(r, S.Infinity) is S.false
    assert Eq(r, I) is S.false
    assert Eq(r, f(0)) is S.false
    assert Eq(r, f(0)) is S.false
    sol = solve(r.expr)
    for s in sol:
        if s.is_real:
            assert Eq(r, s) is S.false
    r = RootOf(r.expr, 0)
    for s in sol:
        if s.is_real:
            assert Eq(r, s) is S.true
    eq = (x**3 + x + 1)
    assert [Eq(RootOf(eq, i), j) for i in range(3) for j in solve(eq)] == \
        [False, False, True, False, True, False, True, False, False]
    assert Eq(RootOf(eq, 0), 1 + S.ImaginaryUnit) is S.false
コード例 #14
0
    def _inverse_cdf_expression(self):
        """ Inverse of the CDF

        Used by sample
        """
        x, z = symbols('x, z', extended_real=True, positive=True, cls=Dummy)
        # Invert CDF
        try:
            inverse_cdf = solve(self.cdf(x) - z, x)
        except NotImplementedError:
            inverse_cdf = None
        if not inverse_cdf or len(inverse_cdf) != 1:
            raise NotImplementedError("Could not invert CDF")

        return Lambda(z, inverse_cdf[0])
コード例 #15
0
def test_RootOf___eval_Eq__():
    f = Function('f')
    r = RootOf(x**3 + x + 3, 2)
    r1 = RootOf(x**3 + x + 3, 1)
    assert Eq(r, r1) is false
    assert Eq(r, r) is true
    assert Eq(r, x) is false
    assert Eq(r, 0) is false
    assert Eq(r, oo) is false
    assert Eq(r, I) is false
    assert Eq(r, f(0)) is false
    assert Eq(r, f(0)) is false
    sol = solve(r.expr, x)
    for s in sol:
        if s[x].is_real:
            assert Eq(r, s[x]) is false
    r = RootOf(r.expr, 0)
    for s in sol:
        if s[x].is_real:
            assert Eq(r, s[x]) is true
    eq = x**3 + x + 1
    assert ([Eq(RootOf(eq, i), j[x]) for i in range(3) for j in solve(eq)
             ] == [False, False, True, False, True, False, True, False, False])
    assert Eq(RootOf(eq, 0), 1 + I) is false
コード例 #16
0
def main():

    print("Initial metric:")
    pprint(gdd)
    print("-" * 40)
    print("Christoffel symbols:")
    pprint_Gamma_udd(0, 1, 0)
    pprint_Gamma_udd(0, 0, 1)
    print()
    pprint_Gamma_udd(1, 0, 0)
    pprint_Gamma_udd(1, 1, 1)
    pprint_Gamma_udd(1, 2, 2)
    pprint_Gamma_udd(1, 3, 3)
    print()
    pprint_Gamma_udd(2, 2, 1)
    pprint_Gamma_udd(2, 1, 2)
    pprint_Gamma_udd(2, 3, 3)
    print()
    pprint_Gamma_udd(3, 2, 3)
    pprint_Gamma_udd(3, 3, 2)
    pprint_Gamma_udd(3, 1, 3)
    pprint_Gamma_udd(3, 3, 1)
    print("-" * 40)
    print("Ricci tensor:")
    pprint_Rmn_dd(0, 0)
    e = Rmn.dd(1, 1)
    pprint_Rmn_dd(1, 1)
    pprint_Rmn_dd(2, 2)
    pprint_Rmn_dd(3, 3)
    print("-" * 40)
    print("Solve Einstein's equations:")
    e = e.subs(nu(r), -lam(r)).doit()
    l = dsolve(e, lam(r))
    pprint(l)
    lamsol = solve(l, lam(r))[0]
    metric = gdd.subs(lam(r), lamsol).subs(nu(r), -lamsol)  # .combine()
    print("metric:")
    pprint(metric)
コード例 #17
0
 def scale(self, **kwargs):
     # TODO: ensure provided kwargs are keys in saufs
     # pass the value of the scaling constant with key its name
     self.scaling_constants = kwargs
     ## TODO: Assuming order, should find a way to pair each ki to its value by name
     ## may not be necessary since we do not care about the value of each UF
     scaling_constants = np.array(list(self.scaling_constants.values()))
     if sum(scaling_constants) == 1:
         self.k = 0
     k = diofant.symbols("k")
     rhs = reduce(mul, k * scaling_constants + 1, 1)
     lhs = k + 1
     sols = diofant.solve(lhs - rhs)
     # as opposed to complex, filter real solutions
     real_solutions = filter(
         lambda sol: -1 <= sol.get(k) <= 1,
         filter(lambda sol: sol.get(k).is_Float, sols),
     )
     not_null = [sol.get(k) for sol in real_solutions if sol.get(k) != 0]
     if len(not_null) == 0:
         self.k = 0
     else:
         self.k = not_null[0]
     return self.k
コード例 #18
0
ファイル: test_sqrtdenest.py プロジェクト: cbm755/diofant
def test_unrad2():
    assert solve(root(x**3 - 3 * x**2, 3) + 1 - x) == []
    assert solve(root(x + 1, 3) + root(x**2 - 2, 5) + 1) == []
コード例 #19
0
ファイル: test_sqrtdenest.py プロジェクト: cbm755/diofant
def test_unrad_slow():
    # this has roots with multiplicity > 1; there should be no
    # repeats in roots obtained, however
    eq = (sqrt(1 + sqrt(1 - 4 * x**2)) - x *
          ((1 + sqrt(1 + 2 * sqrt(1 - 4 * x**2)))))
    assert solve(eq) == [{x: Rational(1, 2)}]
コード例 #20
0
ファイル: test_sqrtdenest.py プロジェクト: cbm755/diofant
def test_unrad1_fail():
    assert solve(sqrt(x + root(x, 3)) + root(x - y, 5), y) != []
コード例 #21
0
ファイル: test_sqrtdenest.py プロジェクト: cbm755/diofant
def test_unrad1():
    pytest.raises(NotImplementedError,
                  lambda: unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3))
    pytest.raises(NotImplementedError,
                  lambda: unrad(sqrt(x) + cbrt(x + 1) + 2 * sqrt(y)))

    s = symbols('s', cls=Dummy)

    # checkers to deal with possibility of answer coming
    # back with a sign change (cf issue sympy/sympy#5203)
    def check(rv, ans):
        assert bool(rv[1]) == bool(ans[1])
        if ans[1]:
            return s_check(rv, ans)
        e = rv[0].expand()
        a = ans[0].expand()
        return e in [a, -a] and rv[1] == ans[1]

    def s_check(rv, ans):
        # get the dummy
        rv = list(rv)
        d = rv[0].atoms(Dummy)
        reps = list(zip(d, [s] * len(d)))
        # replace s with this dummy
        rv = (rv[0].subs(reps).expand(),
              [rv[1][0].subs(reps), rv[1][1].subs(reps)])
        ans = (ans[0].subs(reps).expand(),
               [ans[1][0].subs(reps), ans[1][1].subs(reps)])
        return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \
            str(rv[1]) == str(ans[1])

    assert check(unrad(sqrt(x)), (x, []))
    assert check(unrad(sqrt(x) + 1), (x - 1, []))
    assert check(unrad(sqrt(x) + root(x, 3) + 2),
                 (s**3 + s**2 + 2, [s, s**6 - x]))
    assert check(unrad(sqrt(x) * root(x, 3) + 2), (x**5 - 64, []))
    assert check(unrad(sqrt(x) + cbrt(x + 1)), (x**3 - (x + 1)**2, []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2 * x)),
                 (-2 * sqrt(2) * x - 2 * x + 1, []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + 2), (16 * x - 9, []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)),
                 (5 * x**2 - 4 * x, []))
    assert check(unrad(a * sqrt(x) + b * sqrt(x) + c * sqrt(y) + d * sqrt(y)),
                 ((a * sqrt(x) + b * sqrt(x))**2 -
                  (c * sqrt(y) + d * sqrt(y))**2, []))
    assert check(unrad(sqrt(x) + sqrt(1 - x)), (2 * x - 1, []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) - 3), (x**2 - x + 16, []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)),
                 (5 * x**2 - 2 * x + 1, []))
    assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3) in [
        (25 * x**4 + 376 * x**3 + 1256 * x**2 - 2272 * x + 784, []),
        (25 * x**8 - 476 * x**6 + 2534 * x**4 - 1468 * x**2 + 169, [])
    ]
    assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2*x)) == \
        (41*x**4 + 40*x**3 + 232*x**2 - 160*x + 16, [])  # orig root at 0.487
    assert check(unrad(sqrt(x) + sqrt(x + 1)), (Integer(1), []))

    eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x))
    assert check(unrad(eq), (16 * x**2 - 9 * x, []))
    assert {s[x] for s in solve(eq, check=False)} == {0, Rational(9, 16)}
    assert solve(eq) == []
    # but this one really does have those solutions
    assert ({s[x]
             for s in solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x)))
             } == {0, Rational(9, 16)})

    assert check(unrad(sqrt(x) + root(x + 1, 3) + 2 * sqrt(y), y),
                 (2 * sqrt(x) * cbrt(x + 1) + x - 4 * y +
                  (x + 1)**Rational(2, 3), []))
    assert check(unrad(sqrt(x / (1 - x)) + cbrt(x + 1)),
                 (x**5 - x**4 - x**3 + 2 * x**2 + x - 1, []))
    assert check(unrad(sqrt(x / (1 - x)) + 2 * sqrt(y), y),
                 (4 * x * y + x - 4 * y, []))
    assert check(unrad(sqrt(x) * sqrt(1 - x) + 2, x), (x**2 - x + 4, []))

    # http://tutorial.math.lamar.edu/
    #        Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a
    assert solve(Eq(x, sqrt(x + 6))) == [{x: 3}]
    assert solve(Eq(x + sqrt(x - 4), 4)) == [{x: 4}]
    assert solve(Eq(1, x + sqrt(2 * x - 3))) == []
    assert {s[x] for s in solve(Eq(sqrt(5 * x + 6) - 2, x))} == {-1, 2}
    assert {s[x]
            for s in solve(Eq(sqrt(2 * x - 1) - sqrt(x - 4), 2))} == {5, 13}
    assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [{x: -6}]
    # http://www.purplemath.com/modules/solverad.htm
    assert solve(cbrt(2 * x - 5) - 3) == [{x: 16}]
    assert {s[x]
            for s in solve(x + 1 - root(x**4 + 4 * x**3 - x, 4))
            } == {-Rational(1, 2), -Rational(1, 3)}
    assert {s[x] for s in solve(sqrt(2 * x**2 - 7) - (3 - x))} == {-8, 2}
    assert solve(sqrt(2 * x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [{x: 0}]
    assert solve(sqrt(x + 4) + sqrt(2 * x - 1) - 3 * sqrt(x - 1)) == [{x: 5}]
    assert solve(sqrt(x) * sqrt(x - 7) - 12) == [{x: 16}]
    assert solve(sqrt(x - 3) + sqrt(x) - 3) == [{x: 4}]
    assert solve(sqrt(9 * x**2 + 4) - (3 * x + 2)) == [{x: 0}]
    assert solve(sqrt(x) - 2 - 5) == [{x: 49}]
    assert solve(sqrt(x - 3) - sqrt(x) - 3) == []
    assert solve(sqrt(x - 1) - x + 7) == [{x: 10}]
    assert solve(sqrt(x - 2) - 5) == [{x: 27}]
    assert solve(sqrt(17 * x - sqrt(x**2 - 5)) - 7) == [{x: 3}]
    assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == []

    # don't posify the expression in unrad and do use _mexpand
    z = sqrt(2 * x + 1) / sqrt(x) - sqrt(2 + 1 / x)
    p = posify(z)[0]
    assert solve(p) == []
    assert solve(z) == []
    assert solve(z + 6 * I) == [{x: -Rational(1, 11)}]
    assert solve(p + 6 * I) == []
    # issue sympy/sympy#8622
    assert unrad(
        (root(x + 1, 5) - root(x, 3))) == (x**5 - x**3 - 3 * x**2 - 3 * x - 1,
                                           [])
    # issue sympy/sympy#8679
    assert check(unrad(x + root(x, 3) + root(x, 3)**2 + sqrt(y), x),
                 (s**3 + s**2 + s + sqrt(y), [s, s**3 - x]))

    # for coverage
    assert check(unrad(sqrt(x) + root(x, 3) + y),
                 (s**3 + s**2 + y, [s, s**6 - x]))
    assert solve(sqrt(x) + root(x, 3) - 2) == [{x: 1}]
    pytest.raises(NotImplementedError,
                  lambda: solve(sqrt(x) + root(x, 3) + root(x + 1, 5) - 2))
    # fails through a different code path
    pytest.raises(NotImplementedError, lambda: solve(-sqrt(2) + cosh(x) / x))
    # unrad some
    e = root(x + 1, 3) + root(x, 3)
    assert unrad(e) == (2 * x + 1, [])
    eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6 * sqrt(5) / 5)
    assert check(unrad(eq), (15625 * x**4 + 173000 * x**3 + 355600 * x**2 -
                             817920 * x + 331776, []))
    assert check(unrad(root(x, 4) + root(x, 4)**3 - 1),
                 (s**3 + s - 1, [s, s**4 - x]))
    assert check(unrad(root(x, 2) + root(x, 2)**3 - 1),
                 (x**3 + 2 * x**2 + x - 1, []))
    assert unrad(x**0.5) is None
    assert check(unrad(t + root(x + y, 5) + root(x + y, 5)**3),
                 (s**3 + s + t, [s, s**5 - x - y]))
    assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, y),
                 (s**3 + s + x, [s, s**5 - x - y]))
    assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, x),
                 (s**5 + s**3 + s - y, [s, s**5 - x - y]))
    assert check(
        unrad(root(x - 1, 3) + root(x + 1, 5) + root(2, 5)),
        (s**5 + 5 * root(2, 5) * s**4 + s**3 + 10 * 2**Rational(2, 5) * s**3 +
         10 * 2**Rational(3, 5) * s**2 + 5 * 2**Rational(4, 5) * s + 4,
         [s, s**3 - x + 1]))
    pytest.raises(
        NotImplementedError, lambda: unrad(
            (root(x, 2) + root(x, 3) + root(x, 4)).subs({x: x**5 - x + 1})))

    # the simplify flag should be reset to False for unrad results;
    # if it's not then this next test will take a long time
    assert solve(root(x, 3) + root(x, 5) - 2) == [{x: 1}]
    eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6 * sqrt(5) / 5)
    assert check(unrad(eq),
                 ((5 * x - 4) *
                  (3125 * x**3 + 37100 * x**2 + 100800 * x - 82944), []))
    ans = [{
        x: Rational(4, 5)
    }, {
        x:
        Rational(-1484, 375) + 172564 /
        (140625 *
         cbrt(114 * sqrt(12657) / 78125 + Rational(12459439, 52734375))) +
        4 * cbrt(114 * sqrt(12657) / 78125 + Rational(12459439, 52734375))
    }]
    assert solve(eq) == ans
    # duplicate radical handling
    assert check(unrad(sqrt(x + root(x + 1, 3)) - root(x + 1, 3) - 2),
                 (s**3 - s**2 - 3 * s - 5, [s, s**3 - x - 1]))
    # cov post-processing
    e = root(x**2 + 1, 3) - root(x**2 - 1, 5) - 2
    assert check(unrad(e),
                 (s**5 - 10 * s**4 + 39 * s**3 - 80 * s**2 + 80 * s - 30,
                  [s, s**3 - x**2 - 1]))

    e = sqrt(x + root(x + 1, 2)) - root(x + 1, 3) - 2
    assert check(unrad(e), (s**6 - 2 * s**5 - 7 * s**4 - 3 * s**3 + 26 * s**2 +
                            40 * s + 25, [s, s**3 - x - 1]))
    assert check(unrad(e, _reverse=True),
                 (s**6 - 14 * s**5 + 73 * s**4 - 187 * s**3 + 276 * s**2 -
                  228 * s + 89, [s, s**2 - x - sqrt(x + 1)]))
    # this one needs r0, r1 reversal to work
    assert check(unrad(sqrt(x + sqrt(root(x, 3) - 1)) - root(x, 6) - 2),
                 (s**12 - 2 * s**8 - 8 * s**7 - 8 * s**6 + s**4 + 8 * s**3 +
                  23 * s**2 + 32 * s + 17, [s, s**6 - x]))

    # is this needed?
    # assert unrad(root(cosh(x), 3)/x*root(x + 1, 5) - 1) == (
    #    x**15 - x**3*cosh(x)**5 - 3*x**2*cosh(x)**5 - 3*x*cosh(x)**5 - cosh(x)**5, [])
    pytest.raises(
        NotImplementedError,
        lambda: unrad(sqrt(cosh(x) / x) + root(x + 1, 3) * sqrt(x) - 1))
    assert unrad((x + y)**(2 * y / 3) + cbrt(x + y) + 1) is None
    assert check(unrad((x + y)**(2 * y / 3) + cbrt(x + y) + 1, x),
                 (s**(2 * y) + s + 1, [s, s**3 - x - y]))

    # This tests two things: that if full unrad is attempted and fails
    # the solution should still be found; also it tests that the use of
    # composite
    assert len(solve(sqrt(y) * x + x**3 - 1, x)) == 3
    assert len(
        solve(-512 * y**3 + 1344 * cbrt(x + 2) * y**2 - 1176 *
              (x + 2)**Rational(2, 3) * y - 169 * x + 686,
              y,
              _unrad=False)) == 3

    # watch out for when the cov doesn't involve the symbol of interest
    eq = -x + (7 * y / 8 - cbrt(27 * x / 2 + 27 * sqrt(x**2) / 2) / 3)**3 - 1
    assert solve(eq, y) == [{
        y:
        RootOf(
            -768 * x + 343 * y**3 -
            588 * cbrt(4) * y**2 * cbrt(x + sqrt(x**2)) +
            672 * cbrt(2) * y * cbrt(x + sqrt(x**2))**2 - 256 * sqrt(x**2) -
            512, y, 0)
    }, {
        y:
        RootOf(
            -768 * x + 343 * y**3 -
            588 * cbrt(4) * y**2 * cbrt(x + sqrt(x**2)) +
            672 * cbrt(2) * y * cbrt(x + sqrt(x**2))**2 - 256 * sqrt(x**2) -
            512, y, 1)
    }, {
        y:
        RootOf(
            -768 * x + 343 * y**3 -
            588 * cbrt(4) * y**2 * cbrt(x + sqrt(x**2)) +
            672 * cbrt(2) * y * cbrt(x + sqrt(x**2))**2 - 256 * sqrt(x**2) -
            512, y, 2)
    }]

    eq = root(x + 1, 3) - (root(x, 3) + root(x, 5))
    assert check(unrad(eq), (3 * s**13 + 3 * s**11 + s**9 - 1, [s, s**15 - x]))
    assert check(unrad(eq - 2),
                 (3 * s**13 + 3 * s**11 + 6 * s**10 + s**9 + 12 * s**8 +
                  6 * s**6 + 12 * s**5 + 12 * s**3 + 7, [s, s**15 - x]))
    assert check(
        unrad(root(x, 3) - root(x + 1, 4) / 2 + root(x + 2, 3)),
        (4096 * s**13 + 960 * s**12 + 48 * s**11 - s**10 - 1728 * s**4,
         [s, s**4 - x - 1]))  # orig expr has two real roots: -1, -.389
    assert check(
        unrad(root(x, 3) + root(x + 1, 4) - root(x + 2, 3) / 2),
        (343 * s**13 + 2904 * s**12 + 1344 * s**11 + 512 * s**10 -
         1323 * s**9 - 3024 * s**8 - 1728 * s**7 + 1701 * s**5 + 216 * s**4 -
         729 * s, [s, s**4 - x - 1]))  # orig expr has one real root: -0.048
    assert check(
        unrad(root(x, 3) / 2 - root(x + 1, 4) + root(x + 2, 3)),
        (729 * s**13 - 216 * s**12 + 1728 * s**11 - 512 * s**10 + 1701 * s**9 -
         3024 * s**8 + 1344 * s**7 + 1323 * s**5 - 2904 * s**4 + 343 * s,
         [s, s**4 - x - 1]))  # orig expr has 2 real roots: -0.91, -0.15

    # orig expr has 1 real root: 19.53
    assert check(unrad(root(x, 3) / 2 - root(x + 1, 4) + root(x + 2, 3) - 2),
                 (729 * s**13 + 1242 * s**12 + 18496 * s**10 + 129701 * s**9 +
                  388602 * s**8 + 453312 * s**7 - 612864 * s**6 -
                  3337173 * s**5 - 6332418 * s**4 - 7134912 * s**3 -
                  5064768 * s**2 - 2111913 * s - 398034, [s, s**4 - x - 1]))

    ans = solve(sqrt(x) + sqrt(x + 1) - sqrt(1 - x) - sqrt(2 + x))
    assert len(ans) == 1 and NS(ans[0][x])[:4] == '0.73'
    # the fence optimization problem
    # https://github.com/sympy/sympy/issues/4793#issuecomment-36994519
    eq = F - (2 * x + 2 * y + sqrt(x**2 + y**2))
    ans = 2 * F / 7 - sqrt(2) * F / 14
    X = solve(eq, x, check=False)
    for xi in reversed(X):  # reverse since currently, ans is the 2nd one
        Y = solve((x * y).subs(xi).diff(y), y, simplify=False, check=False)
        if any((a[y] - ans).expand().is_zero for a in Y):
            break
    else:
        assert None  # no answer was found
    assert (solve(sqrt(x + 1) + root(x, 3) - 2) == [{
        x: (-11 / (9 * cbrt(Rational(47, 54) + sqrt(93) / 6)) +
            Rational(1, 3) + cbrt(Rational(47, 54) + sqrt(93) / 6))**3
    }])
    assert (solve(sqrt(sqrt(x + 1)) + cbrt(x) - 2) == [{
        x:
        (-sqrt(-2 * cbrt(Rational(-1, 16) + sqrt(6913) / 16) +
               6 / cbrt(Rational(-1, 16) + sqrt(6913) / 16) + Rational(17, 2) +
               121 / (4 * sqrt(-6 / cbrt(Rational(-1, 16) + sqrt(6913) / 16) +
                               2 * cbrt(Rational(-1, 16) + sqrt(6913) / 16) +
                               Rational(17, 4)))) / 2 +
         sqrt(-6 / cbrt(Rational(-1, 16) + sqrt(6913) / 16) + 2 *
              cbrt(Rational(-1, 16) + sqrt(6913) / 16) + Rational(17, 4)) / 2 +
         Rational(9, 4))**3
    }])
    assert (solve(sqrt(x) + root(sqrt(x) + 1, 3) - 2) == [{
        x: (-cbrt(Rational(81, 2) + 3 * sqrt(741) / 2) / 3 +
            (Rational(81, 2) + 3 * sqrt(741) / 2)**Rational(-1, 3) + 2)**2
    }])
    eq = (-x + (Rational(1, 2) - sqrt(3) * I / 2) *
          cbrt(3 * x**3 / 2 - x * (3 * x**2 - 34) / 2 + sqrt(
              (-3 * x**3 + x *
               (3 * x**2 - 34) + 90)**2 / 4 - Rational(39304, 27)) - 45) + 34 /
          (3 * (Rational(1, 2) - sqrt(3) * I / 2) *
           cbrt(3 * x**3 / 2 - x * (3 * x**2 - 34) / 2 + sqrt(
               (-3 * x**3 + x *
                (3 * x**2 - 34) + 90)**2 / 4 - Rational(39304, 27)) - 45)))
    assert check(unrad(eq),
                 (s**6 - sqrt(3) * s**6 * I + 102 * cbrt(12) * s**4 +
                  102 * 2**Rational(2, 3) * 3**Rational(5, 6) * s**4 * I +
                  1620 * s**3 - 1620 * sqrt(3) * s**3 * I -
                  13872 * cbrt(18) * s**2 + 471648 - 471648 * sqrt(3) * I, [
                      s, s**3 - 306 * x -
                      sqrt(3) * sqrt(31212 * x**2 - 165240 * x + 61484) + 810
                  ]))
    assert solve(eq, x, check=False) != []  # not other code errors
コード例 #22
0
# %%
mauf = access_to_facilities * access_to_pros * access_to_medicine

# %%
mauf.scale(ncenters_nbeds_ndocs_nparam=0.7, npharma=0.2)

# %%
kwargs = {"ncenters_nbeds_ndocs_nparam": 0.7, "npharma": 0.5}

# %%
mauf.saufs.keys()

# %%
X = diofant.symbols("X")
diofant.solve(X + 1 - (0.8 * X + 1) * (0.6 * X + 1) * (0.7 * X + 1))

# %% [markdown]
# ## Figures

# %% [markdown]
# #### Number of doctors

# %%
fig = data.set_index("governorate")["Number of doctors"].apply(
    u_ndocs.normalized_model
).sort_values().iplot(
    kind="bar",
    title=
    "Ranking of governorates based on the utility of number of doctors per 1000 inhabitants",
    asFigure=True)
コード例 #23
0
def test_piecewise_solve2():
    f = Piecewise(((x - 2)**2, x >= 0), (0, True))
    assert solve(f, x) == [2, Interval(0, oo, True, True)]
コード例 #24
0
def test_sympyissue_11553():
    eqs = (x + y + 1, x + GoldenRatio)
    assert solve(eqs, x, y) == [{x: -GoldenRatio, y: -1 + GoldenRatio}]
コード例 #25
0
ファイル: test_piecewise.py プロジェクト: skirpichev/diofant
def test_piecewise_solve2():
    f = Piecewise(((x - 2)**2, x >= 0), (0, True))
    assert solve(f, x) != [{x: 2}]
コード例 #26
0
ファイル: test_piecewise.py プロジェクト: fagan2888/diofant
def test_piecewise_solve2():
    f = Piecewise(((x - 2)**2, x >= 0), (0, True))
    assert solve(f, x) != [{x: 2}]
コード例 #27
0
def ratsimpmodprime(expr, G, *gens, **args):
    """
    Simplifies a rational expression ``expr`` modulo the prime ideal
    generated by ``G``.  ``G`` should be a Groebner basis of the
    ideal.

    >>> from diofant.simplify.ratsimp import ratsimpmodprime
    >>> from diofant.abc import x, y
    >>> eq = (x + y**5 + y)/(x - y)
    >>> ratsimpmodprime(eq, [x*y**5 - x - y], x, y, order='lex')
    (x**2 + x*y + x + y)/(x**2 - x*y)

    If ``polynomial`` is False, the algorithm computes a rational
    simplification which minimizes the sum of the total degrees of
    the numerator and the denominator.

    If ``polynomial`` is True, this function just brings numerator and
    denominator into a canonical form. This is much faster, but has
    potentially worse results.

    References
    ==========

    M. Monagan, R. Pearce, Rational Simplification Modulo a Polynomial
    Ideal,
    http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.163.6984
    (specifically, the second algorithm)
    """
    from diofant import solve

    quick = args.pop('quick', True)
    polynomial = args.pop('polynomial', False)
    debug('ratsimpmodprime', expr)

    # usual preparation of polynomials:

    num, denom = cancel(expr).as_numer_denom()

    try:
        polys, opt = parallel_poly_from_expr([num, denom] + G, *gens, **args)
    except PolificationFailed:
        return expr

    domain = opt.domain

    if domain.has_assoc_Field:
        opt.domain = domain.get_field()
    else:
        raise DomainError("can't compute rational simplification over %s" %
                          domain)

    # compute only once
    leading_monomials = [g.LM(opt.order) for g in polys[2:]]
    tested = set()

    def staircase(n):
        """
        Compute all monomials with degree less than ``n`` that are
        not divisible by any element of ``leading_monomials``.
        """
        if n == 0:
            return [1]
        S = []
        for mi in combinations_with_replacement(range(len(opt.gens)), n):
            m = [0] * len(opt.gens)
            for i in mi:
                m[i] += 1
            if all([monomial_div(m, lmg) is None
                    for lmg in leading_monomials]):
                S.append(m)

        return [Monomial(s).as_expr(*opt.gens) for s in S] + staircase(n - 1)

    def _ratsimpmodprime(a, b, allsol, N=0, D=0):
        """
        Computes a rational simplification of ``a/b`` which minimizes
        the sum of the total degrees of the numerator and the denominator.

        The algorithm proceeds by looking at ``a * d - b * c`` modulo
        the ideal generated by ``G`` for some ``c`` and ``d`` with degree
        less than ``a`` and ``b`` respectively.
        The coefficients of ``c`` and ``d`` are indeterminates and thus
        the coefficients of the normalform of ``a * d - b * c`` are
        linear polynomials in these indeterminates.
        If these linear polynomials, considered as system of
        equations, have a nontrivial solution, then `\frac{a}{b}
        \equiv \frac{c}{d}` modulo the ideal generated by ``G``. So,
        by construction, the degree of ``c`` and ``d`` is less than
        the degree of ``a`` and ``b``, so a simpler representation
        has been found.
        After a simpler representation has been found, the algorithm
        tries to reduce the degree of the numerator and denominator
        and returns the result afterwards.

        As an extension, if quick=False, we look at all possible degrees such
        that the total degree is less than *or equal to* the best current
        solution. We retain a list of all solutions of minimal degree, and try
        to find the best one at the end.
        """
        c, d = a, b
        steps = 0

        maxdeg = a.total_degree() + b.total_degree()
        if quick:
            bound = maxdeg - 1
        else:
            bound = maxdeg
        while N + D <= bound:
            if (N, D) in tested:
                break
            tested.add((N, D))

            M1 = staircase(N)
            M2 = staircase(D)
            debug('%s / %s: %s, %s' % (N, D, M1, M2))

            Cs = symbols("c:%d" % len(M1), cls=Dummy)
            Ds = symbols("d:%d" % len(M2), cls=Dummy)
            ng = Cs + Ds

            c_hat = Poly(sum(Cs[i] * M1[i] for i in range(len(M1))),
                         opt.gens + ng)
            d_hat = Poly(sum(Ds[i] * M2[i] for i in range(len(M2))),
                         opt.gens + ng)

            r = reduced(a * d_hat - b * c_hat,
                        G,
                        opt.gens + ng,
                        order=opt.order,
                        polys=True)[1]

            S = Poly(r, gens=opt.gens).coeffs()
            sol = solve(S, Cs + Ds, particular=True, quick=True)

            if sol and not all([s == 0 for s in sol.values()]):
                c = c_hat.subs(sol)
                d = d_hat.subs(sol)

                # The "free" variables occuring before as parameters
                # might still be in the substituted c, d, so set them
                # to the value chosen before:
                c = c.subs(dict(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))
                d = d.subs(dict(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))

                c = Poly(c, opt.gens)
                d = Poly(d, opt.gens)
                if d == 0:
                    raise ValueError('Ideal not prime?')

                allsol.append((c_hat, d_hat, S, Cs + Ds))
                if N + D != maxdeg:
                    allsol = [allsol[-1]]

                break

            steps += 1
            N += 1
            D += 1

        if steps > 0:
            c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps)
            c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D)

        return c, d, allsol

    # preprocessing. this improves performance a bit when deg(num)
    # and deg(denom) are large:
    num = reduced(num, G, opt.gens, order=opt.order)[1]
    denom = reduced(denom, G, opt.gens, order=opt.order)[1]

    if polynomial:
        return (num / denom).cancel()

    c, d, allsol = _ratsimpmodprime(Poly(num, opt.gens), Poly(denom, opt.gens),
                                    [])
    if not quick and allsol:
        debug('Looking for best minimal solution. Got: %s' % len(allsol))
        newsol = []
        for c_hat, d_hat, S, ng in allsol:
            sol = solve(S, ng, particular=True, quick=False)
            newsol.append((c_hat.subs(sol), d_hat.subs(sol)))
        c, d = min(newsol, key=lambda x: len(x[0].terms()) + len(x[1].terms()))

    if not domain.has_Field:
        cn, c = c.clear_denoms(convert=True)
        dn, d = d.clear_denoms(convert=True)

    cf, c, d = cancel((c, d), opt.gens, order=opt.order)  # canonicalize signs
    r = cf * Rational(cn, dn)

    return (c * r.q) / (d * r.p)
コード例 #28
0
ファイル: test_sqrtdenest.py プロジェクト: skirpichev/diofant
def test_unrad_slow():
    # this has roots with multiplicity > 1; there should be no
    # repeats in roots obtained, however
    eq = (sqrt(1 + sqrt(1 - 4*x**2)) - x*((1 + sqrt(1 + 2*sqrt(1 - 4*x**2)))))
    assert solve(eq) == [{x: Rational(1, 2)}]
コード例 #29
0
ファイル: test_sqrtdenest.py プロジェクト: skirpichev/diofant
def test_unrad1():
    pytest.raises(NotImplementedError, lambda:
                  unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3))
    pytest.raises(NotImplementedError, lambda:
                  unrad(sqrt(x) + cbrt(x + 1) + 2*sqrt(y)))

    s = symbols('s', cls=Dummy)

    # checkers to deal with possibility of answer coming
    # back with a sign change (cf issue sympy/sympy#5203)
    def check(rv, ans):
        assert bool(rv[1]) == bool(ans[1])
        if ans[1]:
            return s_check(rv, ans)
        e = rv[0].expand()
        a = ans[0].expand()
        return e in [a, -a] and rv[1] == ans[1]

    def s_check(rv, ans):
        # get the dummy
        rv = list(rv)
        d = rv[0].atoms(Dummy)
        reps = list(zip(d, [s]*len(d)))
        # replace s with this dummy
        rv = (rv[0].subs(reps).expand(), [rv[1][0].subs(reps), rv[1][1].subs(reps)])
        ans = (ans[0].subs(reps).expand(), [ans[1][0].subs(reps), ans[1][1].subs(reps)])
        return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \
            str(rv[1]) == str(ans[1])

    assert check(unrad(sqrt(x)),
                 (x, []))
    assert check(unrad(sqrt(x) + 1),
                 (x - 1, []))
    assert check(unrad(sqrt(x) + root(x, 3) + 2),
                 (s**3 + s**2 + 2, [s, s**6 - x]))
    assert check(unrad(sqrt(x)*root(x, 3) + 2),
                 (x**5 - 64, []))
    assert check(unrad(sqrt(x) + cbrt(x + 1)),
                 (x**3 - (x + 1)**2, []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2*x)),
                 (-2*sqrt(2)*x - 2*x + 1, []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + 2),
                 (16*x - 9, []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)),
                 (5*x**2 - 4*x, []))
    assert check(unrad(a*sqrt(x) + b*sqrt(x) + c*sqrt(y) + d*sqrt(y)),
                 ((a*sqrt(x) + b*sqrt(x))**2 - (c*sqrt(y) + d*sqrt(y))**2, []))
    assert check(unrad(sqrt(x) + sqrt(1 - x)),
                 (2*x - 1, []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) - 3),
                 (x**2 - x + 16, []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)),
                 (5*x**2 - 2*x + 1, []))
    assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3) in [
        (25*x**4 + 376*x**3 + 1256*x**2 - 2272*x + 784, []),
        (25*x**8 - 476*x**6 + 2534*x**4 - 1468*x**2 + 169, [])]
    assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2*x)) == \
        (41*x**4 + 40*x**3 + 232*x**2 - 160*x + 16, [])  # orig root at 0.487
    assert check(unrad(sqrt(x) + sqrt(x + 1)), (Integer(1), []))

    eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x))
    assert check(unrad(eq),
                 (16*x**2 - 9*x, []))
    assert {s[x] for s in solve(eq, check=False)} == {0, Rational(9, 16)}
    assert solve(eq) == []
    # but this one really does have those solutions
    assert ({s[x] for s in solve(sqrt(x) - sqrt(x + 1) +
                                 sqrt(1 - sqrt(x)))} ==
            {0, Rational(9, 16)})

    assert check(unrad(sqrt(x) + root(x + 1, 3) + 2*sqrt(y), y),
                 (2*sqrt(x)*cbrt(x + 1) + x - 4*y +
                     (x + 1)**Rational(2, 3), []))
    assert check(unrad(sqrt(x/(1 - x)) + cbrt(x + 1)),
                 (x**5 - x**4 - x**3 + 2*x**2 + x - 1, []))
    assert check(unrad(sqrt(x/(1 - x)) + 2*sqrt(y), y),
                 (4*x*y + x - 4*y, []))
    assert check(unrad(sqrt(x)*sqrt(1 - x) + 2, x),
                 (x**2 - x + 4, []))

    # http://tutorial.math.lamar.edu/
    #        Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a
    assert solve(Eq(x, sqrt(x + 6))) == [{x: 3}]
    assert solve(Eq(x + sqrt(x - 4), 4)) == [{x: 4}]
    assert solve(Eq(1, x + sqrt(2*x - 3))) == []
    assert {s[x] for s in solve(Eq(sqrt(5*x + 6) - 2, x))} == {-1, 2}
    assert {s[x] for s in solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))} == {5, 13}
    assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [{x: -6}]
    # http://www.purplemath.com/modules/solverad.htm
    assert solve(cbrt(2*x - 5) - 3) == [{x: 16}]
    assert {s[x] for s in solve(x + 1 - root(x**4 + 4*x**3 - x, 4))} == {-Rational(1, 2),
                                                                         -Rational(1, 3)}
    assert {s[x] for s in solve(sqrt(2*x**2 - 7) - (3 - x))} == {-8, 2}
    assert solve(sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [{x: 0}]
    assert solve(sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1)) == [{x: 5}]
    assert solve(sqrt(x)*sqrt(x - 7) - 12) == [{x: 16}]
    assert solve(sqrt(x - 3) + sqrt(x) - 3) == [{x: 4}]
    assert solve(sqrt(9*x**2 + 4) - (3*x + 2)) == [{x: 0}]
    assert solve(sqrt(x) - 2 - 5) == [{x: 49}]
    assert solve(sqrt(x - 3) - sqrt(x) - 3) == []
    assert solve(sqrt(x - 1) - x + 7) == [{x: 10}]
    assert solve(sqrt(x - 2) - 5) == [{x: 27}]
    assert solve(sqrt(17*x - sqrt(x**2 - 5)) - 7) == [{x: 3}]
    assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == []

    # don't posify the expression in unrad and do use _mexpand
    z = sqrt(2*x + 1)/sqrt(x) - sqrt(2 + 1/x)
    p = posify(z)[0]
    assert solve(p) == []
    assert solve(z) == []
    assert solve(z + 6*I) == [{x: -Rational(1, 11)}]
    assert solve(p + 6*I) == []
    # issue sympy/sympy#8622
    assert unrad((root(x + 1, 5) - root(x, 3))) == (
        x**5 - x**3 - 3*x**2 - 3*x - 1, [])
    # issue sympy/sympy#8679
    assert check(unrad(x + root(x, 3) + root(x, 3)**2 + sqrt(y), x),
                 (s**3 + s**2 + s + sqrt(y), [s, s**3 - x]))

    # for coverage
    assert check(unrad(sqrt(x) + root(x, 3) + y),
                 (s**3 + s**2 + y, [s, s**6 - x]))
    assert solve(sqrt(x) + root(x, 3) - 2) == [{x: 1}]
    pytest.raises(NotImplementedError, lambda:
                  solve(sqrt(x) + root(x, 3) + root(x + 1, 5) - 2))
    # fails through a different code path
    pytest.raises(NotImplementedError, lambda: solve(-sqrt(2) + cosh(x)/x))
    # unrad some
    e = root(x + 1, 3) + root(x, 3)
    assert unrad(e) == (2*x + 1, [])
    eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
    assert check(unrad(eq),
                 (15625*x**4 + 173000*x**3 + 355600*x**2 - 817920*x + 331776, []))
    assert check(unrad(root(x, 4) + root(x, 4)**3 - 1),
                 (s**3 + s - 1, [s, s**4 - x]))
    assert check(unrad(root(x, 2) + root(x, 2)**3 - 1),
                 (x**3 + 2*x**2 + x - 1, []))
    assert unrad(x**0.5) is None
    assert check(unrad(t + root(x + y, 5) + root(x + y, 5)**3),
                 (s**3 + s + t, [s, s**5 - x - y]))
    assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, y),
                 (s**3 + s + x, [s, s**5 - x - y]))
    assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, x),
                 (s**5 + s**3 + s - y, [s, s**5 - x - y]))
    assert check(unrad(root(x - 1, 3) + root(x + 1, 5) + root(2, 5)),
                 (s**5 + 5*root(2, 5)*s**4 + s**3 + 10*2**Rational(2, 5)*s**3 +
                  10*2**Rational(3, 5)*s**2 + 5*2**Rational(4, 5)*s + 4, [s, s**3 - x + 1]))
    pytest.raises(NotImplementedError,
                  lambda: unrad((root(x, 2) + root(x, 3) +
                                 root(x, 4)).subs({x: x**5 - x + 1})))

    # the simplify flag should be reset to False for unrad results;
    # if it's not then this next test will take a long time
    assert solve(root(x, 3) + root(x, 5) - 2) == [{x: 1}]
    eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
    assert check(unrad(eq),
                 ((5*x - 4)*(3125*x**3 + 37100*x**2 + 100800*x - 82944), []))
    ans = [{x: Rational(4, 5)},
           {x: Rational(-1484, 375) + 172564/(140625*cbrt(114*sqrt(12657)/78125 +
                                                          Rational(12459439, 52734375))) +
               4*cbrt(114*sqrt(12657)/78125 +
                      Rational(12459439, 52734375))}]
    assert solve(eq) == ans
    # duplicate radical handling
    assert check(unrad(sqrt(x + root(x + 1, 3)) - root(x + 1, 3) - 2),
                 (s**3 - s**2 - 3*s - 5, [s, s**3 - x - 1]))
    # cov post-processing
    e = root(x**2 + 1, 3) - root(x**2 - 1, 5) - 2
    assert check(unrad(e),
                 (s**5 - 10*s**4 + 39*s**3 - 80*s**2 + 80*s - 30,
                  [s, s**3 - x**2 - 1]))

    e = sqrt(x + root(x + 1, 2)) - root(x + 1, 3) - 2
    assert check(unrad(e),
                 (s**6 - 2*s**5 - 7*s**4 - 3*s**3 + 26*s**2 + 40*s + 25,
                  [s, s**3 - x - 1]))
    assert check(unrad(e, _reverse=True),
                 (s**6 - 14*s**5 + 73*s**4 - 187*s**3 + 276*s**2 - 228*s + 89,
                  [s, s**2 - x - sqrt(x + 1)]))
    # this one needs r0, r1 reversal to work
    assert check(unrad(sqrt(x + sqrt(root(x, 3) - 1)) - root(x, 6) - 2),
                 (s**12 - 2*s**8 - 8*s**7 - 8*s**6 + s**4 + 8*s**3 + 23*s**2 +
                  32*s + 17, [s, s**6 - x]))

    # is this needed?
    # assert unrad(root(cosh(x), 3)/x*root(x + 1, 5) - 1) == (
    #    x**15 - x**3*cosh(x)**5 - 3*x**2*cosh(x)**5 - 3*x*cosh(x)**5 - cosh(x)**5, [])
    pytest.raises(NotImplementedError, lambda:
                  unrad(sqrt(cosh(x)/x) + root(x + 1, 3)*sqrt(x) - 1))
    assert unrad((x+y)**(2*y/3) + cbrt(x+y) + 1) is None
    assert check(unrad((x+y)**(2*y/3) + cbrt(x+y) + 1, x),
                 (s**(2*y) + s + 1, [s, s**3 - x - y]))

    # This tests two things: that if full unrad is attempted and fails
    # the solution should still be found; also it tests that the use of
    # composite
    assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3
    assert len(solve(-512*y**3 + 1344*cbrt(x + 2)*y**2 -
                     1176*(x + 2)**Rational(2, 3)*y -
                     169*x + 686, y, _unrad=False)) == 3

    # watch out for when the cov doesn't involve the symbol of interest
    eq = -x + (7*y/8 - cbrt(27*x/2 + 27*sqrt(x**2)/2)/3)**3 - 1
    assert solve(eq, y) == [
        {y: RootOf(-2304*x + 1029*y**3 - 1764*cbrt(4)*y**2*cbrt(x + sqrt(x**2)) +
                   2016*cbrt(2)*y*(x + sqrt(x**2))**Rational(2, 3) -
                   768*sqrt(x**2) - 1536, y, 0, evaluate=False)},
        {y: RootOf(-2304*x + 1029*y**3 - 1764*cbrt(4)*y**2*cbrt(x + sqrt(x**2)) +
                   2016*cbrt(2)*y*(x + sqrt(x**2))**Rational(2, 3) -
                   768*sqrt(x**2) - 1536, y, 1, evaluate=False)},
        {y: RootOf(-2304*x + 1029*y**3 - 1764*cbrt(4)*y**2*cbrt(x + sqrt(x**2)) +
                   2016*cbrt(2)*y*(x + sqrt(x**2))**Rational(2, 3) -
                   768*sqrt(x**2) - 1536, y, 2, evaluate=False)}]

    eq = root(x + 1, 3) - (root(x, 3) + root(x, 5))
    assert check(unrad(eq),
                 (3*s**13 + 3*s**11 + s**9 - 1, [s, s**15 - x]))
    assert check(unrad(eq - 2),
                 (3*s**13 + 3*s**11 + 6*s**10 + s**9 + 12*s**8 + 6*s**6 + 12*s**5 +
                  12*s**3 + 7, [s, s**15 - x]))
    assert check(unrad(root(x, 3) - root(x + 1, 4)/2 + root(x + 2, 3)),
                 (4096*s**13 + 960*s**12 + 48*s**11 - s**10 - 1728*s**4,
                  [s, s**4 - x - 1]))  # orig expr has two real roots: -1, -.389
    assert check(unrad(root(x, 3) + root(x + 1, 4) - root(x + 2, 3)/2),
                 (343*s**13 + 2904*s**12 + 1344*s**11 + 512*s**10 - 1323*s**9 -
                  3024*s**8 - 1728*s**7 + 1701*s**5 + 216*s**4 - 729*s, [s, s**4 - x -
                                                                         1]))  # orig expr has one real root: -0.048
    assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3)),
                 (729*s**13 - 216*s**12 + 1728*s**11 - 512*s**10 + 1701*s**9 -
                  3024*s**8 + 1344*s**7 + 1323*s**5 - 2904*s**4 + 343*s, [s, s**4 - x -
                                                                          1]))  # orig expr has 2 real roots: -0.91, -0.15

    # orig expr has 1 real root: 19.53
    assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3) - 2),
                 (729*s**13 + 1242*s**12 + 18496*s**10 + 129701*s**9 + 388602*s**8 +
                  453312*s**7 - 612864*s**6 - 3337173*s**5 - 6332418*s**4 - 7134912*s**3
                  - 5064768*s**2 - 2111913*s - 398034, [s, s**4 - x - 1]))

    ans = solve(sqrt(x) + sqrt(x + 1) -
                sqrt(1 - x) - sqrt(2 + x))
    assert len(ans) == 1 and NS(ans[0][x])[:4] == '0.73'
    # the fence optimization problem
    # https://github.com/sympy/sympy/issues/4793#issuecomment-36994519
    eq = F - (2*x + 2*y + sqrt(x**2 + y**2))
    ans = 2*F/7 - sqrt(2)*F/14
    X = solve(eq, x, check=False)
    for xi in reversed(X):  # reverse since currently, ans is the 2nd one
        Y = solve((x*y).subs(xi).diff(y), y,
                  simplify=False, check=False)
        if any((a[y] - ans).expand().is_zero for a in Y):
            break
    else:
        assert None  # no answer was found
    assert (solve(sqrt(x + 1) + root(x, 3) - 2) ==
            [{x: (-11/(9*cbrt(Rational(47, 54) + sqrt(93)/6)) +
                  Rational(1, 3) + cbrt(Rational(47, 54) +
                                        sqrt(93)/6))**3}])
    assert (solve(sqrt(sqrt(x + 1)) + cbrt(x) - 2) ==
            [{x: (-sqrt(-2*cbrt(Rational(-1, 16) + sqrt(6913)/16) +
                        6/cbrt(Rational(-1, 16) + sqrt(6913)/16) +
                        Rational(17, 2) +
                        121/(4*sqrt(-6/cbrt(Rational(-1, 16) +
                                            sqrt(6913)/16) +
                                    2*cbrt(Rational(-1, 16) +
                                           sqrt(6913)/16) +
                                    Rational(17, 4))))/2 +
                  sqrt(-6/cbrt(Rational(-1, 16) + sqrt(6913)/16) +
                       2*cbrt(Rational(-1, 16) + sqrt(6913)/16) +
                       Rational(17, 4))/2 + Rational(9, 4))**3}])
    assert (solve(sqrt(x) + root(sqrt(x) + 1, 3) - 2) ==
            [{x: (-cbrt(Rational(81, 2) + 3*sqrt(741)/2)/3 +
                  (Rational(81, 2) + 3*sqrt(741)/2)**Rational(-1, 3) + 2)**2}])
    eq = (-x + (Rational(1, 2) - sqrt(3)*I/2)*cbrt(3*x**3/2 - x*(3*x**2 - 34)/2 +
                                                   sqrt((-3*x**3 + x*(3*x**2 - 34) + 90)**2/4 - Rational(39304, 27)) -
                                                   45) + 34/(3*(Rational(1, 2) - sqrt(3)*I/2)*cbrt(3*x**3/2 -
                                                                                                   x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2 - 34) + 90)**2/4 -
                                                                                                                            Rational(39304, 27)) - 45)))
    assert check(unrad(eq),
                 (s**6 - sqrt(3)*s**6*I + 102*cbrt(12)*s**4 +
                  102*2**Rational(2, 3)*3**Rational(5, 6)*s**4*I + 1620*s**3 - 1620*sqrt(3)*s**3*I -
                  13872*cbrt(18)*s**2 + 471648 - 471648*sqrt(3)*I, [s, s**3 - 306*x
                                                                    - sqrt(3)*sqrt(31212*x**2 - 165240*x + 61484) + 810]))
    assert solve(eq, x, check=False) != []  # not other code errors
コード例 #30
0
ファイル: test_piecewise.py プロジェクト: Blendify/diofant
def test_piecewise_solve2():
    f = Piecewise(((x - 2)**2, x >= 0), (0, True))
    C0 = Symbol('C0', negative=True)
    assert solve(f, x) == [{x: 2}, {x: C0}]
コード例 #31
0
def test_sympyissue_11553():
    eqs = (x + y + 1, x + GoldenRatio)
    assert solve(eqs, x, y) == [{x: -GoldenRatio, y: -1 + GoldenRatio}]
コード例 #32
0
def test_RootOf_evalf():
    real = RootOf(x**3 + x + 3, 0).evalf(20)

    assert real.epsilon_eq(Float("-1.2134116627622296341"))

    re, im = RootOf(x**3 + x + 3, 1).evalf(20).as_real_imag()

    assert re.epsilon_eq(+Float("0.60670583138111481707"))
    assert im.epsilon_eq(-Float("1.45061224918844152650"))

    re, im = RootOf(x**3 + x + 3, 2).evalf(20).as_real_imag()

    assert re.epsilon_eq(Float("0.60670583138111481707"))
    assert im.epsilon_eq(Float("1.45061224918844152650"))

    p = legendre_poly(4, x, polys=True)
    roots = [str(r.evalf(17)) for r in p.real_roots()]
    assert roots == [
        "-0.86113631159405258",
        "-0.33998104358485626",
        "0.33998104358485626",
        "0.86113631159405258",
    ]

    re = RootOf(x**5 - 5 * x + 12, 0).evalf(20)
    assert re.epsilon_eq(Float("-1.84208596619025438271"))

    re, im = RootOf(x**5 - 5 * x + 12, 1).evalf(20).as_real_imag()
    assert re.epsilon_eq(Float("-0.351854240827371999559"))
    assert im.epsilon_eq(Float("-1.709561043370328882010"))

    re, im = RootOf(x**5 - 5 * x + 12, 2).evalf(20).as_real_imag()
    assert re.epsilon_eq(Float("-0.351854240827371999559"))
    assert im.epsilon_eq(Float("+1.709561043370328882010"))

    re, im = RootOf(x**5 - 5 * x + 12, 3).evalf(20).as_real_imag()
    assert re.epsilon_eq(Float("+1.272897223922499190910"))
    assert im.epsilon_eq(Float("-0.719798681483861386681"))

    re, im = RootOf(x**5 - 5 * x + 12, 4).evalf(20).as_real_imag()
    assert re.epsilon_eq(Float("+1.272897223922499190910"))
    assert im.epsilon_eq(Float("+0.719798681483861386681"))

    # issue sympy/sympy#6393
    assert str(RootOf(x**5 + 2 * x**4 + x**3 - 68719476736,
                      0).evalf(3)) == '147.'
    eq = (531441 * x**11 + 3857868 * x**10 + 13730229 * x**9 +
          32597882 * x**8 + 55077472 * x**7 + 60452000 * x**6 +
          32172064 * x**5 - 4383808 * x**4 - 11942912 * x**3 - 1506304 * x**2 +
          1453312 * x + 512)
    a, b = RootOf(eq, 1).evalf(2).as_real_imag()
    c, d = RootOf(eq, 2).evalf(2).as_real_imag()
    assert a == c
    assert b < d
    assert b == -d
    # issue sympy/sympy#6451
    r = RootOf(legendre_poly(64, x), 7)
    assert r.evalf(2) == r.evalf(100).evalf(2)
    # issue sympy/sympy#8617
    ans = [w[x].evalf(2) for w in solve(x**3 - x - 4)]
    assert RootOf(exp(x)**3 - exp(x) - 4, 0).evalf(2) in ans
    # issue sympy/sympy#9019
    r0 = RootOf(x**2 + 1, 0, radicals=False)
    r1 = RootOf(x**2 + 1, 1, radicals=False)
    assert r0.evalf(4, chop=True) == -1.0 * I
    assert r1.evalf(4, chop=True) == +1.0 * I

    # make sure verification is used in case a max/min traps the "root"
    assert str(RootOf(4 * x**5 + 16 * x**3 + 12 * x**2 + 7,
                      0).evalf(3)) == '-0.976'

    assert isinstance(RootOf(x**3 + y * x + 1, x, 0).evalf(2), RootOf)

    assert RootOf(x**3 + I * x + 2,
                  0).evalf(7) == (Float('-1.260785326', dps=7) +
                                  I * Float('0.2684419416', dps=7))

    r = RootOf(x**2 - 4456178 * x + 60372201703370, 0, radicals=False)
    assert r.evalf(2) == Float('2.2282e+6',
                               dps=2) - I * Float('7.4465e+6', dps=2)
コード例 #33
0
ファイル: test_sqrtdenest.py プロジェクト: skirpichev/diofant
def test_unrad1_fail():
    assert solve(sqrt(x + root(x, 3)) + root(x - y, 5), y) != []
コード例 #34
0
def test_RootOf_evalf():
    real = RootOf(x**3 + x + 3, 0).evalf(20)

    assert real.epsilon_eq(Float("-1.2134116627622296341"))

    re, im = RootOf(x**3 + x + 3, 1).evalf(20).as_real_imag()

    assert re.epsilon_eq( Float("0.60670583138111481707"))
    assert im.epsilon_eq(-Float("1.45061224918844152650"))

    re, im = RootOf(x**3 + x + 3, 2).evalf(20).as_real_imag()

    assert re.epsilon_eq(Float("0.60670583138111481707"))
    assert im.epsilon_eq(Float("1.45061224918844152650"))

    p = legendre_poly(4, x, polys=True)
    roots = [str(r.evalf(17)) for r in p.real_roots()]
    assert roots == [
        "-0.86113631159405258",
        "-0.33998104358485626",
        "0.33998104358485626",
        "0.86113631159405258",
    ]

    re = RootOf(x**5 - 5*x + 12, 0).evalf(20)
    assert re.epsilon_eq(Float("-1.84208596619025438271"))

    re, im = RootOf(x**5 - 5*x + 12, 1).evalf(20).as_real_imag()
    assert re.epsilon_eq(Float("-0.351854240827371999559"))
    assert im.epsilon_eq(Float("-1.709561043370328882010"))

    re, im = RootOf(x**5 - 5*x + 12, 2).evalf(20).as_real_imag()
    assert re.epsilon_eq(Float("-0.351854240827371999559"))
    assert im.epsilon_eq(Float("+1.709561043370328882010"))

    re, im = RootOf(x**5 - 5*x + 12, 3).evalf(20).as_real_imag()
    assert re.epsilon_eq(Float("+1.272897223922499190910"))
    assert im.epsilon_eq(Float("-0.719798681483861386681"))

    re, im = RootOf(x**5 - 5*x + 12, 4).evalf(20).as_real_imag()
    assert re.epsilon_eq(Float("+1.272897223922499190910"))
    assert im.epsilon_eq(Float("+0.719798681483861386681"))

    # issue sympy/sympy#6393
    assert str(RootOf(x**5 + 2*x**4 + x**3 - 68719476736, 0).evalf(3)) == '147.'
    eq = (531441*x**11 + 3857868*x**10 + 13730229*x**9 + 32597882*x**8 +
          55077472*x**7 + 60452000*x**6 + 32172064*x**5 - 4383808*x**4 -
          11942912*x**3 - 1506304*x**2 + 1453312*x + 512)
    a, b = RootOf(eq, 1).evalf(2).as_real_imag()
    c, d = RootOf(eq, 2).evalf(2).as_real_imag()
    assert a == c
    assert b < d
    assert b == -d
    # issue sympy/sympy#6451
    r = RootOf(legendre_poly(64, x), 7)
    assert r.evalf(2) == r.evalf(100).evalf(2)
    # issue sympy/sympy#8617
    ans = [w[x].evalf(2) for w in solve(x**3 - x - 4)]
    assert RootOf(exp(x)**3 - exp(x) - 4, 0).evalf(2) in ans
    # issue sympy/sympy#9019
    r0 = RootOf(x**2 + 1, 0, radicals=False)
    r1 = RootOf(x**2 + 1, 1, radicals=False)
    assert r0.evalf(4, chop=True) == -1.0*I
    assert r1.evalf(4, chop=True) == +1.0*I

    # make sure verification is used in case a max/min traps the "root"
    assert str(RootOf(4*x**5 + 16*x**3 + 12*x**2 + 7, 0).evalf(3)) == '-0.976'

    assert isinstance(RootOf(x**3 + y*x + 1, x, 0).evalf(2), RootOf)

    assert RootOf(x**3 + I*x + 2, 0).evalf(7) == (Float('-1.260785326', dps=7) +
                                                  I*Float('0.2684419416', dps=7))

    r = RootOf(x**2 - 4456178*x + 60372201703370, 0, radicals=False)
    assert r.evalf(2) == Float('2.2282e+6', dps=2) - I*Float('7.4465e+6', dps=2)
コード例 #35
0
ファイル: test_sqrtdenest.py プロジェクト: skirpichev/diofant
def test_unrad2():
    assert solve(root(x**3 - 3*x**2, 3) + 1 - x) == []
    assert solve(root(x + 1, 3) + root(x**2 - 2, 5) + 1) == []
コード例 #36
0
    def _ratsimpmodprime(a, b, allsol, N=0, D=0):
        """
        Computes a rational simplification of ``a/b`` which minimizes
        the sum of the total degrees of the numerator and the denominator.

        The algorithm proceeds by looking at ``a * d - b * c`` modulo
        the ideal generated by ``G`` for some ``c`` and ``d`` with degree
        less than ``a`` and ``b`` respectively.
        The coefficients of ``c`` and ``d`` are indeterminates and thus
        the coefficients of the normalform of ``a * d - b * c`` are
        linear polynomials in these indeterminates.
        If these linear polynomials, considered as system of
        equations, have a nontrivial solution, then `\frac{a}{b}
        \equiv \frac{c}{d}` modulo the ideal generated by ``G``. So,
        by construction, the degree of ``c`` and ``d`` is less than
        the degree of ``a`` and ``b``, so a simpler representation
        has been found.
        After a simpler representation has been found, the algorithm
        tries to reduce the degree of the numerator and denominator
        and returns the result afterwards.

        As an extension, if quick=False, we look at all possible degrees such
        that the total degree is less than *or equal to* the best current
        solution. We retain a list of all solutions of minimal degree, and try
        to find the best one at the end.
        """
        c, d = a, b
        steps = 0

        maxdeg = a.total_degree() + b.total_degree()
        if quick:
            bound = maxdeg - 1
        else:
            bound = maxdeg
        while N + D <= bound:
            if (N, D) in tested:
                break
            tested.add((N, D))

            M1 = staircase(N)
            M2 = staircase(D)
            debug('%s / %s: %s, %s' % (N, D, M1, M2))

            Cs = symbols("c:%d" % len(M1), cls=Dummy)
            Ds = symbols("d:%d" % len(M2), cls=Dummy)
            ng = Cs + Ds

            c_hat = Poly(sum(Cs[i] * M1[i] for i in range(len(M1))),
                         opt.gens + ng)
            d_hat = Poly(sum(Ds[i] * M2[i] for i in range(len(M2))),
                         opt.gens + ng)

            r = reduced(a * d_hat - b * c_hat,
                        G,
                        opt.gens + ng,
                        order=opt.order,
                        polys=True)[1]

            S = Poly(r, gens=opt.gens).coeffs()
            sol = solve(S, Cs + Ds, particular=True, quick=True)

            if sol and not all([s == 0 for s in sol.values()]):
                c = c_hat.subs(sol)
                d = d_hat.subs(sol)

                # The "free" variables occuring before as parameters
                # might still be in the substituted c, d, so set them
                # to the value chosen before:
                c = c.subs(dict(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))
                d = d.subs(dict(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))

                c = Poly(c, opt.gens)
                d = Poly(d, opt.gens)
                if d == 0:
                    raise ValueError('Ideal not prime?')

                allsol.append((c_hat, d_hat, S, Cs + Ds))
                if N + D != maxdeg:
                    allsol = [allsol[-1]]

                break

            steps += 1
            N += 1
            D += 1

        if steps > 0:
            c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps)
            c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D)

        return c, d, allsol