def test_rewrite():
    x, y = Symbol('x', real=True), Symbol('y')
    assert Heaviside(x).rewrite(Piecewise) == (
        Piecewise((0, x < 0), (Heaviside(0), Eq(x, 0)), (1, x > 0)))
    assert Heaviside(y).rewrite(Piecewise) == (
        Piecewise((0, y < 0), (Heaviside(0), Eq(y, 0)), (1, y > 0)))
    assert Heaviside(x, y).rewrite(Piecewise) == (
        Piecewise((0, x < 0), (y, Eq(x, 0)), (1, x > 0)))
    assert Heaviside(x, 0).rewrite(Piecewise) == (
        Piecewise((0, x <= 0), (1, x > 0)))
    assert Heaviside(x, 1).rewrite(Piecewise) == (
        Piecewise((0, x < 0), (1, x >= 0)))

    assert Heaviside(x).rewrite(sign) == (sign(x)+1)/2
    assert Heaviside(y).rewrite(sign) == Heaviside(y)
    assert Heaviside(x, S.Half).rewrite(sign) == (sign(x)+1)/2
    assert Heaviside(x, y).rewrite(sign) == Heaviside(x, y)

    assert DiracDelta(y).rewrite(Piecewise) == Piecewise((DiracDelta(0), Eq(y, 0)), (0, True))
    assert DiracDelta(y, 1).rewrite(Piecewise) == DiracDelta(y, 1)
    assert DiracDelta(x - 5).rewrite(Piecewise) == (
        Piecewise((DiracDelta(0), Eq(x - 5, 0)), (0, True)))

    assert (x*DiracDelta(x - 10)).rewrite(SingularityFunction) == x*SingularityFunction(x, 10, -1)
    assert 5*x*y*DiracDelta(y, 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, 0, -2)
    assert DiracDelta(0).rewrite(SingularityFunction) == SingularityFunction(0, 0, -1)
    assert DiracDelta(0, 1).rewrite(SingularityFunction) == SingularityFunction(0, 0, -2)

    assert Heaviside(x).rewrite(SingularityFunction) == SingularityFunction(x, 0, 0)
    assert 5*x*y*Heaviside(y + 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, -1, 0)
    assert ((x - 3)**3*Heaviside(x - 3)).rewrite(SingularityFunction) == (x - 3)**3*SingularityFunction(x, 3, 0)
    assert Heaviside(0).rewrite(SingularityFunction) == SingularityFunction(0, 0, 0)
Example #2
0
File: libm.py Project: zholos/qml
def test_trig():
    arg = FiniteSet(0, *(pi/x for x in (12, 6, 4, 3, 2, 1)))
    arg += FiniteSet(*sum(((pi-x, pi+x, 2*pi-x) for x in arg), ()))
    arg += FiniteSet(*(-x for x in arg))

    def emit(name, func):
        for x in sorted(arg):
            if func(x) != sp.zoo:
                test(name, x, sp.simplify(sp.sqrtdenest(func(x))))
        test(name, S.NaN, S.NaN)

    def aemit(aname, func, domain):
        for x, y in sorted((sp.simplify(sp.sqrtdenest(func(x))), x)
                           for x in arg & domain):
            test(aname, x, y)
        test(aname, S.NaN, S.NaN)

    emit("sin", sp.sin)
    emit("cos", sp.cos)
    emit("tan", sp.tan)
    aemit("asin", sp.sin, Interval(-pi/2, pi/2))
    aemit("acos", sp.cos, Interval(0, pi))
    aemit("atan", sp.tan, Interval(-pi/2, pi/2, True, True))

    for x in sorted(arg & Interval(-pi, pi, True, True)):
        a = sp.simplify(sp.sqrtdenest(sp.sin(x)))
        b = sp.simplify(sp.sqrtdenest(sp.cos(x)))
        f = sp.sqrt(3) if \
            sp.sqrt(3) == abs(sp.simplify(a/b).as_numer_denom()[0]) else 1
        if b:
            test("atan2", sp.simplify(a/abs(b))*f, sp.sign(b)*f, x)
        if a and a != b:
            test("atan2", sp.sign(a)*f, sp.simplify(b/abs(a))*f, x)
    test("atan2", S.NaN, 1, S.NaN)
    test("atan2", 1, S.NaN, S.NaN)
def sp_derive():

    import sympy as sp

    vars = 'G_s, s_n, s_p_n, w_n, dw_n, ds_n, G_s, G_w, c, phi'

    syms = sp.symbols(vars)

    for var, sym in zip(vars.split(','), syms):
        globals()[var.strip()] = sym

    s_n1 = s_n + ds_n
    w_n1 = w_n + dw_n

    tau_trial = G_s * (s_n1 - s_p_n)

    print 'diff', sp.diff(tau_trial, ds_n)

    print tau_trial

    sig_n1 = G_w * w_n1

    print sig_n1

    tau_fr = (c + sig_n1 * sp.tan(phi)) * sp.Heaviside(sig_n1 - c / sp.tan(phi))

    print tau_fr

    d_tau_fr = sp.diff(tau_fr, dw_n)

    print d_tau_fr

    f_trial = sp.abs(tau_trial) - tau_fr

    print f_trial

    d_gamma = f_trial / G_s

    print 'd_gamma'
    sp.pretty_print(d_gamma)

    print 'd_gamma_s'
    sp.pretty_print(sp.diff(d_gamma, ds_n))

    print 'tau_n1'
    tau_n1 = sp.simplify(tau_trial - d_gamma * G_s * sp.sign(tau_trial))
    sp.pretty_print(tau_n1)

    print 'dtau_n1_w'
    dtau_n1_w = sp.diff(tau_n1, dw_n)
    sp.pretty_print(dtau_n1_w)

    print 'dtau_n1_s'
    dtau_n1_s = sp.diff(d_gamma * sp.sign(tau_trial), ds_n)
    print dtau_n1_s

    s_p_n1 = s_p_n + d_gamma * sp.sign(tau_trial)

    print s_p_n1
Example #4
0
def test_fcode_sign():  #issue 12267
    x=symbols('x')
    y=symbols('y', integer=True)
    z=symbols('z', complex=True)
    assert fcode(sign(x), standard=95, source_format='free') == "merge(0d0, dsign(1d0, x), x == 0d0)"
    assert fcode(sign(y), standard=95, source_format='free') == "merge(0, isign(1, y), y == 0)"
    assert fcode(sign(z), standard=95, source_format='free') == "merge(cmplx(0d0, 0d0), z/abs(z), abs(z) == 0d0)"
    raises(NotImplementedError, lambda: fcode(sign(x)))
Example #5
0
def test_issue_3068X():
    eps = pi**-1500
    big = pi**1000
    one = cos(x)**2 + sin(x)**2
    e = big*one - big + eps
    assert sign(simplify(e)) == 1
    for xi in (111, 11, 1, S(1)/10):
        assert sign(e.subs(x, xi)) == 1
Example #6
0
def base_solution_linear(c, a, b, t=None):
    """
    Return the base solution for a linear diophantine equation with two
    variables. Called repeatedly by diop_linear().

    Usage
    =====

        base_solution_linear(c, a, b, t) -> a, b, c are Integers as in a*x + b*y = c
        and t is the parameter to be used in the solution.

    Details
    =======

        ``c`` is the constant term in a*x + b*y = c
        ``a`` is the integer coefficient of x in a*x + b*y = c
        ``b`` is the integer coefficient of y in a*x + b*y = c
        ``t`` is the parameter to be used in the solution


    Examples
    ========

    >>> from sympy.solvers.diophantine import base_solution_linear
    >>> from sympy.abc import t
    >>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5
    (-5, 5)
    >>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0
    (0, 0)
    >>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5
    (3*t - 5, -2*t + 5)
    >>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0
    (7*t, -5*t)
    """
    d = igcd(a, igcd(b, c))
    a = a // d
    b = b // d
    c = c // d

    if c == 0:
        if t != None:
            return (b*t , -a*t)
        else:
            return (S.Zero, S.Zero)
    else:
        x0, y0, d = extended_euclid(int(abs(a)), int(abs(b)))

        x0 = x0 * sign(a)
        y0 = y0 * sign(b)

        if divisible(c, d):
            if t != None:
                return (c*x0 + b*t, c*y0 - a*t)
            else:
                return (Integer(c*x0), Integer(c*y0))
        else:
            return (None, None)
