示例#1
0
def test_Abs_rewrite():
    x = Symbol('x', real=True)
    a = Abs(x).rewrite(Heaviside).expand()
    assert a == x*Heaviside(x) - x*Heaviside(-x)
    for i in [-2, -1, 0, 1, 2]:
        assert a.subs(x, i) == abs(i)
    y = Symbol('y')
    assert Abs(y).rewrite(Heaviside) == Abs(y)
def test_Abs_rewrite():
    x = Symbol("x", real=True)
    a = Abs(x).rewrite(Heaviside).expand()
    assert a == x * Heaviside(x) - x * Heaviside(-x)
    for i in [-2, -1, 0, 1, 2]:
        assert a.subs(x, i) == abs(i)
    y = Symbol("y")
    assert Abs(y).rewrite(Heaviside) == Abs(y)

    x, y = Symbol("x", real=True), Symbol("y")
    assert Abs(x).rewrite(Piecewise) == Piecewise((x, x >= 0), (-x, True))
    assert Abs(y).rewrite(Piecewise) == Abs(y)
def derive_solution():
    from sympy import symbols, Matrix, cse, cos, sin, Abs, Rational,acos,asin

    cs,K,tec,nu,phase,sigma_phase,alpha,beta,tec_p,cs_p,sigma_tec,sigma_cs = symbols('cs K tec nu phase sigma_phase alpha beta tec_p cs_p sigma_tec sigma_cs', real=True)
    g = K*tec/nu + cs*alpha

    L = Abs(g - phase)/sigma_phase + beta*((tec - tec_p)**Rational(2)/sigma_tec**Rational(2)/Rational(2) + (cs -  cs_p)**Rational(2)/sigma_cs**Rational(2)/Rational(2))

    req,res = cse(L,optimizations='basic')
    for line in req:
        print("{} = {}".format(line[0],line[1]).replace("Abs","np.abs").replace("cos","np.cos").replace("sin","np.sin").replace("sign","np.sign"))
    print("{}".format(res[0]).replace("Abs","np.abs").replace("cos","np.cos").replace("sin","np.sin").replace("sign","np.sign"))
    print()

    grad = Matrix([sigma_tec**Rational(2)*L.diff(tec), sigma_cs**Rational(2)*L.diff(cs)])
    req,res = cse(grad,optimizations='basic')
    for line in req:
        print("{} = {}".format(line[0],line[1]).replace("Abs","np.abs").replace("cos","np.cos").replace("sin","np.sin").replace("sign","np.sign"))
    print("{}".format(res[0]).replace("Abs","np.abs").replace("cos","np.cos").replace("sin","np.sin").replace("sign","np.sign"))
    print()

    H = Matrix([[L.diff(tec).diff(tec),L.diff(tec).diff(cs)],[L.diff(cs).diff(tec),L.diff(cs).diff(cs)]])

    req,res = cse(H,optimizations='basic')
    for line in req:
        print("{} = {}".format(line[0],line[1]).replace("Abs","np.abs").replace("cos","np.cos").replace("sin","np.sin").replace("sign","np.sign"))
    print("{}".format(res[0]).replace("Abs","np.abs").replace("cos","np.cos").replace("sin","np.sin").replace("sign","np.sign"))
示例#4
0
def test_Abs():
    raises(TypeError, lambda: Abs(C.Interval(2, 3)))  # issue 8717

    x, y = symbols('x,y')
    assert sign(sign(x)) == sign(x)
    assert sign(x * y).func is sign
    assert Abs(0) == 0
    assert Abs(1) == 1
    assert Abs(-1) == 1
    assert Abs(I) == 1
    assert Abs(-I) == 1
    assert Abs(nan) == nan
    assert Abs(I * pi) == pi
    assert Abs(-I * pi) == pi
    assert Abs(I * x) == Abs(x)
    assert Abs(-I * x) == Abs(x)
    assert Abs(-2 * x) == 2 * Abs(x)
    assert Abs(-2.0 * x) == 2.0 * Abs(x)
    assert Abs(2 * pi * x * y) == 2 * pi * Abs(x * y)
    assert Abs(conjugate(x)) == Abs(x)
    assert conjugate(Abs(x)) == Abs(x)

    a = Symbol('a', positive=True)
    assert Abs(2 * pi * x * a) == 2 * pi * a * Abs(x)
    assert Abs(2 * pi * I * x * a) == 2 * pi * a * Abs(x)

    x = Symbol('x', real=True)
    n = Symbol('n', integer=True)
    assert Abs((-1)**n) == 1
    assert x**(2 * n) == Abs(x)**(2 * n)
    assert Abs(x).diff(x) == sign(x)
    assert abs(x) == Abs(x)  # Python built-in
    assert Abs(x)**3 == x**2 * Abs(x)
    assert Abs(x)**4 == x**4
    assert (Abs(x)**(3 * n)).args == (Abs(x), 3 * n
                                      )  # leave symbolic odd unchanged
    assert (1 / Abs(x)).args == (Abs(x), -1)
    assert 1 / Abs(x)**3 == 1 / (x**2 * Abs(x))
    assert Abs(x)**-3 == Abs(x) / (x**4)
    assert Abs(x**3) == x**2 * Abs(x)

    x = Symbol('x', imaginary=True)
    assert Abs(x).diff(x) == -sign(x)

    eq = -sqrt(10 + 6 * sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3 * sqrt(3))
    # if there is a fast way to know when you can and when you cannot prove an
    # expression like this is zero then the equality to zero is ok
    assert abs(eq).func is Abs or abs(eq) == 0
    # but sometimes it's hard to do this so it's better not to load
    # abs down with tests that will be very slow
    q = 1 + sqrt(2) - 2 * sqrt(3) + 1331 * sqrt(6)
    p = expand(q**3)**Rational(1, 3)
    d = p - q
    assert abs(d).func is Abs or abs(d) == 0

    assert Abs(4 * exp(pi * I / 4)) == 4
    assert Abs(3**(2 + I)) == 9
    assert Abs((-3)**(1 - I)) == 3 * exp(pi)

    assert Abs(oo) is oo
    assert Abs(-oo) is oo
    assert Abs(oo + I) is oo
    assert Abs(oo + I * oo) is oo

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False
示例#5
0
def test_eigen():
    R = Rational
    M = Matrix.eye(3)
    assert M.eigenvals(multiple=False) == {S.One: 3}
    assert M.eigenvals(multiple=True) == [1, 1, 1]

    assert M.eigenvects() == ([
        (1, 3, [Matrix([1, 0, 0]),
                Matrix([0, 1, 0]),
                Matrix([0, 0, 1])])
    ])

    assert M.left_eigenvects() == ([
        (1, 3, [Matrix([[1, 0, 0]]),
                Matrix([[0, 1, 0]]),
                Matrix([[0, 0, 1]])])
    ])

    M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]])

    assert M.eigenvals() == {2 * S.One: 1, -S.One: 1, S.Zero: 1}

    assert M.eigenvects() == ([(-1, 1, [Matrix([-1, 1, 0])]),
                               (0, 1, [Matrix([0, -1, 1])]),
                               (2, 1, [Matrix([R(2, 3), R(1, 3), 1])])])

    assert M.left_eigenvects() == ([(-1, 1, [Matrix([[-2, 1, 1]])]),
                                    (0, 1, [Matrix([[-1, -1, 1]])]),
                                    (2, 1, [Matrix([[1, 1, 1]])])])

    a = Symbol('a')
    M = Matrix([[a, 0], [0, 1]])

    assert M.eigenvals() == {a: 1, S.One: 1}

    M = Matrix([[1, -1], [1, 3]])
    assert M.eigenvects() == ([(2, 2, [Matrix(2, 1, [-1, 1])])])
    assert M.left_eigenvects() == ([(2, 2, [Matrix([[1, 1]])])])

    M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    a = R(15, 2)
    b = 3 * 33**R(1, 2)
    c = R(13, 2)
    d = (R(33, 8) + 3 * b / 8)
    e = (R(33, 8) - 3 * b / 8)

    def NS(e, n):
        return str(N(e, n))

    r = [
        (a - b / 2, 1, [
            Matrix([
                (12 + 24 / (c - b / 2)) / ((c - b / 2) * e) + 3 / (c - b / 2),
                (6 + 12 / (c - b / 2)) / e, 1
            ])
        ]),
        (0, 1, [Matrix([1, -2, 1])]),
        (a + b / 2, 1, [
            Matrix([
                (12 + 24 / (c + b / 2)) / ((c + b / 2) * d) + 3 / (c + b / 2),
                (6 + 12 / (c + b / 2)) / d, 1
            ])
        ]),
    ]
    r1 = [(NS(r[i][0], 2), NS(r[i][1], 2), [NS(j, 2) for j in r[i][2][0]])
          for i in range(len(r))]
    r = M.eigenvects()
    r2 = [(NS(r[i][0], 2), NS(r[i][1], 2), [NS(j, 2) for j in r[i][2][0]])
          for i in range(len(r))]
    assert sorted(r1) == sorted(r2)

    eps = Symbol('eps', real=True)

    M = Matrix([[abs(eps), I * eps], [-I * eps, abs(eps)]])

    assert M.eigenvects() == ([
        (0, 1, [Matrix([[-I * eps / abs(eps)], [1]])]),
        (2 * abs(eps), 1, [Matrix([[I * eps / abs(eps)], [1]])]),
    ])

    assert M.left_eigenvects() == ([
        (0, 1, [Matrix([[I * eps / Abs(eps), 1]])]),
        (2 * Abs(eps), 1, [Matrix([[-I * eps / Abs(eps), 1]])])
    ])

    M = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
    M._eigenvects = M.eigenvects(simplify=False)
    assert max(i.q for i in M._eigenvects[0][2][0]) > 1
    M._eigenvects = M.eigenvects(simplify=True)
    assert max(i.q for i in M._eigenvects[0][2][0]) == 1
    M = Matrix([[Rational(1, 4), 1], [1, 1]])
    assert M.eigenvects(simplify=True) == [
        (Rational(5, 8) - sqrt(73) / 8, 1,
         [Matrix([[-sqrt(73) / 8 - Rational(3, 8)], [1]])]),
        (Rational(5, 8) + sqrt(73) / 8, 1,
         [Matrix([[Rational(-3, 8) + sqrt(73) / 8], [1]])])
    ]
    with dotprodsimp(True):
        assert M.eigenvects(simplify=False) == [
            (Rational(5, 8) - sqrt(73) / 8, 1,
             [Matrix([[-1 / (-Rational(3, 8) + sqrt(73) / 8)], [1]])]),
            (Rational(5, 8) + sqrt(73) / 8, 1,
             [Matrix([[8 / (3 + sqrt(73))], [1]])])
        ]

    # issue 10719
    assert Matrix([]).eigenvals() == {}
    assert Matrix([]).eigenvals(multiple=True) == []
    assert Matrix([]).eigenvects() == []

    # issue 15119
    raises(NonSquareMatrixError,
           lambda: Matrix([[1, 2], [0, 4], [0, 0]]).eigenvals())
    raises(NonSquareMatrixError,
           lambda: Matrix([[1, 0], [3, 4], [5, 6]]).eigenvals())
    raises(NonSquareMatrixError,
           lambda: Matrix([[1, 2, 3], [0, 5, 6]]).eigenvals())
    raises(NonSquareMatrixError,
           lambda: Matrix([[1, 0, 0], [4, 5, 0]]).eigenvals())
    raises(
        NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [0, 5, 6]]).eigenvals(
            error_when_incomplete=False))
    raises(
        NonSquareMatrixError, lambda: Matrix([[1, 0, 0], [4, 5, 0]]).eigenvals(
            error_when_incomplete=False))

    # issue 15125
    from sympy.core.function import count_ops
    q = Symbol("q", positive=True)
    m = Matrix([[-2, exp(-q), 1], [exp(q), -2, 1], [1, 1, -2]])
    assert count_ops(m.eigenvals(simplify=False)) > count_ops(
        m.eigenvals(simplify=True))
    assert count_ops(m.eigenvals(simplify=lambda x: x)) > count_ops(
        m.eigenvals(simplify=True))

    assert isinstance(m.eigenvals(simplify=True, multiple=False), dict)
    assert isinstance(m.eigenvals(simplify=True, multiple=True), list)
    assert isinstance(m.eigenvals(simplify=lambda x: x, multiple=False), dict)
    assert isinstance(m.eigenvals(simplify=lambda x: x, multiple=True), list)