Example #7
0
def test_basic1():
    assert limit(x, x, oo) == oo
    assert limit(x, x, -oo) == -oo
    assert limit(-x, x, oo) == -oo
    assert limit(x**2, x, -oo) == oo
    assert limit(-x**2, x, oo) == -oo
    assert limit(x*log(x), x, 0, dir="+") == 0
    assert limit(1/x, x, oo) == 0
    assert limit(exp(x), x, oo) == oo
    assert limit(-exp(x), x, oo) == -oo
    assert limit(exp(x)/x, x, oo) == oo
    assert limit(1/x - exp(-x), x, oo) == 0
    assert limit(x + 1/x, x, oo) == oo
    assert limit(x - x**2, x, oo) == -oo
    assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1
    assert limit((1 + x)**oo, x, 0) == oo
    assert limit((1 + x)**oo, x, 0, dir='-') == 0
    assert limit((1 + x + y)**oo, x, 0, dir='-') == (1 + y)**(oo)
    assert limit(y/x/log(x), x, 0) == -oo*sign(y)
    assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo
    assert limit(gamma(1/x + 3), x, oo) == 2
    assert limit(S.NaN, x, -oo) == S.NaN
    assert limit(Order(2)*x, x, S.NaN) == S.NaN
    assert limit(1/(x - 1), x, 1, dir="+") == oo
    assert limit(1/(x - 1), x, 1, dir="-") == -oo
    assert limit(1/(5 - x)**3, x, 5, dir="+") == -oo
    assert limit(1/(5 - x)**3, x, 5, dir="-") == oo
    assert limit(1/sin(x), x, pi, dir="+") == -oo
    assert limit(1/sin(x), x, pi, dir="-") == oo
    assert limit(1/cos(x), x, pi/2, dir="+") == -oo
    assert limit(1/cos(x), x, pi/2, dir="-") == oo
    assert limit(1/tan(x**3), x, (2*pi)**(S(1)/3), dir="+") == oo
    assert limit(1/tan(x**3), x, (2*pi)**(S(1)/3), dir="-") == -oo
    assert limit(1/cot(x)**3, x, (3*pi/2), dir="+") == -oo
    assert limit(1/cot(x)**3, x, (3*pi/2), dir="-") == oo

    # test bi-directional limits
    assert limit(sin(x)/x, x, 0, dir="+-") == 1
    assert limit(x**2, x, 0, dir="+-") == 0
    assert limit(1/x**2, x, 0, dir="+-") == oo

    # test failing bi-directional limits
    raises(ValueError, lambda: limit(1/x, x, 0, dir="+-"))
    # approaching 0
    # from dir="+"
    assert limit(1 + 1/x, x, 0) == oo
    # from dir='-'
    # Add
    assert limit(1 + 1/x, x, 0, dir='-') == -oo
    # Pow
    assert limit(x**(-2), x, 0, dir='-') == oo
    assert limit(x**(-3), x, 0, dir='-') == -oo
    assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I
    assert limit(x**2, x, 0, dir='-') == 0
    assert limit(sqrt(x), x, 0, dir='-') == 0
    assert limit(x**-pi, x, 0, dir='-') == oo*sign((-1)**(-pi))
    assert limit((1 + cos(x))**oo, x, 0) == oo
Example #8
0
def test_basic1():
    assert limit(x, x, oo) == oo
    assert limit(x, x, -oo) == -oo
    assert limit(-x, x, oo) == -oo
    assert limit(x**2, x, -oo) == oo
    assert limit(-x**2, x, oo) == -oo
    assert limit(x*log(x), x, 0, dir="+") == 0
    assert limit(1/x, x, oo) == 0
    assert limit(exp(x), x, oo) == oo
    assert limit(-exp(x), x, oo) == -oo
    assert limit(exp(x)/x, x, oo) == oo
    assert limit(1/x - exp(-x), x, oo) == 0
    assert limit(x + 1/x, x, oo) == oo
    assert limit(x - x**2, x, oo) == -oo
    assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1
    assert limit((1 + x)**oo, x, 0) == oo
    assert limit((1 + x)**oo, x, 0, dir='-') == 0
    assert limit((1 + x + y)**oo, x, 0, dir='-') == (1 + y)**(oo)
    assert limit(y/x/log(x), x, 0) == -oo*sign(y)
    assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo
    raises(NotImplementedError, lambda: limit(Sum(1/x, (x, 1, y)) -
           log(y), y, oo))
    raises(NotImplementedError, lambda: limit(Sum(1/x, (x, 1, y)) - 1/y, y, oo))
    assert limit(gamma(1/x + 3), x, oo) == 2
    assert limit(S.NaN, x, -oo) == S.NaN
    assert limit(Order(2)*x, x, S.NaN) == S.NaN
    assert limit(gamma(1/x + 3), x, oo) == 2
    assert limit(S.NaN, x, -oo) == S.NaN
    assert limit(Order(2)*x, x, S.NaN) == S.NaN
    assert limit(1/(x - 1), x, 1, dir="+") == oo
    assert limit(1/(x - 1), x, 1, dir="-") == -oo
    assert limit(1/(5 - x)**3, x, 5, dir="+") == -oo
    assert limit(1/(5 - x)**3, x, 5, dir="-") == oo
    assert limit(1/sin(x), x, pi, dir="+") == -oo
    assert limit(1/sin(x), x, pi, dir="-") == oo
    assert limit(1/cos(x), x, pi/2, dir="+") == -oo
    assert limit(1/cos(x), x, pi/2, dir="-") == oo
    assert limit(1/tan(x**3), x, (2*pi)**(S(1)/3), dir="+") == oo
    assert limit(1/tan(x**3), x, (2*pi)**(S(1)/3), dir="-") == -oo
    assert limit(1/cot(x)**3, x, (3*pi/2), dir="+") == -oo
    assert limit(1/cot(x)**3, x, (3*pi/2), dir="-") == oo

    # approaching 0
    # from dir="+"
    assert limit(1 + 1/x, x, 0) == oo
    # from dir='-'
    # Add
    assert limit(1 + 1/x, x, 0, dir='-') == -oo
    # Pow
    assert limit(x**(-2), x, 0, dir='-') == oo
    assert limit(x**(-3), x, 0, dir='-') == -oo
    assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I
    assert limit(x**2, x, 0, dir='-') == 0
    assert limit(sqrt(x), x, 0, dir='-') == 0
    assert limit((1 + cos(x))**oo, x, 0) == oo
Example #9
0
def test_issue_6167_6151():
    n = pi**1000
    i = int(n)
    assert sign(n - i) == 1
    assert abs(n - i) == n - i
    eps = pi**-1500
    big = pi**1000
    one = cos(x)**2 + sin(x)**2
    e = big*one - big + eps
    assert sign(simplify(e)) == 1
    for xi in (111, 11, 1, S(1)/10):
        assert sign(e.subs(x, xi)) == 1
Example #10
0
 def eval(cls, arg):
     if not arg.is_Atom:
         c, arg_ = factor_terms(arg).as_coeff_Mul()
         if arg_.is_Mul:
             arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else
                 sign(a) for a in arg_.args])
         arg_ = sign(c)*arg_
     else:
         arg_ = arg
     x, y = re(arg_), im(arg_)
     rv = atan2(y, x)
     if rv.is_number and not rv.atoms(AppliedUndef):
         return rv
     if arg_ != arg:
         return cls(arg_, evaluate=False)
Example #11
0
def _compute_tau(model, robo, j):
    """
    Compute the joint torque by subtracting the effect of friction.

    Args:
        model: An instance of DynModel
        robo: An instance of Robot
        j: joint number

    Returns:
        An instance of DynModel that contains all the new values.
    """
    tau_j = 0
    # local variables
    qdot_j = robo.qdots[j]
    gamma_j = robo.torques[j]
    f_cj = robo.dyns[j].frc
    f_vj = robo.dyns[j].frv
    # actual computation
    coriolis_friction_term = f_cj * sign(qdot_j)
    viscous_friction_term = f_vj * qdot_j
    tau_j = gamma_j - coriolis_friction_term - viscous_friction_term
    # store in model
    model.taus[j] = tau_j
    return model
Example #12
0
 def _updated_range(r, first):
     st = sign(r.step)*step
     if r.start.is_finite:
         rv = Range(first, r.stop, st)
     else:
         rv = Range(r.start, first + st, st)
     return rv
Example #13
0
def frictionforce(rbtdef, ifunc=None):
    '''Generate friction forces (Coulomb/viscouse model plus offset).'''

    if not ifunc:
        ifunc = identity

    fric = zeros(rbtdef.dof, 1)

    if rbtdef.frictionmodel is None or len(rbtdef.frictionmodel) == 0:
        pass
    else:
        askedterms = set(rbtdef.frictionmodel)
        if askedterms.issubset(_frictionterms):
            if 'viscous' in askedterms:
                for i in range(rbtdef.dof):
                    fric[i] += rbtdef.fv[i] * rbtdef.dq[i]
            if 'Coulomb' in askedterms:
                for i in range(rbtdef.dof):
                    fric[i] += rbtdef.fc[i] * sign(rbtdef.dq[i])
            if 'offset' in askedterms:
                for i in range(rbtdef.dof):
                    fric[i] += rbtdef.fo[i]
            fric[i] = ifunc(fric[i])
        else:
            raise Exception(
                'Friction model terms \'%s\' not understanded. Use None or a'
                ' combination of %s.' %
                (str(askedterms - _frictionterms), _frictionterms))

    return fric
Example #14
0
def frictionforce(rbtdef, ifunc=None):
    """Generate friction forces (Coulomb/viscouse model plus offset)."""

    if not ifunc:
        ifunc = identity

    fric = zeros((rbtdef.dof, 1))

    if rbtdef.frictionmodel is None or len(rbtdef.frictionmodel) == 0:
        pass
    else:
        askedterms = set(rbtdef.frictionmodel)
        if askedterms.issubset(_frictionterms):
            if "viscous" in askedterms:
                for i in range(rbtdef.dof):
                    fric[i] += rbtdef.fv[i] * rbtdef.dq[i]
            if "Coulomb" in askedterms:
                for i in range(rbtdef.dof):
                    fric[i] += rbtdef.fc[i] * sign(rbtdef.dq[i])
            if "offset" in askedterms:
                for i in range(rbtdef.dof):
                    fric[i] += rbtdef.fo[i]
            fric[i] = ifunc(fric[i])
        else:
            raise Exception(
                "Friction model terms '%s' not understanded. Use None or a"
                " combination of %s." % (str(askedterms - _frictionterms), _frictionterms)
            )

    return fric
Example #15
0
    def __new__(cls, lhs, rhs, rop=None, **assumptions):
        lhs = _sympify(lhs)
        rhs = _sympify(rhs)
        if cls is not Relational:
            rop_cls = cls
        else:
            try:
                rop_cls = Relational.ValidRelationOperator[rop]
            except KeyError:
                msg = "Invalid relational operator symbol: '%r'"
                raise ValueError(msg % repr(rop))
        if lhs.is_number and rhs.is_number and (rop_cls in (Equality, Unequality) or lhs.is_real and rhs.is_real):
            diff = lhs - rhs
            know = diff.equals(0, failing_expression=True)
            if know is True:  # exclude failing expression case
                Nlhs = S.Zero
            elif know is False:
                from sympy import sign

                Nlhs = sign(diff.n(1))
            else:
                Nlhs = None
                lhs = know
                rhs = S.Zero
            if Nlhs is not None:
                return rop_cls._eval_relation(Nlhs, S.Zero)

        obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions)
        return obj
Example #16
0
def _compute_joint_torque(model, robo, j):
    """
    Compute the joint torque for joint j.

    Args:
        model: An instance of DynModel
        robo: An instance of Robot
        j: joint number

    Returns:
        An instance of DynModel that contains all the new values.
    """
    # local variables
    qdot_j = robo.qdots[j]
    qddot_j = robo.qddots[j]
    j_a_j = robo.geos[j].axisa
    ia_j = robo.dyns[j].ia
    f_cj = robo.dyns[j].frc
    f_vj = robo.dyns[j].frv
    j_f_j = model.wrenchs[j].val
    # actual computation
    wrench_term = j_f_j.transpose() * j_a_j
    actuator_inertia_term = Matrix([ia_j * qddot_j])
    coriolis_friction_term = Matrix([f_cj * sign(qdot_j)])
    viscous_friction_term = Matrix([f_vj * qdot_j])
    gamma_j = wrench_term + actuator_inertia_term + \
        viscous_friction_term + coriolis_friction_term
    # store computed torque in model
    model.torques[j] = gamma_j[0, 0]
    return model
Example #17
0
 def eval(cls, t, tprime, d_i, d_j, l):
     if t.is_Number and tprime.is_Number and d_i.is_Number and d_j.is_Number and l.is_Number:
         diff_t = t - tprime
         l2 = l * l
         half_l_di = 0.5 * l * d_i
         h = h(t, tprime, d_i, d_j, l)
         arg_1 = half_l_di + tprime / l
         arg_2 = half_l_di - (t - tprime) / l
         ln_part_1 = ln_diff_erf(arg_1, arg_2)
         arg_1 = half_l_di
         arg_2 = half_l_di - t / l
         sign_val = sign(t / l)
         ln_part_2 = ln_diff_erf(half_l_di, half_l_di - t / l)
         sign_val = sign(t / l)
         base = tprime * sign_val * exp(half_l_di * half_l_di - (d_i * t + d_j * tprime) + ln_part_2) - h
         return base / (d_i + d_j)
Example #18
0
 def _eval_derivative(self, x):
     if self.args[0].is_real or self.args[0].is_imaginary:
         return Derivative(self.args[0], x, evaluate=True) \
             * sign(conjugate(self.args[0]))
     return (re(self.args[0]) * Derivative(re(self.args[0]), x,
         evaluate=True) + im(self.args[0]) * Derivative(im(self.args[0]),
             x, evaluate=True)) / Abs(self.args[0])
Example #19
0
    def eval(cls, t, tprime, d_i, d_j, l):
        if t.is_Number and tprime.is_Number and d_i.is_Number and d_j.is_Number and l.is_Number:

            diff_t = t - tprime
            l2 = l * l
            h = h(t, tprime, d_i, d_j, l)
            half_l_di = 0.5 * l * d_i
            arg_1 = half_l_di + tprime / l
            arg_2 = half_l_di - (t - tprime) / l
            ln_part_1 = ln_diff_erf(arg_1, arg_2)
            arg_1 = half_l_di
            arg_2 = half_l_di - t / l
            sign_val = sign(t / l)
            ln_part_2 = ln_diff_erf(half_l_di, half_l_di - t / l)

            base = (
                (0.5 * d_i * l2 * (d_i + d_j) - 1) * h
                + (
                    -diff_t * sign_val * exp(half_l_di * half_l_di - d_i * diff_t + ln_part_1)
                    + t * sign_val * exp(half_l_di * half_l_di - d_i * t - d_j * tprime + ln_part_2)
                )
                + l
                / sqrt(pi)
                * (
                    -exp(-diff_t * diff_t / l2)
                    + exp(-tprime * tprime / l2 - d_i * t)
                    + exp(-t * t / l2 - d_j * tprime)
                    - exp(-(d_i * t + d_j * tprime))
                )
            )
            return base / (d_i + d_j)
def test_rewrite():
    x, y = Symbol('x', real=True), Symbol('y')
    assert Heaviside(x).rewrite(Piecewise) == \
        Piecewise((1, x > 0), (S(1)/2, Eq(x, 0)), (0, True))
    assert Heaviside(y).rewrite(Piecewise) == Heaviside(y)

    assert Heaviside(x).rewrite(sign) == (sign(x)+1)/2
    assert Heaviside(y).rewrite(sign) == Heaviside(y)
Example #21
0
 def _eval_nseries(self, x, n, logx):
     direction = self.args[0].leadterm(x)[0]
     s = self.args[0]._eval_nseries(x, n=n, logx=logx)
     when = Eq(direction, 0)
     return Piecewise(
         ((s.subs(direction, 0)), when),
         (sign(direction)*s, True),
     )