示例#6
0
class TestAllGood(object):
    # These latex strings should parse to the corresponding SymPy expression
    GOOD_PAIRS = [
        ("0", 0),
        ("1", 1),
        ("-3.14", -3.14),
        ("5-3", _Add(5, -3)),
        ("(-7.13)(1.5)", _Mul(Rational('-7.13'), Rational('1.5'))),
        ("\\left(-7.13\\right)\\left(1.5\\right)", _Mul(Rational('-7.13'), Rational('1.5'))),
        ("x", x),
        ("2x", 2 * x),
        ("x^2", x**2),
        ("x^{3 + 1}", x**_Add(3, 1)),
        ("x^{\\left\\{3 + 1\\right\\}}", x**_Add(3, 1)),
        ("-3y + 2x", _Add(_Mul(2, x), Mul(-1, 3, y, evaluate=False))),
        ("-c", -c),
        ("a \\cdot b", a * b),
        ("a / b", a / b),
        ("a \\div b", a / b),
        ("a + b", a + b),
        ("a + b - a", Add(a, b, _Mul(-1, a), evaluate=False)),
        ("a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)),
        ("a^2 + b^2 != 2c^2", Ne(a**2 + b**2, 2 * c**2)),
        ("a\\mod b", Mod(a, b)),
        ("\\sin \\theta", sin(theta)),
        ("\\sin(\\theta)", sin(theta)),
        ("\\sin\\left(\\theta\\right)", sin(theta)),
        ("\\sin^{-1} a", asin(a)),
        ("\\sin a \\cos b", _Mul(sin(a), cos(b))),
        ("\\sin \\cos \\theta", sin(cos(theta))),
        ("\\sin(\\cos \\theta)", sin(cos(theta))),
        ("\\arcsin(a)", asin(a)),
        ("\\arccos(a)", acos(a)),
        ("\\arctan(a)", atan(a)),
        ("\\sinh(a)", sinh(a)),
        ("\\cosh(a)", cosh(a)),
        ("\\tanh(a)", tanh(a)),
        ("\\sinh^{-1}(a)", asinh(a)),
        ("\\cosh^{-1}(a)", acosh(a)),
        ("\\tanh^{-1}(a)", atanh(a)),
        ("\\arcsinh(a)", asinh(a)),
        ("\\arccosh(a)", acosh(a)),
        ("\\arctanh(a)", atanh(a)),
        ("\\arsinh(a)", asinh(a)),
        ("\\arcosh(a)", acosh(a)),
        ("\\artanh(a)", atanh(a)),
        ("\\operatorname{arcsinh}(a)", asinh(a)),
        ("\\operatorname{arccosh}(a)", acosh(a)),
        ("\\operatorname{arctanh}(a)", atanh(a)),
        ("\\operatorname{arsinh}(a)", asinh(a)),
        ("\\operatorname{arcosh}(a)", acosh(a)),
        ("\\operatorname{artanh}(a)", atanh(a)),
        ("\\operatorname{gcd}(a, b)", UnevaluatedExpr(gcd(a, b))),
        ("\\operatorname{lcm}(a, b)", UnevaluatedExpr(lcm(a, b))),
        ("\\operatorname{gcd}(a,b)", UnevaluatedExpr(gcd(a, b))),
        ("\\operatorname{lcm}(a,b)", UnevaluatedExpr(lcm(a, b))),
        ("\\operatorname{floor}(a)", floor(a)),
        ("\\operatorname{ceil}(b)", ceiling(b)),
        ("\\cos^2(x)", cos(x)**2),
        ("\\cos(x)^2", cos(x)**2),
        ("\\gcd(a, b)", UnevaluatedExpr(gcd(a, b))),
        ("\\lcm(a, b)", UnevaluatedExpr(lcm(a, b))),
        ("\\gcd(a,b)", UnevaluatedExpr(gcd(a, b))),
        ("\\lcm(a,b)", UnevaluatedExpr(lcm(a, b))),
        ("\\floor(a)", floor(a)),
        ("\\ceil(b)", ceiling(b)),
        ("\\max(a, b)", Max(a, b)),
        ("\\min(a, b)", Min(a, b)),
        ("\\frac{a}{b}", a / b),
        ("\\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))),
        ("\\frac{7}{3}", _Mul(7, _Pow(3, -1))),
        ("(\\csc x)(\\sec y)", csc(x) * sec(y)),
        ("\\lim_{x \\to 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\rightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\Rightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\longrightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\Longrightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\to 3^{+}} a", Limit(a, x, 3, dir='+')),
        ("\\lim_{x \\to 3^{-}} a", Limit(a, x, 3, dir='-')),
        ("\\infty", oo),
        ("\\infty\\%", oo),
        ("\\$\\infty", oo),
        ("-\\infty", -oo),
        ("-\\infty\\%", -oo),
        ("-\\$\\infty", -oo),
        ("\\lim_{x \\to \\infty} \\frac{1}{x}", Limit(_Mul(1, _Pow(x, -1)), x, oo)),
        ("\\frac{d}{dx} x", Derivative(x, x)),
        ("\\frac{d}{dt} x", Derivative(x, t)),
        # ("f(x)", f(x)),
        # ("f(x, y)", f(x, y)),
        # ("f(x, y, z)", f(x, y, z)),
        # ("\\frac{d f(x)}{dx}", Derivative(f(x), x)),
        # ("\\frac{d\\theta(x)}{dx}", Derivative(theta(x), x)),
        ("|x|", _Abs(x)),
        ("\\left|x\\right|", _Abs(x)),
        ("||x||", _Abs(Abs(x))),
        ("|x||y|", _Abs(x) * _Abs(y)),
        ("||x||y||", _Abs(_Abs(x) * _Abs(y))),
        ("\\lfloor x\\rfloor", floor(x)),
        ("\\lceil y\\rceil", ceiling(y)),
        ("\\pi^{|xy|}", pi**_Abs(x * y)),
        ("\\frac{\\pi}{3}", _Mul(pi, _Pow(3, -1))),
        ("\\sin{\\frac{\\pi}{2}}", sin(_Mul(pi, _Pow(2, -1)), evaluate=False)),
        ("a+bI", a + I * b),
        ("e^{I\\pi}", -1),
        ("\\int x dx", Integral(x, x)),
        ("\\int x d\\theta", Integral(x, theta)),
        ("\\int (x^2 - y)dx", Integral(x**2 - y, x)),
        ("\\int x + a dx", Integral(_Add(x, a), x)),
        ("\\int da", Integral(1, a)),
        ("\\int_0^7 dx", Integral(1, (x, 0, 7))),
        ("\\int_a^b x dx", Integral(x, (x, a, b))),
        ("\\int^b_a x dx", Integral(x, (x, a, b))),
        ("\\int_{a}^b x dx", Integral(x, (x, a, b))),
        ("\\int^{b}_a x dx", Integral(x, (x, a, b))),
        ("\\int_{a}^{b} x dx", Integral(x, (x, a, b))),
        ("\\int_{  }^{}x dx", Integral(x, x)),
        ("\\int^{  }_{ }x dx", Integral(x, x)),
        ("\\int^{b}_{a} x dx", Integral(x, (x, a, b))),
        # ("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
        ("\\int (x+a)", Integral(_Add(x, a), x)),
        ("\\int a + b + c dx", Integral(Add(a, b, c, evaluate=False), x)),
        ("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)),
        ("\\int \\frac{3 dz}{z}", Integral(3 * Pow(z, -1), z)),
        ("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)),
        ("\\int \\frac{1}{a} + \\frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
        ("\\int \\frac{3 \\cdot d\\theta}{\\theta}", Integral(3 * _Pow(theta, -1), theta)),
        ("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
        ("x_0", Symbol('x_0', real=True)),
        ("x_{1}", Symbol('x_1', real=True)),
        ("x_a", Symbol('x_a', real=True)),
        ("x_{b}", Symbol('x_b', real=True)),
        ("h_\\theta", Symbol('h_{\\theta}', real=True)),
        ("h_\\theta ", Symbol('h_{\\theta}', real=True)),
        ("h_{\\theta}", Symbol('h_{\\theta}', real=True)),
        # ("h_{\\theta}(x_0, x_1)", Symbol('h_{theta}', real=True)(Symbol('x_{0}', real=True), Symbol('x_{1}', real=True))),
        ("x!", _factorial(x)),
        ("100!", _factorial(100)),
        ("\\theta!", _factorial(theta)),
        ("(x + 1)!", _factorial(_Add(x, 1))),
        ("\\left(x + 1\\right)!", _factorial(_Add(x, 1))),
        ("(x!)!", _factorial(_factorial(x))),
        ("x!!!", _factorial(_factorial(_factorial(x)))),
        ("5!7!", _Mul(_factorial(5), _factorial(7))),
        ("\\sqrt{x}", sqrt(x)),
        ("\\sqrt{x + b}", sqrt(_Add(x, b))),
        ("\\sqrt[3]{\\sin x}", root(sin(x), 3)),
        ("\\sqrt[y]{\\sin x}", root(sin(x), y)),
        ("\\sqrt[\\theta]{\\sin x}", root(sin(x), theta)),
        ("x < y", StrictLessThan(x, y)),
        ("x \\leq y", LessThan(x, y)),
        ("x > y", StrictGreaterThan(x, y)),
        ("x \\geq y", GreaterThan(x, y)),
        ("\\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
        ("\\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
        ("\\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
        ("\\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
        ("\\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))),
        ("\\sum_{n = 0}^{\\infty} \\frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))),
        ("\\prod_{a = b}^{c} x", Product(x, (a, b, c))),
        ("\\prod_{a = b}^c x", Product(x, (a, b, c))),
        ("\\prod^{c}_{a = b} x", Product(x, (a, b, c))),
        ("\\prod^c_{a = b} x", Product(x, (a, b, c))),
        ("\\ln x", _log(x, E)),
        ("\\ln xy", _log(x * y, E)),
        ("\\log x", _log(x, 10)),
        ("\\log xy", _log(x * y, 10)),
        # ("\\log_2 x", _log(x, 2)),
        ("\\log_{2} x", _log(x, 2)),
        # ("\\log_a x", _log(x, a)),
        ("\\log_{a} x", _log(x, a)),
        ("\\log_{11} x", _log(x, 11)),
        ("\\log_{a^2} x", _log(x, _Pow(a, 2))),
        ("[x]", x),
        ("[a + b]", _Add(a, b)),
        ("\\frac{d}{dx} [ \\tan x ]", Derivative(tan(x), x)),
        ("2\\overline{x}", 2 * Symbol('xbar', real=True)),
        ("2\\overline{x}_n", 2 * Symbol('xbar_n', real=True)),
        ("\\frac{x}{\\overline{x}_n}", x / Symbol('xbar_n', real=True)),
        ("\\frac{\\sin(x)}{\\overline{x}_n}", sin(Symbol('x', real=True)) / Symbol('xbar_n', real=True)),
        ("2\\bar{x}", 2 * Symbol('xbar', real=True)),
        ("2\\bar{x}_n", 2 * Symbol('xbar_n', real=True)),
        ("\\sin\\left(\\theta\\right) \\cdot4", sin(theta) * 4),
        ("\\ln\\left(\\theta\\right)", _log(theta, E)),
        ("\\ln\\left(x-\\theta\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left(x-\\theta\\right)\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left[x-\\theta\\right]\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left\\{x-\\theta\\right\\}\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left|x-\\theta\\right|\\right)", _log(_Abs(x - theta), E)),
        ("\\frac{1}{2}xy(x+y)", Mul(_Pow(2, -1), x, y, (x + y), evaluate=False)),
        ("\\frac{1}{2}\\theta(x+y)", Mul(_Pow(2, -1), theta, (x + y), evaluate=False)),
        ("1-f(x)", 1 - f * x),

        ("\\begin{matrix}1&2\\\\3&4\\end{matrix}", Matrix([[1, 2], [3, 4]])),
        ("\\begin{matrix}x&x^2\\\\\\sqrt{x}&x\\end{matrix}", Matrix([[x, x**2], [_Pow(x, S.Half), x]])),
        ("\\begin{matrix}\\sqrt{x}\\\\\\sin(\\theta)\\end{matrix}", Matrix([_Pow(x, S.Half), sin(theta)])),
        ("\\begin{pmatrix}1&2\\\\3&4\\end{pmatrix}", Matrix([[1, 2], [3, 4]])),
        ("\\begin{bmatrix}1&2\\\\3&4\\end{bmatrix}", Matrix([[1, 2], [3, 4]])),

        # scientific notation
        ("2.5\\times 10^2", 250),
        ("1,500\\times 10^{-1}", 150),

        # e notation
        ("2.5E2", 250),
        ("1,500E-1", 150),

        # multiplication without cmd
        ("2x2y", Mul(2, x, 2, y, evaluate=False)),
        ("2x2", Mul(2, x, 2, evaluate=False)),
        ("x2", x * 2),

        # lin alg processing
        ("\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(theta, Matrix([[1, 2], [3, 4]]), evaluate=False)),
        ("\\theta\\begin{matrix}1\\\\3\\end{matrix} - \\begin{matrix}-1\\\\2\\end{matrix}", MatAdd(MatMul(theta, Matrix([[1], [3]]), evaluate=False), MatMul(-1, Matrix([[-1], [2]]), evaluate=False), evaluate=False)),
        ("\\theta\\begin{matrix}1&0\\\\0&1\\end{matrix}*\\begin{matrix}3\\\\-2\\end{matrix}", MatMul(theta, Matrix([[1, 0], [0, 1]]), Matrix([3, -2]), evaluate=False)),
        ("\\frac{1}{9}\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(Pow(9, -1, evaluate=False), theta, Matrix([[1, 2], [3, 4]]), evaluate=False)),
        ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix};\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix},\\begin{pmatrix}1\\\\1\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1]), Matrix([1, 1, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right\\}", Matrix([1, 2, 3])),
        ("\\left{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right}", Matrix([1, 2, 3])),
        ("{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}}", Matrix([1, 2, 3])),

        # us dollars
        ("\\$1,000.00", 1000),
        ("\\$543.21", 543.21),
        ("\\$0.009", 0.009),

        # percentages
        ("100\\%", 1),
        ("1.5\\%", 0.015),
        ("0.05\\%", 0.0005),

        # empty set
        ("\\emptyset", S.EmptySet)
    ]

    def test_good_pair(self, s, eq):
        assert_equal(s, eq)
def test_geometric_sums():
    assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi)
    assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1
    assert summation(Rational(1, 2)**n, (n, 1, oo)) == 1
    assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1
    assert summation(2**n, (n, 1, oo)) == oo
    assert summation(2**(-n), (n, 1, oo)) == 1
    assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54)
    assert summation(2**(-4 * n + 3), (n, 1, oo)) == Rational(8, 15)
    assert summation(2**(n + 1), (n, 1, b)).expand() == 4 * (2**b - 1)

    # issue 6664:
    assert summation(x**n, (n, 0, oo)) == \
        Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True))

    assert summation(-2**n, (n, 0, oo)) == -oo
    assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo))

    # issue 6802:
    assert summation((-1)**(2 * x + 2), (x, 0, n)) == n + 1
    assert summation((-2)**(2 * x + 2),
                     (x, 0, n)) == 4 * 4**(n + 1) / S(3) - S(4) / 3
    assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1) / S(2) + S(1) / 2
    assert summation(y**x, (x, a, b)) == \
        Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True))
    assert summation((-2)**(y*x + 2), (x, 0, n)) == \
        4*Piecewise((n + 1, Eq((-2)**y, 1)),
                    ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True))

    # issue 8251:
    assert summation((1 / (n + 1)**2) * n**2, (n, 0, oo)) == oo

    #issue 9908:
    assert Sum(1 / (n**3 - 1),
               (n, -oo, -2)).doit() == summation(1 / (n**3 - 1), (n, -oo, -2))

    #issue 11642:
    result = Sum(0.5**n, (n, 1, oo)).doit()
    assert result == 1
    assert result.is_Float

    result = Sum(0.25**n, (n, 1, oo)).doit()
    assert result == S(1) / 3
    assert result.is_Float

    result = Sum(0.99999**n, (n, 1, oo)).doit()
    assert result == 99999
    assert result.is_Float

    result = Sum(Rational(1, 2)**n, (n, 1, oo)).doit()
    assert result == 1
    assert not result.is_Float

    result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit()
    assert result == S(3) / 2
    assert not result.is_Float

    assert Sum(1.0**n, (n, 1, oo)).doit() == oo
    assert Sum(2.43**n, (n, 1, oo)).doit() == oo

    # Issue 13979:
    i, k, q = symbols('i k q', integer=True)
    result = summation(
        exp(-2 * I * pi * k * i / n) * exp(2 * I * pi * q * i / n) / n,
        (i, 0, n - 1))
    assert result.simplify() == Piecewise(
        (1, Eq(exp(2 * I * pi * (-k + q) / n), 1)), (0, True))
示例#8
0
def test_issue_17292():
    assert simplify(abs(x) / abs(x**2)) == 1 / abs(x)
    # this is bigger than the issue: check that deep processing works
    assert simplify(5 * abs((x**2 - 1) / (x - 1))) == 5 * Abs(x + 1)
def test_sinc_mpmath():
    f = lambdify(x, sinc(x), "mpmath")
    assert Abs(f(1) - sinc(1)).n() < 1e-15
示例#10
0
def test_laplace():
    mu = Symbol("mu")
    b = Symbol("b", positive=True)

    X = Laplace('x', mu, b)
    assert density(X)(x) == exp(-Abs(x - mu) / b) / (2 * b)
示例#11
0
def test_issue_18997():
    assert limit(Abs(log(x)), x, 0) == oo
    assert limit(Abs(log(Abs(x))), x, 0) == oo
示例#12
0
def test_issue_18501():
    assert limit(Abs(log(x - 1)**3 - 1), x, 1, '+') == oo
示例#13
0
def test_issue_12398():
    assert limit(Abs(log(x)/x**3), x, oo) == 0
    assert limit(x*(Abs(log(x)/x**3)/Abs(log(x + 1)/(x + 1)**3) - 1), x, oo) == 3
示例#14
0
def test_issue_3206():
    x = Symbol('x')
    assert Abs(Abs(x)) == Abs(x)
示例#15
0
def test_issue_4035():
    x = Symbol('x')
    assert Abs(x).expand(trig=True) == Abs(x)
    assert sign(x).expand(trig=True) == sign(x)
    assert arg(x).expand(trig=True) == arg(x)
示例#16
0
def test_Abs_properties():
    x = Symbol('x')
    assert Abs(x).is_real is True
    assert Abs(x).is_rational is None
    assert Abs(x).is_positive is None
    assert Abs(x).is_nonnegative is True

    z = Symbol('z', complex=True, zero=False)
    assert Abs(z).is_real is True
    assert Abs(z).is_rational is None
    assert Abs(z).is_positive is True
    assert Abs(z).is_zero is False

    p = Symbol('p', positive=True)
    assert Abs(p).is_real is True
    assert Abs(p).is_rational is None
    assert Abs(p).is_positive is True
    assert Abs(p).is_zero is False

    q = Symbol('q', rational=True)
    assert Abs(q).is_rational is True
    assert Abs(q).is_integer is None
    assert Abs(q).is_positive is None
    assert Abs(q).is_nonnegative is True

    i = Symbol('i', integer=True)
    assert Abs(i).is_integer is True
    assert Abs(i).is_positive is None
    assert Abs(i).is_nonnegative is True

    e = Symbol('n', even=True)
    ne = Symbol('ne', real=True, even=False)
    assert Abs(e).is_even
    assert Abs(ne).is_even is False
    assert Abs(i).is_even is None

    o = Symbol('n', odd=True)
    no = Symbol('no', real=True, odd=False)
    assert Abs(o).is_odd
    assert Abs(no).is_odd is False
    assert Abs(i).is_odd is None
示例#17
0
def test_issue_8821_highprec_from_str():
    s = str(pi.evalf(128))
    p = sympify(s)
    assert Abs(sin(p)) < 1e-127
示例#18
0
文件: test_str.py 项目: Maihj/sympy
def test_Abs():
    assert str(Abs(x)) == "Abs(x)"
    assert str(Abs(Rational(1, 6))) == "1/6"
    assert str(Abs(Rational(-1, 6))) == "1/6"
示例#19
0
def test_issue_19026():
    x = Symbol('x', positive=True)
    assert limit(Abs(log(x) + 1)/log(x), x, oo) == 1
def test_issue_13642():
    if not numpy:
        skip("numpy not installed")
    f = lambdify(x, sinc(x))
    assert Abs(f(1) - sinc(1)).n() < 1e-15
示例#21
0
def AbsSIMD_check(a):
    return Abs(a)
示例#22
0
def cgen_ncomp(ncomp=3, nporder=2, aggstat=False, debug=False):
    """Generates a C function for ncomp (int) number of components.
    The jth key component is always in the first position and the kth
    key component is always in the second.  The number of enrichment 
    stages (NP) is calculated via a taylor series approximation.  The
    order of this approximation may be set with nporder.  Only values
    of 1 or 2 are allowed. The aggstat argument determines whether the
    status messages should be aggreated and printed at the end or output
    as the function executes.
    """
    start_time = time.time()
    stat = _aggstatus('', "generating {0} component enrichment".format(ncomp),
                      aggstat)
    r = range(0, ncomp)
    j = 0
    k = 1

    # setup-symbols
    alpha = Symbol('alpha', positive=True, real=True)
    LpF = Symbol('LpF', positive=True, real=True)
    PpF = Symbol('PpF', positive=True, real=True)
    TpF = Symbol('TpF', positive=True, real=True)
    SWUpF = Symbol('SWUpF', positive=True, real=True)
    SWUpP = Symbol('SWUpP', positive=True, real=True)
    NP = Symbol('NP', positive=True, real=True)  # Enrichment Stages
    NT = Symbol('NT', positive=True, real=True)  # De-enrichment Stages
    NP0 = Symbol('NP0', positive=True,
                 real=True)  # Enrichment Stages Initial Guess
    NT0 = Symbol('NT0', positive=True,
                 real=True)  # De-enrichment Stages Initial Guess
    NP1 = Symbol('NP1', positive=True,
                 real=True)  # Enrichment Stages Computed Value
    NT1 = Symbol('NT1', positive=True,
                 real=True)  # De-enrichment Stages Computed Value
    Mstar = Symbol('Mstar', positive=True, real=True)
    MW = [Symbol('MW[{0}]'.format(i), positive=True, real=True) for i in r]
    beta = [alpha**(Mstar - MWi) for MWi in MW]

    # np_closed helper terms
    NP_b = Symbol('NP_b', real=True)
    NP_2a = Symbol('NP_2a', real=True)
    NP_sqrt_base = Symbol('NP_sqrt_base', real=True)

    xF = [Symbol('xF[{0}]'.format(i), positive=True, real=True) for i in r]
    xPi = [Symbol('xP[{0}]'.format(i), positive=True, real=True) for i in r]
    xTi = [Symbol('xT[{0}]'.format(i), positive=True, real=True) for i in r]
    xPj = Symbol('xPj', positive=True, real=True)
    xFj = xF[j]
    xTj = Symbol('xTj', positive=True, real=True)
    ppf = (xFj - xTj) / (xPj - xTj)
    tpf = (xFj - xPj) / (xTj - xPj)

    xP = [(((xF[i]/ppf)*(beta[i]**(NT+1) - 1))/(beta[i]**(NT+1) - beta[i]**(-NP))) \
                                                                            for i in r]
    xT = [(((xF[i]/tpf)*(1 - beta[i]**(-NP)))/(beta[i]**(NT+1) - beta[i]**(-NP))) \
                                                                            for i in r]
    rfeed = xFj / xF[k]
    rprod = xPj / xP[k]
    rtail = xTj / xT[k]

    # setup constraint equations
    numer = [
        ppf * xP[i] * log(rprod) + tpf * xT[i] * log(rtail) -
        xF[i] * log(rfeed) for i in r
    ]
    denom = [log(beta[j]) * ((beta[i] - 1.0) / (beta[i] + 1.0)) for i in r]
    LoverF = sum([n / d for n, d in zip(numer, denom)])
    SWUoverF = -1.0 * sum(numer)
    SWUoverP = SWUoverF / ppf

    prod_constraint = (xPj/xFj)*ppf - (beta[j]**(NT+1) - 1)/\
                      (beta[j]**(NT+1) - beta[j]**(-NP))
    tail_constraint = (xTj/xFj)*(sum(xT)) - (1 - beta[j]**(-NP))/\
                      (beta[j]**(NT+1) - beta[j]**(-NP))
    #xp_constraint = 1.0 - sum(xP)
    #xf_constraint = 1.0 - sum(xF)
    #xt_constraint = 1.0 - sum(xT)

    # This is NT(NP,...) and is correct!
    #nt_closed = solve(prod_constraint, NT)[0]

    # However, this is NT(NP,...) rewritten (by hand) to minimize the number of NP
    # and M* instances in the expression.  Luckily this is only depends on the key
    # component and remains general no matter the number of components.
    nt_closed = (-MW[0]*log(alpha) + Mstar*log(alpha) + log(xTj) + log((-1.0 + xPj/\
        xF[0])/(xPj - xTj)) - log(alpha**(NP*(MW[0] - Mstar))*(xF[0]*xPj - xPj*xTj)/\
        (-xF[0]*xPj + xF[0]*xTj) + 1))/((MW[0] - Mstar)*log(alpha))

    # new expression for normalized flow rate
    # NOTE: not needed, solved below
    #loverf = LoverF.xreplace({NT: nt_closed})

    # Define the constraint equation with which to solve NP. This is chosen such to
    # minimize the number of ops in the derivatives (and thus np_closed).  Other,
    # more verbose possibilities are commented out.
    #np_constraint = (xP[j]/sum(xP) - xPj).xreplace({NT: nt_closed})
    #np_constraint = (xP[j]- sum(xP)*xPj).xreplace({NT: nt_closed})
    #np_constraint = (xT[j]/sum(xT) - xTj).xreplace({NT: nt_closed})
    np_constraint = (xT[j] - sum(xT) * xTj).xreplace({NT: nt_closed})

    # get closed form approximation of NP via symbolic derivatives
    stat = _aggstatus(stat, "  order-{0} NP approximation".format(nporder),
                      aggstat)
    d0NP = np_constraint.xreplace({NP: NP0})
    d1NP = diff(np_constraint, NP, 1).xreplace({NP: NP0})
    if 1 == nporder:
        np_closed = NP0 - d1NP / d0NP
    elif 2 == nporder:
        d2NP = diff(np_constraint, NP, 2).xreplace({NP: NP0}) / 2.0
        # taylor series polynomial coefficients, grouped by order
        # f(x) = ax**2 + bx + c
        a = d2NP
        b = d1NP - 2 * NP0 * d2NP
        c = d0NP - NP0 * d1NP + NP0 * NP0 * d2NP
        # quadratic eq. (minus only)
        #np_closed = (-b - sqrt(b**2 - 4*a*c)) / (2*a)
        # However, we need to break up this expr as follows to prevent
        # a floating point arithmetic bug if b**2 - 4*a*c is very close
        # to zero but happens to be negative.  LAME!!!
        np_2a = 2 * a
        np_sqrt_base = b**2 - 4 * a * c
        np_closed = (-NP_b - sqrt(NP_sqrt_base)) / (NP_2a)
    else:
        raise ValueError("nporder must be 1 or 2")

    # generate cse for writing out
    msg = "  minimizing ops by eliminating common sub-expressions"
    stat = _aggstatus(stat, msg, aggstat)
    exprstages = [
        Eq(NP_b, b),
        Eq(NP_2a, np_2a),
        # fix for floating point sqrt() error
        Eq(NP_sqrt_base, np_sqrt_base),
        Eq(NP_sqrt_base, Abs(NP_sqrt_base)),
        Eq(NP1, np_closed),
        Eq(NT1, nt_closed).xreplace({NP: NP1})
    ]
    cse_stages = cse(exprstages, numbered_symbols('n'))
    exprothers = [Eq(LpF, LoverF), Eq(PpF, ppf), Eq(TpF, tpf),
                  Eq(SWUpF, SWUoverF), Eq(SWUpP, SWUoverP)] + \
                 [Eq(*z) for z in zip(xPi, xP)] + [Eq(*z) for z in zip(xTi, xT)]
    exprothers = [e.xreplace({NP: NP1, NT: NT1}) for e in exprothers]
    cse_others = cse(exprothers, numbered_symbols('g'))
    exprops = count_ops(exprstages + exprothers)
    cse_ops = count_ops(cse_stages + cse_others)
    msg = "    reduced {0} ops to {1}".format(exprops, cse_ops)
    stat = _aggstatus(stat, msg, aggstat)

    # create function body
    ccode, repnames = cse_to_c(*cse_stages, indent=6, debug=debug)
    ccode_others, repnames_others = cse_to_c(*cse_others,
                                             indent=6,
                                             debug=debug)
    ccode += ccode_others
    repnames |= repnames_others

    msg = "  completed in {0:.3G} s".format(time.time() - start_time)
    stat = _aggstatus(stat, msg, aggstat)
    if aggstat:
        print(stat)
    return ccode, repnames, stat
示例#23
0
def nrpyAbsSIMD_check(a):
    return Abs(a)
示例#24
0
def test_signsimp():
    e = x * (-x + 1) + x * (x - 1)
    assert signsimp(Eq(e, 0)) is S.true
    assert Abs(x - 1) == Abs(1 - x)
    assert signsimp(y - x) == y - x
    assert signsimp(y - x, evaluate=False) == Mul(-1, x - y, evaluate=False)
示例#25
0
def test_ellipse():
    p1 = Point(0, 0)
    p2 = Point(1, 1)
    p3 = Point(x1, x2)
    p4 = Point(0, 1)
    p5 = Point(-1, 0)

    e1 = Ellipse(p1, 1, 1)
    e2 = Ellipse(p2, half, 1)
    e3 = Ellipse(p1, y1, y1)
    c1 = Circle(p1, 1)
    c2 = Circle(p2, 1)
    c3 = Circle(Point(sqrt(2), sqrt(2)), 1)

    # Test creation with three points
    cen, rad = Point(3 * half, 2), 5 * half
    assert Circle(Point(0, 0), Point(3, 0), Point(0, 4)) == Circle(cen, rad)
    raises(GeometryError, "Circle(Point(0,0), Point(1,1), Point(2,2))")

    # Basic Stuff
    assert e1 == c1
    assert e1 != e2
    assert p4 in e1
    assert p2 not in e2
    assert e1.area == pi
    assert e2.area == pi / 2
    assert e3.area == pi * (y1**2)
    assert c1.area == e1.area
    assert c1.circumference == e1.circumference
    assert e3.circumference == 2 * pi * y1

    a = Symbol('a')
    b = Symbol('b')
    e5 = Ellipse(p1, a, b)
    assert e5.circumference == 4*a*C.Integral(((1 - x**2*Abs(b**2 - a**2)/a**2)/(1 - x**2))**(S(1)/2),\
                                            (x, 0, 1))

    assert e2.arbitrary_point() in e2

    # Foci
    f1, f2 = Point(sqrt(12), 0), Point(-sqrt(12), 0)
    ef = Ellipse(Point(0, 0), 4, 2)
    assert ef.foci in [(f1, f2), (f2, f1)]

    # Tangents
    v = sqrt(2) / 2
    p1_1 = Point(v, v)
    p1_2 = p2 + Point(half, 0)
    p1_3 = p2 + Point(0, 1)
    assert e1.tangent_line(p4) == c1.tangent_line(p4)
    assert e2.tangent_line(p1_2) == Line(p1_2, p2 + Point(half, 1))
    assert e2.tangent_line(p1_3) == Line(p1_3, p2 + Point(half, 1))
    assert c1.tangent_line(p1_1) == Line(p1_1, Point(0, sqrt(2)))
    assert e2.is_tangent(Line(p1_2, p2 + Point(half, 1)))
    assert e2.is_tangent(Line(p1_3, p2 + Point(half, 1)))
    assert c1.is_tangent(Line(p1_1, Point(0, sqrt(2))))
    assert e1.is_tangent(Line(Point(0, 0), Point(1, 1))) == False

    # Intersection
    l1 = Line(Point(1, -5), Point(1, 5))
    l2 = Line(Point(-5, -1), Point(5, -1))
    l3 = Line(Point(-1, -1), Point(1, 1))
    l4 = Line(Point(-10, 0), Point(0, 10))
    pts_c1_l3 = [
        Point(sqrt(2) / 2,
              sqrt(2) / 2),
        Point(-sqrt(2) / 2, -sqrt(2) / 2)
    ]

    assert intersection(e2, l4) == []
    assert intersection(c1, Point(1, 0)) == [Point(1, 0)]
    assert intersection(c1, l1) == [Point(1, 0)]
    assert intersection(c1, l2) == [Point(0, -1)]
    assert intersection(c1, l3) in [pts_c1_l3, [pts_c1_l3[1], pts_c1_l3[0]]]
    assert intersection(c1, c2) in [[(1, 0), (0, 1)], [(0, 1), (1, 0)]]
    assert intersection(c1, c3) == [(sqrt(2) / 2, sqrt(2) / 2)]

    # some special case intersections
    csmall = Circle(p1, 3)
    cbig = Circle(p1, 5)
    cout = Circle(Point(5, 5), 1)
    # one circle inside of another
    assert csmall.intersection(cbig) == []
    # separate circles
    assert csmall.intersection(cout) == []
    # coincident circles
    assert csmall.intersection(csmall) == csmall

    v = sqrt(2)
    t1 = Triangle(Point(0, v), Point(0, -v), Point(v, 0))
    points = intersection(t1, c1)
    assert len(points) == 4
    assert Point(0, 1) in points
    assert Point(0, -1) in points
    assert Point(v / 2, v / 2) in points
    assert Point(v / 2, -v / 2) in points

    e1 = Circle(Point(0, 0), 5)
    e2 = Ellipse(Point(0, 0), 5, 20)
    assert intersection(e1, e2) in \
        [[Point(5, 0), Point(-5, 0)], [Point(-5, 0), Point(5, 0)]]

    # FAILING ELLIPSE INTERSECTION GOES HERE

    # Combinations of above
    assert e3.is_tangent(e3.tangent_line(p1 + Point(y1, 0)))

    major = 3
    minor = 1
    e4 = Ellipse(p2, major, minor)
    assert e4.focus_distance == sqrt(abs(major**2 - minor**2))
    ecc = e4.focus_distance / major
    assert e4.eccentricity == ecc
    assert e4.periapsis == major * (1 - ecc)
    assert e4.apoapsis == major * (1 + ecc)
示例#26
0
def _Abs(a):
    return Abs(a, evaluate=False)
示例#27
0
def test_polygon():
    p1 = Polygon(Point(0, 0), Point(3, -1), Point(6, 0), Point(4, 5),
                 Point(2, 3), Point(0, 3))
    p2 = Polygon(Point(6, 0), Point(3, -1), Point(0, 0), Point(0, 3),
                 Point(2, 3), Point(4, 5))
    p3 = Polygon(Point(0, 0), Point(3, 0), Point(5, 2), Point(4, 4))
    p4 = Polygon(Point(0, 0), Point(4, 4), Point(5, 2), Point(3, 0))

    #
    # General polygon
    #
    assert p1 == p2
    assert len(p1) == Rational(6)
    assert len(p1.sides) == 6
    assert p1.perimeter == 5 + 2 * sqrt(10) + sqrt(29) + sqrt(8)
    assert p1.area == 22
    assert not p1.is_convex()
    assert p3.is_convex()
    assert p4.is_convex(
    )  # ensure convex for both CW and CCW point specification

    #
    # Regular polygon
    #
    p1 = RegularPolygon(Point(0, 0), 10, 5)
    p2 = RegularPolygon(Point(0, 0), 5, 5)

    assert p1 != p2
    assert p1.interior_angle == 3 * pi / 5
    assert p1.exterior_angle == 2 * pi / 5
    assert p2.apothem == 5 * cos(pi / 5)
    assert p2.circumcircle == Circle(Point(0, 0), 5)
    assert p2.incircle == Circle(Point(0, 0), p2.apothem)
    assert p1.is_convex()

    #
    # Angles
    #
    angles = p4.angles
    assert feq(angles[Point(0, 0)].evalf(), Real("0.7853981633974483"))
    assert feq(angles[Point(4, 4)].evalf(), Real("1.2490457723982544"))
    assert feq(angles[Point(5, 2)].evalf(), Real("1.8925468811915388"))
    assert feq(angles[Point(3, 0)].evalf(), Real("2.3561944901923449"))

    angles = p3.angles
    assert feq(angles[Point(0, 0)].evalf(), Real("0.7853981633974483"))
    assert feq(angles[Point(4, 4)].evalf(), Real("1.2490457723982544"))
    assert feq(angles[Point(5, 2)].evalf(), Real("1.8925468811915388"))
    assert feq(angles[Point(3, 0)].evalf(), Real("2.3561944901923449"))

    #
    # Triangle
    #
    p1 = Point(0, 0)
    p2 = Point(5, 0)
    p3 = Point(0, 5)
    t1 = Triangle(p1, p2, p3)
    t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4))))
    t3 = Triangle(p1, Point(x1, 0), Point(0, x1))
    s1 = t1.sides
    s2 = t2.sides
    s3 = t3.sides

    # Basic stuff
    assert t1.area == Rational(25, 2)
    assert t1.is_right()
    assert t2.is_right() == False
    assert t3.is_right()
    assert p1 in t1
    assert Point(5, 5) not in t2
    assert t1.is_convex()
    assert feq(t1.angles[p1].evalf(), pi.evalf() / 2)

    assert t1.is_equilateral() == False
    assert t2.is_equilateral()
    assert t3.is_equilateral() == False
    assert are_similar(t1, t2) == False
    assert are_similar(t1, t3)
    assert are_similar(t2, t3) == False

    # Bisectors
    bisectors = t1.bisectors
    assert bisectors[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
    ic = (250 - 125 * sqrt(2)) / 50
    assert t1.incenter == Point(ic, ic)

    # Inradius
    assert t1.inradius == 5 - 5 * 2**(S(1) / 2) / 2
    assert t2.inradius == 5 * 3**(S(1) / 2) / 6
    t3_inradius = (2 * x1**2 * Abs(x1) -
                   2**(S(1) / 2) * x1**2 * Abs(x1)) / (2 * x1**2)
    assert simplify((t3.inradius - t3_inradius)) == 0

    # Medians + Centroid
    m = t1.medians
    assert t1.centroid == Point(Rational(5, 3), Rational(5, 3))
    assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
    assert t3.medians[p1] == Segment(p1, Point(x1 / 2, x1 / 2))
    assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid]

    # Perpendicular
    altitudes = t1.altitudes
    assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
    assert altitudes[p2] == s1[0]
    assert altitudes[p3] == s1[2]

    # Ensure
    assert len(intersection(*bisectors.values())) == 1
    assert len(intersection(*altitudes.values())) == 1
    assert len(intersection(*m.values())) == 1

    # Distance
    p1 = Polygon(Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1))
    p2 = Polygon(Point(0,
                       Rational(5) / 4), Point(1,
                                               Rational(5) / 4),
                 Point(1,
                       Rational(9) / 4), Point(0,
                                               Rational(9) / 4))
    p3 = Polygon(Point(1, 2), Point(2, 2), Point(2, 1))
    p4 = Polygon(Point(1, 1), Point(Rational(6) / 5, 1),
                 Point(1,
                       Rational(6) / 5))
    p5 = Polygon(Point(half, 3**(half) / 2), Point(-half, 3**(half) / 2),
                 Point(-1, 0), Point(-half, -(3)**(half) / 2),
                 Point(half, -(3)**(half) / 2), Point(1, 0))
    p6 = Polygon(Point(2,
                       Rational(3) / 10), Point(Rational(17) / 10, 0),
                 Point(2, -Rational(3) / 10), Point(Rational(23) / 10, 0))
    pt1 = Point(half, half)
    pt2 = Point(1, 1)
    '''Polygon to Point'''
    assert p1.distance(pt1) == half
    assert p1.distance(pt2) == 0
    assert p2.distance(pt1) == Rational(3) / 4
    assert p3.distance(pt2) == sqrt(2) / 2
    '''Polygon to Polygon'''
    assert p1.distance(p2) == half / 2
    assert p1.distance(p3) == sqrt(2) / 2
    assert p3.distance(p4) == (sqrt(2) / 2 - sqrt(Rational(2) / 25) / 2)
    assert p5.distance(p6) == Rational(7) / 10