Example #22
0
 def __build_energy_distribution_function(energy_distribution_function, energy_spread):
     conduction_band_energy, energy, trap_central_energy_level = sym.symbols('Ecb E Et')
     if energy_distribution_function in energy_distribution_functions['Single Level']:
         energy_distribution = sym.DiracDelta(energy - conduction_band_energy + trap_central_energy_level)
     elif energy_distribution_function in energy_distribution_functions['Gaussian Level']:
         energy_distribution = sym.exp(-((energy - conduction_band_energy + trap_central_energy_level) ** 2)
                                       / (2 * energy_spread ** 2))
         energy_distribution /= (sym.sqrt(sym.pi) * energy_spread)
         energy_distribution *= sym.sqrt(2) / 2
     elif energy_distribution_function in energy_distribution_functions['Rectangular Level']:
         energy_offset = conduction_band_energy - trap_central_energy_level
         energy_distribution = (sym.sign(energy - energy_offset + energy_spread / 2) + 1) / 2
         energy_distribution *= (sym.sign(energy_offset + energy_spread / 2 - energy) + 1) / 2
         energy_distribution /= energy_spread
     else:
         raise Exception('The distribution function supplied is not supported!')
     return energy_distribution
Example #23
0
def test_Abs():
    x, y = symbols('x,y')
    assert Abs(0) == 0
    assert Abs(1) == 1
    assert Abs(-1)== 1
    assert Abs(nan) == nan
    x = Symbol('x',real=True)
    n = Symbol('n',integer=True)
    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)**(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).diff(x) == sign(x)
    assert conjugate(Abs(x)) == Abs(x)
Example #24
0
def modf(x):
    """modf(x)

    Return the fractional and integer parts of x.  Both results carry the sign
    of x.
    """
    signx = sign(x)
    absx = Abs(x)
    return (signx * Mod(absx, 1), signx * floor(absx))
Example #25
0
def test_abs():
    x = Symbol("x")
    a = Symbol("a")
    assert abs(x).nseries(x, n=4) == x
    assert abs(-x).nseries(x, n=4) == x
    assert abs(x + 1).nseries(x, n=4) == x + 1
    assert abs(sin(x)).nseries(x, n=4) == x - Rational(1, 6) * x ** 3 + O(x ** 4)
    assert abs(sin(-x)).nseries(x, n=4) == x - Rational(1, 6) * x ** 3 + O(x ** 4)
    assert abs(x - a).nseries(x, 1) == Piecewise((x - 1, Eq(1 - a, 0)), ((x - a) * sign(1 - a), True))
Example #26
0
def test_abs():
    x, y = symbols('xy')
    assert abs(0) == 0
    assert abs(1) == 1
    assert abs(-1)== 1
    assert abs(x).diff(x) == sign(x)
    x = Symbol('x',real=True)
    n = Symbol('n',integer=True)
    assert x**(2*n) == abs(x)**(2*n)
Example #27
0
def test_as_sum_trapezoid():
    e = Integral((x + y)**2, (x, 0, 1))
    assert e.as_sum(1, method="trapezoid").expand() == y**2 + y + S(1)/2
    assert e.as_sum(2, method="trapezoid").expand() == y**2 + y + S(3)/8
    assert e.as_sum(3, method="trapezoid").expand() == y**2 + y + S(19)/54
    assert e.as_sum(4, method="trapezoid").expand() == y**2 + y + S(11)/32
    assert e.as_sum(n, method="trapezoid").expand() == \
        y**2 + y + S(1)/3 + 1/(6*n**2)
    assert Integral(sign(x), (x, 0, 1)).as_sum(1, 'trapezoid') == S(1)/2
Example #28
0
def test_sign_issue_3068():
    n = pi**1000
    i = int(n)
    assert (n - i).round() == 1  # doesn't hang
    assert sign(n - i) == 1
    # perhaps it's not possible to get the sign right when
    # only 1 digit is being requested for this situtation;
    # 2 digits works
    assert (n - x).n(1, subs={x: i}) > 0
    assert (n - x).n(2, subs={x: i}) > 0
Example #29
0
def test_Abs():
    x, y = symbols('x,y')
    assert Abs(0) == 0
    assert Abs(1) == 1
    assert Abs(-1)== 1
    x = Symbol('x',real=True)
    n = Symbol('n',integer=True)
    assert x**(2*n) == Abs(x)**(2*n)
    assert Abs(x).diff(x) == sign(x)
    assert abs(x) == Abs(x) # Python built-in
Example #30
0
 def process(self, p, conn, param, alpha):
     mu, Ex, Kp, Kvb, Kg1, Gco, Gcf = const = sp.symbols("mu,Ex,Kp,Kvb,Kg1,Gco,Gcf")
     Ugk, Uak = v = sp.symbols("Ugk,Uak", real=True) # "real" needed to get derivative of sign()
     t = Kp*(1/mu+Ugk/sp.sqrt(Kvb+Uak*Uak))
     E1 = Uak/Kp*sp.log(1+sp.exp(t))
     E1_ = Uak/Kp*t
     calc_Ia = sp.Piecewise(
         (0, Uak < 0),
         (0, t < -500),
         (-pow(E1_,Ex) / Kg1 * (1+sp.sign(E1_)), t > 500),
         (-pow(E1,Ex) / Kg1 * (1+sp.sign(E1)), True))
     calc_Ia = calc_Ia.subs(dict([(k,param[str(k)]) for k in const]))
     calc_Ig = sp.Piecewise((0, Ugk < Gco), (-Gcf*pow(Ugk-Gco, 1.5), True))
     calc_Ig = calc_Ig.subs(dict([(k,param[str(k)]) for k in const]))
     # def calc_Ia(v):
     #     Ugk = float(v[0])
     #     Uak = float(v[1])
     #     if Uak < 0:
     #         return 0
     #     t = Kp*(1/mu+Ugk/math.sqrt(Kvb+Uak*Uak))
     #     if t > 500:
     #         E1 = Uak/Kp*t
     #     elif t < -500:
     #         return 0
     #     else:
     #         E1 = Uak/Kp*math.log(1+math.exp(t))
     #     r = pow(E1,Ex) / Kg1 * 2*(E1 > 0.0)
     #     return -r
     # def calc_Ig(v):
     #     Ugk = float(v[0])
     #     if Ugk < Gco:
     #         return 0
     #     r = Gcf*pow(Ugk-Gco, 1.5)
     #     return -r
     idx1 = p.new_row("N", self, "Ig")
     p.add_2conn("Nl", idx1, (conn[0],conn[2]))
     p.add_2conn("Nr", idx1, (conn[0],conn[2]))
     p.set_function(idx1, calc_Ig, v, idx1)
     idx2 = p.new_row("N", self, "Ip")
     p.add_2conn("Nl", idx2, (conn[1],conn[2]))
     p.add_2conn("Nr", idx2, (conn[1],conn[2]))
     p.set_function(idx2, calc_Ia, v, idx1)
Example #31
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)

    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)
    assert Abs(y).rewrite(sign) == y/sign(y)

    i = Symbol('i', imaginary=True)
    assert abs(i).rewrite(Piecewise) == Piecewise((I*i, I*i >= 0), (-I*i, True))


    assert Abs(y).rewrite(conjugate) == sqrt(y*conjugate(y))
    assert Abs(i).rewrite(conjugate) == sqrt(-i**2) #  == -I*i

    y = Symbol('y', extended_real=True)
    assert  (Abs(exp(-I*x)-exp(-I*y))**2).rewrite(conjugate) == \
        -exp(I*x)*exp(-I*y) + 2 - exp(-I*x)*exp(I*y)
Example #32
0
    def __new__(cls, b, e, evaluate=True):
        from sympy.functions.elementary.exponential import exp_polar

        # don't optimize "if e==0; return 1" here; it's better to handle that
        # in the calling routine so this doesn't get called
        b = _sympify(b)
        e = _sympify(e)
        if evaluate:
            if e is S.Zero:
                return S.One
            elif e is S.One:
                return b
            elif S.NaN in (b, e):
                if b is S.One:  # already handled e == 0 above
                    return S.One
                return S.NaN
            else:
                # recognize base as E
                if not e.is_Atom and b is not S.Exp1 and b.func is not exp_polar:
                    from sympy import numer, denom, log, sign, im, factor_terms
                    c, ex = factor_terms(e, sign=False).as_coeff_Mul()
                    den = denom(ex)
                    if den.func is log and den.args[0] == b:
                        return S.Exp1**(c * numer(ex))
                    elif den.is_Add:
                        s = sign(im(b))
                        if s.is_Number and s and den == \
                                log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
                            return S.Exp1**(c * numer(ex))

                obj = b._eval_power(e)
                if obj is not None:
                    return obj
        obj = Expr.__new__(cls, b, e)
        obj.is_commutative = (b.is_commutative and e.is_commutative)
        return obj
Example #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 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)
Example #34
0
def test_sign():
    assert sign(1.2) == 1
    assert sign(-1.2) == -1
    assert sign(0) == 0
    assert sign(nan) == nan
    x = Symbol('x')
    assert sign(x).is_zero == False
    assert sign(2*x) == sign(x)
    assert sign(x).diff(x) == 0
    assert conjugate(sign(x)) == 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 = 0
    assert sign(x).is_zero == True
Example #35
0
global_equation_file = 'hall_of_fame.csv'
global_n_features = None
global_variable_names = []
global_extra_sympy_mappings = {}

sympy_mappings = {
    'div': lambda x, y: x / y,
    'mult': lambda x, y: x * y,
    'sqrtm': lambda x: sympy.sqrt(abs(x)),
    'square': lambda x: x**2,
    'cube': lambda x: x**3,
    'plus': lambda x, y: x + y,
    'sub': lambda x, y: x - y,
    'neg': lambda x: -x,
    'pow': lambda x, y: sympy.sign(x) * abs(x)**y,
    'cos': lambda x: sympy.cos(x),
    'sin': lambda x: sympy.sin(x),
    'tan': lambda x: sympy.tan(x),
    'cosh': lambda x: sympy.cosh(x),
    'sinh': lambda x: sympy.sinh(x),
    'tanh': lambda x: sympy.tanh(x),
    'exp': lambda x: sympy.exp(x),
    'acos': lambda x: sympy.acos(x),
    'asin': lambda x: sympy.asin(x),
    'atan': lambda x: sympy.atan(x),
    'acosh': lambda x: sympy.acosh(x),
    'asinh': lambda x: sympy.asinh(x),
    'atanh': lambda x: sympy.atanh(x),
    'abs': lambda x: abs(x),
    'mod': lambda x, y: sympy.Mod(x, y),
Example #36
0
def test_Abs():
    raises(TypeError, lambda: Abs(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(zoo) == oo
    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)
    assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)

    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)
    assert Abs(I**I) == exp(-pi / 2)
    assert Abs((4 + 5 * I)**(6 + 7 * I)) == 68921 * exp(-7 * atan(S(5) / 4))
    y = Symbol('y', real=True)
    assert Abs(I**y) == 1
    y = Symbol('y')
    assert Abs(I**y) == exp(-pi * im(y) / 2)

    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
    assert Abs(x).fdiff() == sign(x)
    raises(ArgumentIndexError, lambda: Abs(x).fdiff(2))
Example #37
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

    x = Symbol('x')
    assert sign(x).is_zero == 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_zero == 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_zero == 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_zero == 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_zero == False
    assert sign(x).doit() == x / Abs(x)
    assert sign(Abs(x)) == 1
    assert Abs(sign(x)) == 1

    x = 0
    assert sign(x).is_zero == 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)**2 == 1
    assert (sign(nz)**3).args == (sign(nz), 3)
Example #38
0
def test_issue_4099():
    a = Symbol('a')
    assert limit(a / x, x, 0) == oo * sign(a)
    assert limit(-a / x, x, 0) == -oo * sign(a)
    assert limit(-a * x, x, oo) == -oo * sign(a)
    assert limit(a * x, x, oo) == oo * sign(a)
Example #39
0
sp.series(sp.log(1-x))

# %%
%%markdown

'''
Number of fringes observed between 0 and theta due to a "thickness" thick layer of medium
of refractive index "index" $n=1$
'''

# %%

theta = sp.symbols('theta')
index, gamma = sp.symbols('n gamma', positive=True)

N_t = sp.sign(theta) / gamma * ( 1 - index - sp.cos(theta)
                                   + sp.sqrt(index**2 - sp.sin(theta)**2))

# %%

N = sp.symbols('N')

theta_t = sp.sign(N) * sp.acos(index**2 - 1 - (gamma * sp.Abs(N) + index - 1)**2)/(2*(gamma*sp.Abs(N)+index-1))

# %%

N_t

theta_t

# %%
Example #40
0
def test_issue_15893():
    f = Function('f', real=True)
    x = Symbol('x', real=True)
    eq = Derivative(Abs(f(x)), f(x))
    assert eq.doit() == sign(f(x))
Example #41
0
def falsa_posicao(f, erro=10**-6, intervalo=None, max=MAX, precisao=PREC):
    x = symbols('x')
    if type(f) == str:
        f = str_to_func(f, x)

    a = intervalo[0]
    b = intervalo[1]

    ea = abs(f(a)).evalf(precisao)
    if ea <= erro:
        return {
            'd': a,
            'it': 1,
            'ea': ea
        }

    ea = abs(f(b)).evalf(precisao)
    if ea <= erro:
        return {
            'd': b,
            'it': 1,
            'ea': ea
        }

    for i in range(1, max+1):
        ea = abs(b - a)
        if ea <= erro:
            return {
                'd': [a, b],
                'it': i,
                'ea': ea
            }

        f_a = f(a).evalf(precisao)
        f_b = f(b).evalf(precisao)
        x = ((a * f_b - b * f_a) / (f_b - f_a)).evalf(precisao)
        f_x = f(x).evalf(precisao)

        ea = abs(f_x)
        if ea <= erro:
            return {
                'd': x,
                'it': i,
                'ea': ea
            }

        if not f_x.is_comparable:
            return {
                'd': 'Não é possivel obter o sinal de um número imaginário em f(x).',
                'it': i,
                'ea': ea
            }
        if sign(f_x) > 0:
            a = x
        else:
            b = x


    return {
        'd': 'Limite de iterações atingido.',
        'it': max,
        'ea': ea
    }
Example #42
0
def test_basic1():
    assert limit(x, x, oo) is oo
    assert limit(x, x, -oo) is -oo
    assert limit(-x, x, oo) is -oo
    assert limit(x**2, x, -oo) is oo
    assert limit(-x**2, x, oo) is -oo
    assert limit(x * log(x), x, 0, dir="+") == 0
    assert limit(1 / x, x, oo) == 0
    assert limit(exp(x), x, oo) is oo
    assert limit(-exp(x), x, oo) is -oo
    assert limit(exp(x) / x, x, oo) is oo
    assert limit(1 / x - exp(-x), x, oo) == 0
    assert limit(x + 1 / x, x, oo) is oo
    assert limit(x - x**2, x, oo) is -oo
    assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1
    assert limit((1 + x)**oo, x, 0) == Limit((x + 1)**oo, x, 0)
    assert limit((1 + x)**oo, x, 0, dir='-') == Limit((x + 1)**oo,
                                                      x,
                                                      0,
                                                      dir='-')
    assert limit((1 + x + y)**oo, x, 0, dir='-') == Limit((x + y + 1)**oo,
                                                          x,
                                                          0,
                                                          dir='-')
    assert limit(y / x / log(x), x, 0) == -oo * sign(y)
    assert limit(cos(x + y) / x, x, 0) == sign(cos(y)) * oo
    assert limit(gamma(1 / x + 3), x, oo) == 2
    assert limit(S.NaN, x, -oo) is S.NaN
    assert limit(Order(2) * x, x, S.NaN) is S.NaN
    assert limit(1 / (x - 1), x, 1, dir="+") is oo
    assert limit(1 / (x - 1), x, 1, dir="-") is -oo
    assert limit(1 / (5 - x)**3, x, 5, dir="+") is -oo
    assert limit(1 / (5 - x)**3, x, 5, dir="-") is oo
    assert limit(1 / sin(x), x, pi, dir="+") is -oo
    assert limit(1 / sin(x), x, pi, dir="-") is oo
    assert limit(1 / cos(x), x, pi / 2, dir="+") is -oo
    assert limit(1 / cos(x), x, pi / 2, dir="-") is oo
    assert limit(1 / tan(x**3), x, (2 * pi)**Rational(1, 3), dir="+") is oo
    assert limit(1 / tan(x**3), x, (2 * pi)**Rational(1, 3), dir="-") is -oo
    assert limit(1 / cot(x)**3, x, (pi * Rational(3, 2)), dir="+") is -oo
    assert limit(1 / cot(x)**3, x, (pi * Rational(3, 2)), dir="-") is oo

    # test bi-directional limits
    assert limit(sin(x) / x, x, 0, dir="+-") == 1
    assert limit(x**2, x, 0, dir="+-") == 0
    assert limit(1 / x**2, x, 0, dir="+-") is oo

    # test failing bi-directional limits
    assert limit(1 / x, x, 0, dir="+-") is zoo
    # approaching 0
    # from dir="+"
    assert limit(1 + 1 / x, x, 0) is oo
    # from dir='-'
    # Add
    assert limit(1 + 1 / x, x, 0, dir='-') is -oo
    # Pow
    assert limit(x**(-2), x, 0, dir='-') is oo
    assert limit(x**(-3), x, 0, dir='-') is -oo
    assert limit(1 / sqrt(x), x, 0, dir='-') == (-oo) * I
    assert limit(x**2, x, 0, dir='-') == 0
    assert limit(sqrt(x), x, 0, dir='-') == 0
    assert limit(x**-pi, x, 0, dir='-') == oo * sign((-1)**(-pi))
    assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0)