示例#28
0
def periodicity(f, symbol, check=False):
    """
    Tests the given function for periodicity in the given symbol.

    Parameters
    ==========

    f : Expr.
        The concerned function.
    symbol : Symbol
        The variable for which the period is to be determined.
    check : Boolean
        The flag to verify whether the value being returned is a period or not.

    Returns
    =======

    period
        The period of the function is returned.
        `None` is returned when the function is aperiodic or has a complex period.
        The value of `0` is returned as the period of a constant function.

    Raises
    ======

    NotImplementedError
        The value of the period computed cannot be verified.


    Notes
    =====

    Currently, we do not support functions with a complex period.
    The period of functions having complex periodic values such
    as `exp`, `sinh` is evaluated to `None`.

    The value returned might not be the "fundamental" period of the given
    function i.e. it may not be the smallest periodic value of the function.

    The verification of the period through the `check` flag is not reliable
    due to internal simplification of the given expression. Hence, it is set
    to `False` by default.

    Examples
    ========
    >>> from sympy import Symbol, sin, cos, tan, exp
    >>> from sympy.calculus.util import periodicity
    >>> x = Symbol('x')
    >>> f = sin(x) + sin(2*x) + sin(3*x)
    >>> periodicity(f, x)
    2*pi
    >>> periodicity(sin(x)*cos(x), x)
    pi
    >>> periodicity(exp(tan(2*x) - 1), x)
    pi/2
    >>> periodicity(sin(4*x)**cos(2*x), x)
    pi
    >>> periodicity(exp(x), x)

    """
    from sympy.core.function import diff
    from sympy.core.mod import Mod
    from sympy.core.relational import Relational
    from sympy.functions.elementary.complexes import Abs
    from sympy.functions.elementary.trigonometric import (
        TrigonometricFunction, sin, cos, csc, sec)
    from sympy.simplify.simplify import simplify
    from sympy.solvers.decompogen import decompogen
    from sympy.polys.polytools import degree, lcm_list

    def _check(orig_f, period):
        '''Return the checked period or raise an error.'''
        new_f = orig_f.subs(symbol, symbol + period)
        if new_f.equals(orig_f):
            return period
        else:
            raise NotImplementedError(filldedent('''
                The period of the given function cannot be verified.
                When `%s` was replaced with `%s + %s` in `%s`, the result
                was `%s` which was not recognized as being the same as
                the original function.
                So either the period was wrong or the two forms were
                not recognized as being equal.
                Set check=False to obtain the value.''' %
                (symbol, symbol, period, orig_f, new_f)))

    orig_f = f
    period = None

    if isinstance(f, Relational):
        f = f.lhs - f.rhs

    f = simplify(f)

    if symbol not in f.free_symbols:
        return S.Zero

    if isinstance(f, TrigonometricFunction):
        try:
            period = f.period(symbol)
        except NotImplementedError:
            pass

    if isinstance(f, Abs):
        arg = f.args[0]
        if isinstance(arg, (sec, csc, cos)):
            # all but tan and cot might have a
            # a period that is half as large
            # so recast as sin
            arg = sin(arg.args[0])
        period = periodicity(arg, symbol)
        if period is not None and isinstance(arg, sin):
            # the argument of Abs was a trigonometric other than
            # cot or tan; test to see if the half-period
            # is valid. Abs(arg) has behaviour equivalent to
            # orig_f, so use that for test:
            orig_f = Abs(arg)
            try:
                return _check(orig_f, period/2)
            except NotImplementedError as err:
                if check:
                    raise NotImplementedError(err)
            # else let new orig_f and period be
            # checked below

    if f.is_Pow:
        base, expo = f.args
        base_has_sym = base.has(symbol)
        expo_has_sym = expo.has(symbol)

        if base_has_sym and not expo_has_sym:
            period = periodicity(base, symbol)

        elif expo_has_sym and not base_has_sym:
            period = periodicity(expo, symbol)

        else:
            period = _periodicity(f.args, symbol)

    elif f.is_Mul:
        coeff, g = f.as_independent(symbol, as_Add=False)
        if isinstance(g, TrigonometricFunction) or coeff is not S.One:
            period = periodicity(g, symbol)

        else:
            period = _periodicity(g.args, symbol)

    elif f.is_Add:
        k, g = f.as_independent(symbol)
        if k is not S.Zero:
            return periodicity(g, symbol)

        period = _periodicity(g.args, symbol)

    elif isinstance(f, Mod):
        a, n = f.args

        if a == symbol:
            period = n
        elif isinstance(a, TrigonometricFunction):
            period = periodicity(a, symbol)
        #check if 'f' is linear in 'symbol'
        elif degree(a, symbol) == 1 and symbol not in n.free_symbols:
            period = Abs(n / a.diff(symbol))

    elif period is None:
        from sympy.solvers.decompogen import compogen
        g_s = decompogen(f, symbol)
        num_of_gs = len(g_s)
        if num_of_gs > 1:
            for index, g in enumerate(reversed(g_s)):
                start_index = num_of_gs - 1 - index
                g = compogen(g_s[start_index:], symbol)
                if g != orig_f and g != f: # Fix for issue 12620
                    period = periodicity(g, symbol)
                    if period is not None:
                        break

    if period is not None:
        if check:
            return _check(orig_f, period)
        return period

    return None