Example #43
0
    def _regular_point_ellipse(self, a, b, c, d, e, f):
        D = 4 * a * c - b**2
        ok = D

        if not ok:
            raise ValueError("Rational Point on the conic does not exist")

        if a == 0 and c == 0:
            K = -1
            L = 4 * (d * e - b * f)
        elif c != 0:
            K = D
            L = 4 * c**2 * d**2 - 4 * b * c * d * e + 4 * a * c * e**2 + 4 * b**2 * c * f - 16 * a * c**2 * f
        else:
            K = D
            L = 4 * a**2 * e**2 - 4 * b * a * d * e + 4 * b**2 * a * f

        ok = L != 0 and not (K > 0 and L < 0)
        if not ok:
            raise ValueError("Rational Point on the conic does not exist")

        K = Rational(K).limit_denominator(10**12)
        L = Rational(L).limit_denominator(10**12)

        k1, k2 = K.p, K.q
        l1, l2 = L.p, L.q
        g = gcd(k2, l2)

        a1 = (l2 * k2) / g
        b1 = (k1 * l2) / g
        c1 = -(l1 * k2) / g
        a2 = sign(a1) * core(abs(a1), 2)
        r1 = sqrt(a1 / a2)
        b2 = sign(b1) * core(abs(b1), 2)
        r2 = sqrt(b1 / b2)
        c2 = sign(c1) * core(abs(c1), 2)
        r3 = sqrt(c1 / c2)

        g = gcd(gcd(a2, b2), c2)
        a2 = a2 / g
        b2 = b2 / g
        c2 = c2 / g

        g1 = gcd(a2, b2)
        a2 = a2 / g1
        b2 = b2 / g1
        c2 = c2 * g1

        g2 = gcd(a2, c2)
        a2 = a2 / g2
        b2 = b2 * g2
        c2 = c2 / g2

        g3 = gcd(b2, c2)
        a2 = a2 * g3
        b2 = b2 / g3
        c2 = c2 / g3

        x, y, z = symbols("x y z")
        eq = a2 * x**2 + b2 * y**2 + c2 * z**2

        solutions = diophantine(eq)

        if len(solutions) == 0:
            raise ValueError("Rational Point on the conic does not exist")

        flag = False
        for sol in solutions:
            syms = Tuple(*sol).free_symbols
            rep = {s: 3 for s in syms}
            sol_z = sol[2]

            if sol_z == 0:
                flag = True
                continue

            if not (isinstance(sol_z, Integer) or isinstance(sol_z, int)):
                syms_z = sol_z.free_symbols

                if len(syms_z) == 1:
                    p = next(iter(syms_z))
                    p_values = Complement(
                        S.Integers, solveset(Eq(sol_z, 0), p, S.Integers))
                    rep[p] = next(iter(p_values))

                if len(syms_z) == 2:
                    p, q = list(ordered(syms_z))

                    for i in S.Integers:
                        subs_sol_z = sol_z.subs(p, i)
                        q_values = Complement(
                            S.Integers,
                            solveset(Eq(subs_sol_z, 0), q, S.Integers))

                        if not q_values.is_empty:
                            rep[p] = i
                            rep[q] = next(iter(q_values))
                            break

                if len(syms) != 0:
                    x, y, z = tuple(s.subs(rep) for s in sol)
                else:
                    x, y, z = sol
                flag = False
                break

        if flag:
            raise ValueError("Rational Point on the conic does not exist")

        x = (x * g3) / r1
        y = (y * g2) / r2
        z = (z * g1) / r3
        x = x / z
        y = y / z

        if a == 0 and c == 0:
            x_reg = (x + y - 2 * e) / (2 * b)
            y_reg = (x - y - 2 * d) / (2 * b)
        elif c != 0:
            x_reg = (x - 2 * d * c + b * e) / K
            y_reg = (y - b * x_reg - e) / (2 * c)
        else:
            y_reg = (x - 2 * e * a + b * d) / K
            x_reg = (y - b * y_reg - d) / (2 * a)

        return x_reg, y_reg
Example #44
0
    def _calc_dyn(self):
        print("Calculating Lagrangian...")
        # Calculate kinetic energy and potential energy
        p_e = 0
        k_e = 0
        self.k_e3 = 0

        for num in self.rbt_def.link_nums[1:]:
            k_e_n = 0
            if self.rbt_def.use_inertia[num]:
                print("Calculating the link kinetic energy of {}/{}".format(
                    num, self.rbt_def.link_nums[-1]))
                p_e += -self.rbt_def.m[num] * self.geom.p_c[num].dot(self._g)

                k_e_n = self.rbt_def.m[num] * self.geom.v_cw[num].dot(self.geom.v_cw[num])/2 +\
                       (self.geom.w_b[num].transpose() * self.rbt_def.I_by_Llm[num] * self.geom.w_b[num])[0, 0]/2

                # k_e_n = sympy.simplify(k_e_n) # this is replaced by the following code to reduce time cost
                k_e_n = sympy.factor(
                    sympy.expand(k_e_n) -
                    sympy.expand(k_e_n * self.rbt_def.m[num]).subs(
                        self.rbt_def.m[num], 0) / self.rbt_def.m[num])

            k_e += k_e_n

        # Lagrangian
        L = k_e - p_e

        tau = []

        print("Calculating joint torques...")
        for q, dq in zip(self.rbt_def.coordinates, self.rbt_def.d_coordinates):
            print("tau of {}".format(q))
            dk_ddq = sympy.diff(k_e, dq)
            dk_ddq_t = dk_ddq.subs(self.rbt_def.subs_q2qt +
                                   self.rbt_def.subs_dq2dqt)
            dk_ddq_dtt = sympy.diff(dk_ddq_t, sympy.Symbol('t'))

            dk_ddq_dt = dk_ddq_dtt.subs(self.rbt_def.subs_ddqt2ddq +
                                        self.rbt_def.subs_dqt2dq +
                                        self.rbt_def.subs_qt2q)

            dL_dq = sympy.diff(L, q)

            tau.append(sympy.expand(dk_ddq_dt - dL_dq))

        print("Adding frictions and springs...")
        tau = copy.deepcopy(tau)

        for i in range(self.rbt_def.frame_num):
            dq = self.rbt_def.dq_for_frame[i]

            if self.rbt_def.use_friction[i]:
                tau_f = sympy.sign(dq) * self.rbt_def.Fc[
                    i] + dq * self.rbt_def.Fv[i] + self.rbt_def.Fo[i]
                for a in range(len(self.rbt_def.d_coordinates)):
                    dq_da = sympy.diff(dq, self.rbt_def.d_coordinates[a])
                    tau[a] += dq_da * tau_f

        for k in range(len(self.rbt_def.K)):
            tau_k = self.rbt_def.springs[k] * self.rbt_def.K[k]
            index = self.rbt_def.coordinates.index(
                list(self.rbt_def.springs[k].free_symbols)[0])
            tau[index] += -tau_k

        print("Add motor inertia...")

        for i in range(self.rbt_def.frame_num):
            if self.rbt_def.use_Ia[i]:
                tau_Ia = self.rbt_def.ddq_for_frame[i] * self.rbt_def.Ia[i]
                tau_index = self.rbt_def.dd_coordinates.index(
                    self.rbt_def.ddq_for_frame[i].free_symbols.pop())
                tau[tau_index] += tau_Ia

        # for tendon_coupling in self.rbt_def.tendon_couplings:
        #     src_frame, dst_frame, k = tendon_coupling
        #     dq_src = self.rbt_def.dq_for_frame[src_frame]
        #     dq_dst = self.rbt_def.dq_for_frame[dst_frame]
        #     src_index = self.rbt_def.d_coordinates.index(dq_src)
        #
        #     for a in range(len(self.rbt_def.d_coordinates)):
        #         dq_da = sympy.diff(dq_dst, self.rbt_def.d_coordinates[a])
        #         tau_c[a] += dq_da * k * tau_csf[src_index]

        self.tau = tau
Example #45
0
 def _eval_conjugate(self):
     return sign(conjugate(self.args[0]))
Example #46
0
 def _eval_rewrite_as_sign(self, arg):
     from sympy import sign
     return arg / sign(arg)
Example #47
0
def test_issue_5740():
    assert limit(log(x) * z - log(2 * x) * y, x, 0) == oo * sign(y - z)
Example #48
0
def copysign(x, y):
    """copysign(x, y)

    Return x with the sign of y.
    """
    return Abs(x) * sign(y)
Example #49
0
import sympy.physics.mechanics as _me
import sympy as _sm
import math as m
import numpy as _np

x, y = _me.dynamicsymbols('x y')
x_d, y_d = _me.dynamicsymbols('x_ y_', 1)
e = _sm.cos(x)+_sm.sin(x)+_sm.tan(x)+_sm.cosh(x)+_sm.sinh(x)+_sm.tanh(x)+_sm.acos(x)+_sm.asin(x)+_sm.atan(x)+_sm.log(x)+_sm.exp(x)+_sm.sqrt(x)+_sm.factorial(x)+_sm.ceiling(x)+_sm.floor(x)+_sm.sign(x)
e = (x)**2+_sm.log(x, 10)
a = _sm.Abs(-1*1)+int(1.5)+round(1.9)
e1 = 2*x+3*y
e2 = x+y
am = _sm.Matrix([e1.expand().coeff(x), e1.expand().coeff(y), e2.expand().coeff(x), e2.expand().coeff(y)]).reshape(2, 2)
b = (e1).expand().coeff(x)
c = (e2).expand().coeff(y)
d1 = (e1).collect(x).coeff(x,0)
d2 = (e1).collect(x).coeff(x,1)
fm = _sm.Matrix([i.collect(x)for i in _sm.Matrix([e1,e2]).reshape(1, 2)]).reshape((_sm.Matrix([e1,e2]).reshape(1, 2)).shape[0], (_sm.Matrix([e1,e2]).reshape(1, 2)).shape[1])
f = (e1).collect(y)
g = (e1).subs({x:2*x})
gm = _sm.Matrix([i.subs({x:3}) for i in _sm.Matrix([e1,e2]).reshape(2, 1)]).reshape((_sm.Matrix([e1,e2]).reshape(2, 1)).shape[0], (_sm.Matrix([e1,e2]).reshape(2, 1)).shape[1])
frame_a = _me.ReferenceFrame('a')
frame_b = _me.ReferenceFrame('b')
theta = _me.dynamicsymbols('theta')
frame_b.orient(frame_a, 'Axis', [theta, frame_a.z])
v1 = 2*frame_a.x-3*frame_a.y+frame_a.z
v2 = frame_b.x+frame_b.y+frame_b.z
a = _me.dot(v1, v2)
bm = _sm.Matrix([_me.dot(v1, v2),_me.dot(v1, 2*v2)]).reshape(2, 1)
c = _me.cross(v1, v2)
d = 2*v1.magnitude()+3*v1.magnitude()
Example #50
0
def test_sign():
    x = Symbol("x")
    e1 = sympy.sign(sympy.Symbol("x"))
    e2 = sign(x)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1
Example #51
0
def test_log_sign():
    assert sign(log(2)) == 1
Example #52
0
def test_nsimplify():
    x = Symbol("x")
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1 + x) == 1 + x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5)) / 2
    assert nsimplify((1 + sqrt(5)) / 4, [GoldenRatio]) == GoldenRatio / 2
    assert nsimplify(2 / GoldenRatio, [GoldenRatio]) == 2 * GoldenRatio - 2
    assert nsimplify(exp(5*pi*I/3, evaluate=False)) == \
        sympify('1/2 - sqrt(3)*I/2')
    assert nsimplify(sin(3*pi/5, evaluate=False)) == \
        sympify('sqrt(sqrt(5)/8 + 5/8)')
    assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \
        sqrt(pi) + sqrt(pi)/2*I
    assert nsimplify(2 + exp(2 * atan('1/4') * I)) == sympify('49/17 + 8*I/17')
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0**(1 / 3.), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == \
        2**Rational(1, 3)
    assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x
    assert nsimplify(1 / .3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == \
        sympify('109861228866811/100000000000000')
    assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi * log(2) / 8
    assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == \
        -pi/4 - log(2) + S(7)/4
    assert nsimplify(x / 7.0) == x / 7
    assert nsimplify(pi / 1e2) == pi / 100
    assert nsimplify(pi / 1e2, rational=False) == pi / 100.0
    assert nsimplify(pi / 1e-7) == 10000000 * pi
    assert not nsimplify(
        factor(-3.0 * z**2 * (z**2)**(-2.5) + 3 * (z**2)**(-1.5))).atoms(Float)
    e = x**0.0
    assert e.is_Pow and nsimplify(x**0.0) == 1
    assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3)
    assert nsimplify(3.333333, tolerance=0.01,
                     rational=True) == Rational(10, 3)
    assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3)
    assert nsimplify(3.666666, tolerance=0.01,
                     rational=True) == Rational(11, 3)
    assert nsimplify(33, tolerance=10, rational=True) == Rational(33)
    assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30)
    assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40)
    assert nsimplify(-203.1) == -S(2031) / 10
    assert nsimplify(.2, tolerance=0) == S.One / 5
    assert nsimplify(-.2, tolerance=0) == -S.One / 5
    assert nsimplify(.2222, tolerance=0) == S(1111) / 5000
    assert nsimplify(-.2222, tolerance=0) == -S(1111) / 5000
    # issue 7211, PR 4112
    assert nsimplify(S(2e-8)) == S(1) / 50000000
    # issue 7322 direct test
    assert nsimplify(1e-42, rational=True) != 0
    # issue 10336
    inf = Float('inf')
    infs = (-oo, oo, inf, -inf)
    for i in infs:
        ans = sign(i) * oo
        assert nsimplify(i) == ans
        assert nsimplify(i + x) == x + ans
Example #53
0
def intersection_sets(a, b):  # noqa:F811
    from sympy.solvers.diophantine.diophantine import diop_linear
    from sympy.core.numbers import ilcm
    from sympy import sign

    # non-overlap quick exits
    if not b:
        return S.EmptySet
    if not a:
        return S.EmptySet
    if b.sup < a.inf:
        return S.EmptySet
    if b.inf > a.sup:
        return S.EmptySet

    # work with finite end at the start
    r1 = a
    if r1.start.is_infinite:
        r1 = r1.reversed
    r2 = b
    if r2.start.is_infinite:
        r2 = r2.reversed

    # If both ends are infinite then it means that one Range is just the set
    # of all integers (the step must be 1).
    if r1.start.is_infinite:
        return b
    if r2.start.is_infinite:
        return a

    # this equation represents the values of the Range;
    # it's a linear equation
    eq = lambda r, i: r.start + i * r.step

    # we want to know when the two equations might
    # have integer solutions so we use the diophantine
    # solver
    va, vb = diop_linear(eq(r1, Dummy('a')) - eq(r2, Dummy('b')))

    # check for no solution
    no_solution = va is None and vb is None
    if no_solution:
        return S.EmptySet

    # there is a solution
    # -------------------

    # find the coincident point, c
    a0 = va.as_coeff_Add()[0]
    c = eq(r1, a0)

    # find the first point, if possible, in each range
    # since c may not be that point
    def _first_finite_point(r1, c):
        if c == r1.start:
            return c
        # st is the signed step we need to take to
        # get from c to r1.start
        st = sign(r1.start - c) * step
        # use Range to calculate the first point:
        # we want to get as close as possible to
        # r1.start; the Range will not be null since
        # it will at least contain c
        s1 = Range(c, r1.start + st, st)[-1]
        if s1 == r1.start:
            pass
        else:
            # if we didn't hit r1.start then, if the
            # sign of st didn't match the sign of r1.step
            # we are off by one and s1 is not in r1
            if sign(r1.step) != sign(st):
                s1 -= st
        if s1 not in r1:
            return
        return s1

    # calculate the step size of the new Range
    step = abs(ilcm(r1.step, r2.step))
    s1 = _first_finite_point(r1, c)
    if s1 is None:
        return S.EmptySet
    s2 = _first_finite_point(r2, c)
    if s2 is None:
        return S.EmptySet

    # replace the corresponding start or stop in
    # the original Ranges with these points; the
    # result must have at least one point since
    # we know that s1 and s2 are in the Ranges
    def _updated_range(r, first):
        st = sign(r.step) * step
        if r.start.is_finite:
            rv = Range(first, r.stop, st)
        else:
            rv = Range(r.start, first + st, st)
        return rv

    r1 = _updated_range(a, s1)
    r2 = _updated_range(b, s2)

    # work with them both in the increasing direction
    if sign(r1.step) < 0:
        r1 = r1.reversed
    if sign(r2.step) < 0:
        r2 = r2.reversed

    # return clipped Range with positive step; it
    # can't be empty at this point
    start = max(r1.start, r2.start)
    stop = min(r1.stop, r2.stop)
    return Range(start, stop, step)