示例#29
0
def test_isolve_Sets():
    n = Dummy('n')
    assert isolve(Abs(x) <= n, x, relational=False) == \
        Piecewise((S.EmptySet, n < 0), (Interval(-n, n), True))
示例#30
0
 def _eval_Abs(self):
     scale_factor = Abs(self.scale_factor)
     if scale_factor == self.scale_factor:
         return self
     return None
     q = self.func(self.name, self.abbrev)
示例#31
0
def test_sign():
    assert sign(1.2) == 1
    assert sign(-1.2) == -1
    assert sign(3 * I) == I
    assert sign(-3 * I) == -I
    assert sign(0) == 0
    assert sign(nan) == nan
    assert sign(2 + 2 * I).doit() == sqrt(2) * (2 + 2 * I) / 4
    assert sign(2 + 3 * I).simplify() == sign(2 + 3 * I)
    assert sign(2 + 2 * I).simplify() == sign(1 + I)
    assert sign(im(sqrt(1 - sqrt(3)))) == 1
    assert sign(sqrt(1 - sqrt(3))) == I

    x = Symbol('x')
    assert sign(x).is_finite is True
    assert sign(x).is_complex is True
    assert sign(x).is_imaginary is None
    assert sign(x).is_integer is None
    assert sign(x).is_real is None
    assert sign(x).is_zero is None
    assert sign(x).doit() == sign(x)
    assert sign(1.2 * x) == sign(x)
    assert sign(2 * x) == sign(x)
    assert sign(I * x) == I * sign(x)
    assert sign(-2 * I * x) == -I * sign(x)
    assert sign(conjugate(x)) == conjugate(sign(x))

    p = Symbol('p', positive=True)
    n = Symbol('n', negative=True)
    m = Symbol('m', negative=True)
    assert sign(2 * p * x) == sign(x)
    assert sign(n * x) == -sign(x)
    assert sign(n * m * x) == sign(x)

    x = Symbol('x', imaginary=True)
    assert sign(x).is_imaginary is True
    assert sign(x).is_integer is False
    assert sign(x).is_real is False
    assert sign(x).is_zero is False
    assert sign(x).diff(x) == 2 * DiracDelta(-I * x)
    assert sign(x).doit() == x / Abs(x)
    assert conjugate(sign(x)) == -sign(x)

    x = Symbol('x', real=True)
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is None
    assert sign(x).diff(x) == 2 * DiracDelta(x)
    assert sign(x).doit() == sign(x)
    assert conjugate(sign(x)) == sign(x)

    x = Symbol('x', nonzero=True)
    assert sign(x).is_imaginary is None
    assert sign(x).is_integer is None
    assert sign(x).is_real is None
    assert sign(x).is_zero is False
    assert sign(x).doit() == x / Abs(x)
    assert sign(Abs(x)) == 1
    assert Abs(sign(x)) == 1

    x = Symbol('x', positive=True)
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is False
    assert sign(x).doit() == x / Abs(x)
    assert sign(Abs(x)) == 1
    assert Abs(sign(x)) == 1

    x = 0
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is True
    assert sign(x).doit() == 0
    assert sign(Abs(x)) == 0
    assert Abs(sign(x)) == 0

    nz = Symbol('nz', nonzero=True, integer=True)
    assert sign(nz).is_imaginary is False
    assert sign(nz).is_integer is True
    assert sign(nz).is_real is True
    assert sign(nz).is_zero is False
    assert sign(nz)**2 == 1
    assert (sign(nz)**3).args == (sign(nz), 3)

    assert sign(Symbol('x', nonnegative=True)).is_nonnegative
    assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None
    assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None
    assert sign(Symbol('x', nonpositive=True)).is_nonpositive
    assert sign(Symbol('x', real=True)).is_nonnegative is None
    assert sign(Symbol('x', real=True)).is_nonpositive is None
    assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None

    x, y = Symbol('x', real=True), Symbol('y')
    assert sign(x).rewrite(Piecewise) == \
        Piecewise((1, x > 0), (-1, x < 0), (0, True))
    assert sign(y).rewrite(Piecewise) == sign(y)
    assert sign(x).rewrite(Heaviside) == 2 * Heaviside(x) - 1
    assert sign(y).rewrite(Heaviside) == sign(y)

    # evaluate what can be evaluated
    assert sign(exp_polar(I * pi) * pi) is S.NegativeOne

    eq = -sqrt(10 + 6 * sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3 * sqrt(3))
    # if there is a fast way to know when and when you cannot prove an
    # expression like this is zero then the equality to zero is ok
    assert sign(eq).func is sign or sign(eq) == 0
    # but sometimes it's hard to do this so it's better not to load
    # abs down with tests that will be very slow
    q = 1 + sqrt(2) - 2 * sqrt(3) + 1331 * sqrt(6)
    p = expand(q**3)**Rational(1, 3)
    d = p - q
    assert sign(d).func is sign or sign(d) == 0
示例#32
0
def test_polygon():
    t = Triangle(Point(0, 0), Point(2, 0), Point(3, 3))
    assert Polygon(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 3)) == t
    assert Polygon(Point(1, 0), Point(2, 0), Point(3, 3), Point(0, 0)) == t
    assert Polygon(Point(2, 0), Point(3, 3), Point(0, 0), Point(1, 0)) == t

    p1 = Polygon(Point(0, 0), Point(3, -1), Point(6, 0), Point(4, 5),
                 Point(2, 3), Point(0, 3))
    p2 = Polygon(Point(6, 0), Point(3, -1), Point(0, 0), Point(0, 3),
                 Point(2, 3), Point(4, 5))
    p3 = Polygon(Point(0, 0), Point(3, 0), Point(5, 2), Point(4, 4))
    p4 = Polygon(Point(0, 0), Point(4, 4), Point(5, 2), Point(3, 0))

    #
    # General polygon
    #
    assert p1 == p2
    assert len(p1) == 6
    assert len(p1.sides) == 6
    assert p1.perimeter == 5 + 2 * sqrt(10) + sqrt(29) + sqrt(8)
    assert p1.area == 22
    assert not p1.is_convex()
    assert p3.is_convex()
    assert p4.is_convex(
    )  # ensure convex for both CW and CCW point specification

    #
    # Regular polygon
    #
    p1 = RegularPolygon(Point(0, 0), 10, 5)
    p2 = RegularPolygon(Point(0, 0), 5, 5)

    assert p1 != p2
    assert p1.interior_angle == 3 * pi / 5
    assert p1.exterior_angle == 2 * pi / 5
    assert p2.apothem == 5 * cos(pi / 5)
    assert p2.circumcircle == Circle(Point(0, 0), 5)
    assert p2.incircle == Circle(Point(0, 0), p2.apothem)
    assert p1.is_convex()
    assert p1.rotation == 0
    p1.spin(pi / 3)
    assert p1.rotation == pi / 3
    assert p1[0] == Point(5, 5 * sqrt(3))
    # while spin works in place (notice that rotation is 2pi/3 below)
    # rotate returns a new object
    p1_old = p1
    assert p1.rotate(pi / 3) == RegularPolygon(Point(0, 0), 10, 5, 2 * pi / 3)
    assert p1 == p1_old

    #
    # Angles
    #
    angles = p4.angles
    assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483"))
    assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544"))
    assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388"))
    assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449"))

    angles = p3.angles
    assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483"))
    assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544"))
    assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388"))
    assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449"))

    #
    # Triangle
    #
    p1 = Point(0, 0)
    p2 = Point(5, 0)
    p3 = Point(0, 5)
    t1 = Triangle(p1, p2, p3)
    t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4))))
    t3 = Triangle(p1, Point(x1, 0), Point(0, x1))
    s1 = t1.sides
    s2 = t2.sides
    s3 = t3.sides

    # Basic stuff
    assert Triangle(p1, p1, p1) == p1
    assert Triangle(p2, p2 * 2, p2 * 3) == Segment(p2, p2 * 3)
    assert t1.area == Rational(25, 2)
    assert t1.is_right()
    assert t2.is_right() == False
    assert t3.is_right()
    assert p1 in t1
    assert Point(5, 5) not in t2
    assert t1.is_convex()
    assert feq(t1.angles[p1].evalf(), pi.evalf() / 2)

    assert t1.is_equilateral() == False
    assert t2.is_equilateral()
    assert t3.is_equilateral() == False
    assert are_similar(t1, t2) == False
    assert are_similar(t1, t3)
    assert are_similar(t2, t3) == False

    # Bisectors
    bisectors = t1.bisectors()
    assert bisectors[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
    ic = (250 - 125 * sqrt(2)) / 50
    assert t1.incenter == Point(ic, ic)

    # Inradius
    assert t1.inradius == 5 - 5 * sqrt(2) / 2
    assert t2.inradius == 5 * sqrt(3) / 6
    assert t3.inradius == x1**2 / ((2 + sqrt(2)) * Abs(x1))

    # Medians + Centroid
    m = t1.medians
    assert t1.centroid == Point(Rational(5, 3), Rational(5, 3))
    assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
    assert t3.medians[p1] == Segment(p1, Point(x1 / 2, x1 / 2))
    assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid]

    # Perpendicular
    altitudes = t1.altitudes
    assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
    assert altitudes[p2] == s1[0]
    assert altitudes[p3] == s1[2]

    # Ensure
    assert len(intersection(*bisectors.values())) == 1
    assert len(intersection(*altitudes.values())) == 1
    assert len(intersection(*m.values())) == 1

    # Distance
    p1 = Polygon(Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1))
    p2 = Polygon(Point(0,
                       Rational(5) / 4), Point(1,
                                               Rational(5) / 4),
                 Point(1,
                       Rational(9) / 4), Point(0,
                                               Rational(9) / 4))
    p3 = Polygon(Point(1, 2), Point(2, 2), Point(2, 1))
    p4 = Polygon(Point(1, 1), Point(Rational(6) / 5, 1),
                 Point(1,
                       Rational(6) / 5))
    p5 = Polygon(Point(half, 3**(half) / 2), Point(-half, 3**(half) / 2),
                 Point(-1, 0), Point(-half, -(3)**(half) / 2),
                 Point(half, -(3)**(half) / 2), Point(1, 0))
    p6 = Polygon(Point(2,
                       Rational(3) / 10), Point(Rational(17) / 10, 0),
                 Point(2, -Rational(3) / 10), Point(Rational(23) / 10, 0))
    pt1 = Point(half, half)
    pt2 = Point(1, 1)
    '''Polygon to Point'''
    assert p1.distance(pt1) == half
    assert p1.distance(pt2) == 0
    assert p2.distance(pt1) == Rational(3) / 4
    assert p3.distance(pt2) == sqrt(2) / 2
    '''Polygon to Polygon'''
    import warnings
    # p1.distance(p2) emits a warning
    # First, test the warning
    warnings.filterwarnings(
        "error", "Polygons may intersect producing erroneous output")
    raises(UserWarning, "p1.distance(p2)")
    # now test the actual output
    warnings.filterwarnings(
        "ignore", "Polygons may intersect producing erroneous output")
    assert p1.distance(p2) == half / 2
    # Keep testing reasonably thread safe, so reset the warning
    warnings.filterwarnings(
        "default", "Polygons may intersect producing erroneous output")
    # Note, in Python 2.6+, this can be done more nicely using the
    # warnings.catch_warnings context manager.
    # See http://docs.python.org/library/warnings#testing-warnings.

    assert p1.distance(p3) == sqrt(2) / 2
    assert p3.distance(p4) == (sqrt(2) / 2 - sqrt(Rational(2) / 25) / 2)
    assert p5.distance(p6) == Rational(7) / 10