def test_issue_1113():
    assert not integrate(sign(x), x).has(Integral)
Example #55
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 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 = 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
Example #56
0
def test_issue_9449():
    assert limit((Abs(x + y) - Abs(x - y))/(2*x), x, 0) == sign(y)
Example #57
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)
Example #58
0
def test_issue_18118():
    assert limit(sign(sin(x)), x, 0, "-") == -1
    assert limit(sign(sin(x)), x, 0, "+") == 1
Example #59
0
def test_sign():
    x = Symbol('x', real = True)
    assert refine(sign(x), Q.positive(x)) == 1
    assert refine(sign(x), Q.negative(x)) == -1
    assert refine(sign(x), Q.zero(x)) == 0
    assert refine(sign(x), True) == sign(x)
    assert refine(sign(Abs(x)), Q.nonzero(x)) == 1

    x = Symbol('x', imaginary=True)
    assert refine(sign(x), Q.positive(im(x))) == S.ImaginaryUnit
    assert refine(sign(x), Q.negative(im(x))) == -S.ImaginaryUnit
    assert refine(sign(x), True) == sign(x)

    x = Symbol('x', complex=True)
    assert refine(sign(x), Q.zero(x)) == 0
Example #60
0
File: mul.py Project: pernici/sympy
    def _eval_subs(self, old, new):

        from sympy import sign
        from sympy.simplify.simplify import powdenest

        if self == old:
            return new

        def fallback():
            """Return this value when partial subs has failed."""

            return self.__class__(*[s._eval_subs(old, new) for s in self.args])

        def breakup(eq):
            """break up powers assuming (not checking) that eq is a Mul:
                   b**(Rational*e) -> b**e, Rational
                commutatives come back as a dictionary {b**e: Rational}
                noncommutatives come back as a list [(b**e, Rational)]
            """

            (c, nc) = (dict(), list())
            for (i, a) in enumerate(
                    Mul.make_args(eq)
                    or [eq]):  # remove or [eq] after 2114 accepted
                a = powdenest(a)
                (b, e) = a.as_base_exp()
                if not e is S.One:
                    (co, _) = e.as_coeff_mul()
                    b = Pow(b, e / co)
                    e = co
                if a.is_commutative:
                    if b in c:  # handle I and -1 like things where b, e for I is -1, 1/2
                        c[b] += e
                    else:
                        c[b] = e
                else:
                    nc.append([b, e])
            return (c, nc)

        def rejoin(b, co):
            """
            Put rational back with exponent; in general this is not ok, but
            since we took it from the exponent for analysis, it's ok to put
            it back.
            """

            (b, e) = b.as_base_exp()
            return Pow(b, e * co)

        def ndiv(a, b):
            """if b divides a in an extractive way (like 1/4 divides 1/2
            but not vice versa, and 2/5 does not divide 1/3) then return
            the integer number of times it divides, else return 0.
            """

            if not b.q % a.q or not a.q % b.q:
                return int(a / b)
            return 0

        if not old.is_Mul:
            return fallback()

        # handle the leading coefficient and use it to decide if anything
        # should even be started; we always know where to find the Rational
        # so it's a quick test

        coeff = S.One
        co_self = self.args[0]
        co_old = old.args[0]
        if co_old.is_Rational and co_self.is_Rational:
            co_xmul = co_self.extract_multiplicatively(co_old)
        elif co_old.is_Rational:
            co_xmul = None
        else:
            co_xmul = True

        if not co_xmul:
            return fallback()

        (c, nc) = breakup(self)
        (old_c, old_nc) = breakup(old)

        # update the coefficients if we had an extraction

        if getattr(co_xmul, 'is_Rational', False):
            c.pop(co_self)
            c[co_xmul] = S.One
            old_c.pop(co_old)

        # do quick tests to see if we can't succeed

        ok = True
        if (
                # more non-commutative terms
                len(old_nc) > len(nc)):
            ok = False
        elif (
                # more commutative terms
                len(old_c) > len(c)):
            ok = False
        elif (
                # unmatched non-commutative bases
                set(_[0] for _ in old_nc).difference(set(_[0] for _ in nc))):
            ok = False
        elif (
                # unmatched commutative terms
                set(old_c).difference(set(c))):
            ok = False
        elif (
                # differences in sign
                any(sign(c[b]) != sign(old_c[b]) for b in old_c)):
            ok = False
        if not ok:
            return fallback()

        if not old_c:
            cdid = None
        else:
            rat = []
            for (b, old_e) in old_c.items():
                c_e = c[b]
                rat.append(ndiv(c_e, old_e))
                if not rat[-1]:
                    return fallback()
            cdid = min(rat)

        if not old_nc:
            ncdid = None
            for i in range(len(nc)):
                nc[i] = rejoin(*nc[i])
        else:
            ncdid = 0  # number of nc replacements we did
            take = len(old_nc)  # how much to look at each time
            limit = cdid or S.Infinity  # max number that we can take
            failed = []  # failed terms will need subs if other terms pass
            i = 0
            while limit and i + take <= len(nc):
                hit = False

                # the bases must be equivalent in succession, and
                # the powers must be extractively compatible on the
                # first and last factor but equal inbetween.

                rat = []
                for j in range(take):
                    if nc[i + j][0] != old_nc[j][0]:
                        break
                    elif j == 0:
                        rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
                    elif j == take - 1:
                        rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
                    elif nc[i + j][1] != old_nc[j][1]:
                        break
                    else:
                        rat.append(1)
                    j += 1
                else:
                    ndo = min(rat)
                    if ndo:
                        if take == 1:
                            if cdid:
                                ndo = min(cdid, ndo)
                            nc[i] = Pow(new, ndo) * rejoin(
                                nc[i][0], nc[i][1] - ndo * old_nc[0][1])
                        else:
                            ndo = 1

                            # the left residual

                            l = rejoin(nc[i][0], nc[i][1] - ndo * old_nc[0][1])

                            # eliminate all middle terms

                            mid = new

                            # the right residual (which may be the same as the middle if take == 2)

                            ir = i + take - 1
                            r = (nc[ir][0], nc[ir][1] - ndo * old_nc[-1][1])
                            if r[1]:
                                if i + take < len(nc):
                                    nc[i:i + take] = [l * mid, r]
                                else:
                                    r = rejoin(*r)
                                    nc[i:i + take] = [l * mid * r]
                            else:

                                # there was nothing left on the right

                                nc[i:i + take] = [l * mid]

                        limit -= ndo
                        ncdid += ndo
                        hit = True
                if not hit:

                    # do the subs on this failing factor

                    failed.append(i)
                i += 1
            else:

                if not ncdid:
                    return fallback()

                # although we didn't fail, certain nc terms may have
                # failed so we rebuild them after attempting a partial
                # subs on them

                failed.extend(range(i, len(nc)))
                for i in failed:
                    nc[i] = rejoin(*nc[i]).subs(old, new)

        # rebuild the expression

        if cdid is None:
            do = ncdid
        elif ncdid is None:
            do = cdid
        else:
            do = min(ncdid, cdid)

        margs = []
        for b in c:
            if b in old_c:

                # calculate the new exponent

                e = c[b] - old_c[b] * do
                margs.append(rejoin(b, e))
            else:
                margs.append(rejoin(b.subs(old, new), c[b]))
        if cdid and not ncdid:

            # in case we are replacing commutative with non-commutative,
            # we want the new term to come at the front just like the
            # rest of this routine

            margs = [Pow(new, cdid)] + margs
        return Mul(*margs) * Mul(*nc)