示例#33
0
def test_Abs():
    x, y = symbols('x,y')
    assert sign(sign(x)) == sign(x)
    assert sign(x * y).func is sign
    assert Abs(0) == 0
    assert Abs(1) == 1
    assert Abs(-1) == 1
    assert Abs(I) == 1
    assert Abs(-I) == 1
    assert Abs(nan) == nan
    assert Abs(I * pi) == pi
    assert Abs(-I * pi) == pi
    assert Abs(I * x) == Abs(x)
    assert Abs(-I * x) == Abs(x)
    assert Abs(-2 * x) == 2 * Abs(x)
    assert Abs(-2.0 * x) == 2.0 * Abs(x)
    assert Abs(2 * pi * x * y) == 2 * pi * Abs(x * y)
    assert Abs(conjugate(x)) == Abs(x)
    assert conjugate(Abs(x)) == Abs(x)

    a = Symbol('a', positive=True)
    assert Abs(2 * pi * x * a) == 2 * pi * a * Abs(x)
    assert Abs(2 * pi * I * x * a) == 2 * pi * a * Abs(x)

    x = Symbol('x', real=True)
    n = Symbol('n', integer=True)
    assert Abs((-1)**n) == 1
    assert x**(2 * n) == Abs(x)**(2 * n)
    assert Abs(x).diff(x) == sign(x)
    assert abs(x) == Abs(x)  # Python built-in
    assert Abs(x)**3 == x**2 * Abs(x)
    assert Abs(x)**4 == x**4
    assert (Abs(x)**(3 * n)).args == (Abs(x), 3 * n
                                      )  # leave symbolic odd unchanged
    assert (1 / Abs(x)).args == (Abs(x), -1)
    assert 1 / Abs(x)**3 == 1 / (x**2 * Abs(x))

    x = Symbol('x', imaginary=True)
    assert Abs(x).diff(x) == -sign(x)

    eq = -sqrt(10 + 6 * sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3 * sqrt(3))
    # if there is a fast way to know when you can and when you cannot prove an
    # expression like this is zero then the equality to zero is ok
    assert abs(eq).func is Abs or abs(eq) == 0
    # but sometimes it's hard to do this so it's better not to load
    # abs down with tests that will be very slow
    q = 1 + sqrt(2) - 2 * sqrt(3) + 1331 * sqrt(6)
    p = expand(q**3)**Rational(1, 3)
    d = p - q
    assert abs(d).func is Abs or abs(d) == 0