Exemple #1
0
def find_period_sqrt(x, ITS_MAX=20):
    #x = S(sqrt(x))
    x = np.sqrt(x)

    seq = array([], dtype=float64)
    for its in arange(ITS_MAX):
        # subtract the integer part
        y = x - floor(x)

        # put that into an array
        seq = hstack(( seq, floor(x).n() ))

        # take the inverse
        x = 1/y

    # boom, we have the sequence
    seq = seq[1:]
    l = len(seq)

    # find out how periodic it is
    for i in arange(0,10):
        # repeat some sequence
        tiled_array = tile(seq[:i-1], 10*l//i)
        # make it the right len
        tiled_array = tiled_array[:l]
        # see if they're equal
        if array_equal(tiled_array, seq):
            length = len(seq[:i-1])
            #print length
            #break
            return length
    #print -1
    return -1
    def _eval_expand_func(self, **hints):
        from sympy import exp, I, floor, Add, Poly, Dummy, exp_polar, unpolarify
        z, s, a = self.args
        if z == 1:
            return zeta(s, a)
        if s.is_Integer and s <= 0:
            t = Dummy('t')
            p = Poly((t + a)**(-s), t)
            start = 1/(1 - t)
            res = S(0)
            for c in reversed(p.all_coeffs()):
                res += c*start
                start = t*start.diff(t)
            return res.subs(t, z)

        if a.is_Rational:
            # See section 18 of
            #   Kelly B. Roach.  Hypergeometric Function Representations.
            #   In: Proceedings of the 1997 International Symposium on Symbolic and
            #   Algebraic Computation, pages 205-211, New York, 1997. ACM.
            # TODO should something be polarified here?
            add = S(0)
            mul = S(1)
            # First reduce a to the interaval (0, 1]
            if a > 1:
                n = floor(a)
                if n == a:
                    n -= 1
                a -= n
                mul = z**(-n)
                add = Add(*[-z**(k - n)/(a + k)**s for k in xrange(n)])
            elif a <= 0:
                n = floor(-a) + 1
                a += n
                mul = z**n
                add = Add(*[z**(n - 1 - k)/(a - k - 1)**s for k in xrange(n)])

            m, n = S([a.p, a.q])
            zet = exp_polar(2*pi*I/n)
            root = z**(1/n)
            return add + mul*n**(s - 1)*Add(
                *[polylog(s, zet**k*root)._eval_expand_func(**hints)
                  / (unpolarify(zet)**k*root)**m for k in xrange(n)])

        # TODO use minpoly instead of ad-hoc methods when issue 2789 is fixed
        if z.func is exp and (z.args[0]/(pi*I)).is_Rational or z in [-1, I, -I]:
            # TODO reference?
            if z == -1:
                p, q = S([1, 2])
            elif z == I:
                p, q = S([1, 4])
            elif z == -I:
                p, q = S([-1, 4])
            else:
                arg = z.args[0]/(2*pi*I)
                p, q = S([arg.p, arg.q])
            return Add(*[exp(2*pi*I*k*p/q)/q**s*zeta(s, (k + a)/q)
                         for k in xrange(q)])

        return lerchphi(z, s, a)
Exemple #3
0
def round_afz(val, ndigits=0):
    u"""Round using round-away-from-zero strategy for halfway cases.

    Python 3+ implements round-half-even, and Python 2.7 has a random behaviour
    from end user point of view (in fact, result depends on internal
    representation in floating point arithmetic).
    """
    ceil = math.ceil
    floor = math.floor
    val = float(val)
    if isnan(val) or isinf(val):
        return val
    s = repr(val).rstrip('0')
    if 'e' in s:
        # XXX: implement round-away-from-zero in this case too.
        return round(val, ndigits)
    sep = s.find('.')
    pos = sep + ndigits
    if ndigits <= 0:
        pos -= 1
    # Skip dot if needed to reach next digit.
    next_pos = (pos + 1 if pos + 1 != sep else pos + 2)
    if next_pos < 0 or next_pos == 0 and s[next_pos] == '-':
        return 0.
    if len(s) <= next_pos:
        # No need to round (no digit after).
        return val
    power = 10**ndigits
    if s[next_pos] in '01234':
        return (floor(val*power)/power if val > 0 else ceil(val*power)/power)
    else:
        return (ceil(val*power)/power if val > 0 else floor(val*power)/power)
def test_frac():
    assert isinstance(frac(x), frac)
    assert frac(oo) == AccumBounds(0, 1)
    assert frac(-oo) == AccumBounds(0, 1)

    assert frac(n) == 0
    assert frac(nan) == nan
    assert frac(Rational(4, 3)) == Rational(1, 3)
    assert frac(-Rational(4, 3)) == Rational(2, 3)

    r = Symbol('r', real=True)
    assert frac(I*r) == I*frac(r)
    assert frac(1 + I*r) == I*frac(r)
    assert frac(0.5 + I*r) == 0.5 + I*frac(r)
    assert frac(n + I*r) == I*frac(r)
    assert frac(n + I*k) == 0
    assert frac(x + I*x) == frac(x + I*x)
    assert frac(x + I*n) == frac(x)

    assert frac(x).rewrite(floor) == x - floor(x)
    assert frac(x).rewrite(ceiling) == x + ceiling(-x)
    assert frac(y).rewrite(floor).subs(y, pi) == frac(pi)
    assert frac(y).rewrite(floor).subs(y, -E) == frac(-E)
    assert frac(y).rewrite(ceiling).subs(y, -pi) == frac(-pi)
    assert frac(y).rewrite(ceiling).subs(y, E) == frac(E)

    assert Eq(frac(y), y - floor(y))
    assert Eq(frac(y), y + ceiling(-y))
Exemple #5
0
def rationalize(x, maxcoeff=10000):
    """
    Helps identifying a rational number from a float (or mpmath.mpf) value by
    using a continued fraction. The algorithm stops as soon as a large partial
    quotient is detected (greater than 10000 by default).

    Examples
    ========

    >>> from sympy.concrete.guess import rationalize
    >>> from mpmath import cos, pi
    >>> rationalize(cos(pi/3))
    1/2

    >>> from mpmath import mpf
    >>> rationalize(mpf("0.333333333333333"))
    1/3

    While the function is rather intended to help 'identifying' rational
    values, it may be used in some cases for approximating real numbers.
    (Though other functions may be more relevant in that case.)

    >>> rationalize(pi, maxcoeff = 250)
    355/113

    See also
    ========
    Several other methods can approximate a real number as a rational, like:

      * fractions.Fraction.from_decimal
      * fractions.Fraction.from_float
      * mpmath.identify
      * mpmath.pslq by using the following syntax: mpmath.pslq([x, 1])
      * mpmath.findpoly by using the following syntax: mpmath.findpoly(x, 1)
      * sympy.simplify.nsimplify (which is a more general function)

    The main difference between the current function and all these variants is
    that control focuses on magnitude of partial quotients here rather than on
    global precision of the approximation. If the real is "known to be" a
    rational number, the current function should be able to detect it correctly
    with the default settings even when denominator is great (unless its
    expansion contains unusually big partial quotients) which may occur
    when studying sequences of increasing numbers. If the user cares more
    on getting simple fractions, other methods may be more convenient.

    """
    p0, p1 = 0, 1
    q0, q1 = 1, 0
    a = floor(x)
    while a < maxcoeff or q1 == 0:
        p = a * p1 + p0
        q = a * q1 + q0
        p0, p1 = p1, p
        q0, q1 = q1, q
        if x == a:
            break
        x = 1 / (x - a)
        a = floor(x)
    return sympify(p) / q
Exemple #6
0
def test_dir():
    assert abs(x).series(x, 0, dir="+") == x
    assert abs(x).series(x, 0, dir="-") == -x
    assert floor(x + 2).series(x, 0, dir='+') == 2
    assert floor(x + 2).series(x, 0, dir='-') == 1
    assert floor(x + 2.2).series(x, 0, dir='-') == 2
    assert ceiling(x + 2.2).series(x, 0, dir='-') == 3
    assert sin(x + y).series(x, 0, dir='-') == sin(x + y).series(x, 0, dir='+')
Exemple #7
0
def rightshift(a, b):
    if issig('rr', a, b):
        return Real(int(sym.floor(a)) >> int(sym.floor(b)))

    if issig('qr', a, b):
        b = sym.floor(b)
        return a[-b:] + a[:-b]

    raise BadTypeCombinationError('rightshift', a, b)
Exemple #8
0
def leftshift(a, b):
    if issig('rr', a, b):
        return Real(int(sym.floor(a)) << int(sym.floor(b)))

    if issig('qr', a, b):
        b = sym.floor(b)
        return a[b:] + a[:b]

    raise BadTypeCombinationError('leftshift', a, b)
def test_dir():
    x = Symbol('x')
    y = Symbol('y')
    assert abs(x).series(x, 0, dir="+") == x
    assert abs(x).series(x, 0, dir="-") == -x
    assert floor(x+2).series(x,0,dir='+') == 2
    assert floor(x+2).series(x,0,dir='-') == 1
    assert floor(x+2.2).series(x,0,dir='-') == 2
    assert sin(x+y).series(x,0,dir='-') == sin(x+y).series(x,0,dir='+')
Exemple #10
0
def test_issue_8444_nonworkingtests():
    x = symbols('x', real=True)
    assert (x <= oo) == (x >= -oo) == True

    x = symbols('x')
    assert x >= floor(x)
    assert (x < floor(x)) == False
    assert x <= ceiling(x)
    assert (x > ceiling(x)) == False
Exemple #11
0
def test_issue_8444_workingtests():
    x = symbols('x')
    assert Gt(x, floor(x)) == Gt(x, floor(x), evaluate=False)
    assert Ge(x, floor(x)) == Ge(x, floor(x), evaluate=False)
    assert Lt(x, ceiling(x)) == Lt(x, ceiling(x), evaluate=False)
    assert Le(x, ceiling(x)) == Le(x, ceiling(x), evaluate=False)
    i = symbols('i', integer=True)
    assert (i > floor(i)) == False
    assert (i < ceiling(i)) == False
Exemple #12
0
def length(P, Q, D):
    """
    Returns the length of aperiodic part + length of periodic part of
    continued fraction representation of (P + sqrt(D))/Q. It is important
    to remember that this does NOT return the length of the periodic
    part but the addition of the legths of the two parts as mentioned above.

    Usage
    =====

        length(P, Q, D) -> P, Q and D are integers corresponding to the
        continued fraction (P + sqrt(D))/Q.

    Details
    =======

        ``P`` corresponds to the P in the continued fraction, (P + sqrt(D))/ Q
        ``D`` corresponds to the D in the continued fraction, (P + sqrt(D))/ Q
        ``Q`` corresponds to the Q in the continued fraction, (P + sqrt(D))/ Q

    Examples
    ========

    >>> from sympy.solvers.diophantine import length
    >>> length(-2 , 4, 5) # (-2 + sqrt(5))/4
    3
    >>> length(-5, 4, 17) # (-5 + sqrt(17))/4
    4
    """
    x = P + sqrt(D)
    y = Q

    x = sympify(x)
    v, res = [], []
    q = x/y

    if q < 0:
        v.append(q)
        res.append(floor(q))
        q = q - floor(q)
        num, den = rad_rationalize(1, q)
        q = num / den

    while 1:
        v.append(q)
        a = int(q)
        res.append(a)

        if q == a:
            return len(res)

        num, den = rad_rationalize(1,(q - a))
        q = num / den

        if q in v:
            return len(res)
def test_series():
    x, y = symbols('x,y')
    assert floor(x).nseries(x, y, 100) == floor(y)
    assert ceiling(x).nseries(x, y, 100) == ceiling(y)
    assert floor(x).nseries(x, pi, 100) == 3
    assert ceiling(x).nseries(x, pi, 100) == 4
    assert floor(x).nseries(x, 0, 100) == 0
    assert ceiling(x).nseries(x, 0, 100) == 1
    assert floor(-x).nseries(x, 0, 100) == -1
    assert ceiling(-x).nseries(x, 0, 100) == 0
Exemple #14
0
def test_dir():
    x = Symbol("x")
    y = Symbol("y")
    assert abs(x).series(x, 0, dir="+") == x
    assert abs(x).series(x, 0, dir="-") == -x
    assert floor(x + 2).series(x, 0, dir="+") == 2
    assert floor(x + 2).series(x, 0, dir="-") == 1
    assert floor(x + 2.2).series(x, 0, dir="-") == 2
    assert ceiling(x + 2.2).series(x, 0, dir="-") == 3
    assert sin(x + y).series(x, 0, dir="-") == sin(x + y).series(x, 0, dir="+")
def test_upretty_floor():
    assert upretty(floor(x)) == u'⌊x⌋'

    u = upretty( floor(1 / (y - floor(x))) )
    s = \
u"""\
⎢   1   ⎥
⎢───────⎥
⎣y - ⌊x⌋⎦\
"""
    assert u == s
Exemple #16
0
def power(a, b):
    if issig('rr', a, b):
        return sym.Pow(a, b)

    if issig('sr', a, b):
        return [p + q for p, q in itertools.product(a, repeat=sym.floor(b))]

    if issig('qr', a, b):
        return [list(tup) for tup in itertools.product(a, repeat=sym.floor(b))]

    raise BadTypeCombinationError('power', a, b)
Exemple #17
0
def test_issue_8853():
    p = Symbol('x', even=True, positive=True)
    assert floor(-p - S.Half).is_even == False
    assert floor(-p + S.Half).is_even == True
    assert ceiling(p - S.Half).is_even == True
    assert ceiling(p + S.Half).is_even == False

    assert get_integer_part(S.Half, -1, {}, True) == (0, 0)
    assert get_integer_part(S.Half, 1, {}, True) == (1, 0)
    assert get_integer_part(-S.Half, -1, {}, True) == (-1, 0)
    assert get_integer_part(-S.Half, 1, {}, True) == (0, 0)
Exemple #18
0
def test_evalf_integer_parts():
    a = floor(log(8)/log(2) - exp(-1000), evaluate=False)
    b = floor(log(8)/log(2), evaluate=False)
    raises(PrecisionExhausted, "a.evalf()")
    assert a.evalf(chop=True) == 3
    assert a.evalf(maxprec=500) == 2
    raises(PrecisionExhausted, "b.evalf()")
    raises(PrecisionExhausted, "b.evalf(maxprec=500)")
    assert b.evalf(chop=True) == 3
    assert int(floor(factorial(50)/E,evaluate=False).evalf()) == \
        11188719610782480504630258070757734324011354208865721592720336800L
    assert int(ceiling(factorial(50)/E,evaluate=False).evalf()) == \
        11188719610782480504630258070757734324011354208865721592720336801L
    assert int(floor((GoldenRatio**999 / sqrt(5) + Rational(1,2))).evalf(1000)) == fibonacci(999)
    assert int(floor((GoldenRatio**1000 / sqrt(5) + Rational(1,2))).evalf(1000)) == fibonacci(1000)
Exemple #19
0
def test_bng_rounding():
    """ Test Ceiling and Floor match BNG implementation of rounding """
    x_sym = sympy.symbols('x')
    for x in (-1.5, -1, -0.5, 0, 0.5, 1.0, 1.5):
        for expr in (sympy.ceiling(x_sym), sympy.floor(x_sym)):
            assert expr.subs({'x': x}) == eval(
                _bng_print(expr), {}, {'rint': _rint, 'x': x})
Exemple #20
0
def test_latex_functions():
    assert latex(exp(x)) == "$e^{x}$"
    assert latex(exp(1) + exp(2)) == "$e + e^{2}$"

    f = Function("f")
    assert latex(f(x)) == "$\\operatorname{f}\\left(x\\right)$"

    beta = Function("beta")

    assert latex(beta(x)) == r"$\operatorname{beta}\left(x\right)$"
    assert latex(sin(x)) == r"$\operatorname{sin}\left(x\right)$"
    assert latex(sin(x), fold_func_brackets=True) == r"$\operatorname{sin}x$"
    assert latex(sin(2 * x ** 2), fold_func_brackets=True) == r"$\operatorname{sin}2 x^{2}$"
    assert latex(sin(x ** 2), fold_func_brackets=True) == r"$\operatorname{sin}x^{2}$"

    assert latex(asin(x) ** 2) == r"$\operatorname{asin}^{2}\left(x\right)$"
    assert latex(asin(x) ** 2, inv_trig_style="full") == r"$\operatorname{arcsin}^{2}\left(x\right)$"
    assert latex(asin(x) ** 2, inv_trig_style="power") == r"$\operatorname{sin}^{-1}\left(x\right)^{2}$"
    assert latex(asin(x ** 2), inv_trig_style="power", fold_func_brackets=True) == r"$\operatorname{sin}^{-1}x^{2}$"

    assert latex(factorial(k)) == r"$k!$"
    assert latex(factorial(-k)) == r"$\left(- k\right)!$"

    assert latex(floor(x)) == r"$\lfloor{x}\rfloor$"
    assert latex(ceiling(x)) == r"$\lceil{x}\rceil$"
    assert latex(abs(x)) == r"$\lvert{x}\rvert$"
    assert latex(re(x)) == r"$\Re{x}$"
    assert latex(im(x)) == r"$\Im{x}$"
    assert latex(conjugate(x)) == r"$\overline{x}$"
    assert latex(gamma(x)) == r"$\operatorname{\Gamma}\left(x\right)$"
    assert latex(Order(x)) == r"$\operatorname{\mathcal{O}}\left(x\right)$"
Exemple #21
0
def test_evalf_integer_parts():
    a = floor(log(8)/log(2) - exp(-1000), evaluate=False)
    b = floor(log(8)/log(2), evaluate=False)
    raises(PrecisionExhausted, "a.evalf()")
    assert a.evalf(chop=True) == 3
    assert a.evalf(maxn=500) == 2
    assert b.evalf() == 3
    # equals, as a fallback, can still fail but it might succeed as here
    assert ceiling(10*(sin(1)**2 + cos(1)**2)) == 10

    assert int(floor(factorial(50)/E,evaluate=False).evalf()) == \
        11188719610782480504630258070757734324011354208865721592720336800L
    assert int(ceiling(factorial(50)/E,evaluate=False).evalf()) == \
        11188719610782480504630258070757734324011354208865721592720336801L
    assert int(floor((GoldenRatio**999 / sqrt(5) + Rational(1,2))).evalf(1000)) == fibonacci(999)
    assert int(floor((GoldenRatio**1000 / sqrt(5) + Rational(1,2))).evalf(1000)) == fibonacci(1000)
Exemple #22
0
def test_uniformsum():
    n = Symbol("n", integer=True)
    _k = Symbol("k")

    X = UniformSum('x', n)
    assert density(X)(x) == (Sum((-1)**_k*(-_k + x)**(n - 1)
                        *binomial(n, _k), (_k, 0, floor(x)))/factorial(n - 1))
Exemple #23
0
def test_latex_functions():
    assert latex(exp(x)) == "$e^{x}$"
    assert latex(exp(1)+exp(2)) == "$e + e^{2}$"

    f = Function('f')
    assert latex(f(x)) == '$\\operatorname{f}\\left(x\\right)$'

    beta = Function('beta')

    assert latex(beta(x)) == r"$\operatorname{beta}\left(x\right)$"
    assert latex(sin(x)) == r"$\operatorname{sin}\left(x\right)$"
    assert latex(sin(x), fold_func_brackets=True) == r"$\operatorname{sin}x$"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
    r"$\operatorname{sin}2 x^{2}$"

    assert latex(factorial(k)) == r"$k!$"
    assert latex(factorial(-k)) == r"$\left(- k\right)!$"

    assert latex(floor(x)) == r"$\lfloor{x}\rfloor$"
    assert latex(ceiling(x)) == r"$\lceil{x}\rceil$"
    assert latex(abs(x)) == r"$\lvert{x}\rvert$"
    assert latex(re(x)) == r"$\Re{x}$"
    assert latex(im(x)) == r"$\Im{x}$"
    assert latex(conjugate(x)) == r"$\overline{x}$"
    assert latex(gamma(x)) == r"$\operatorname{\Gamma}\left(x\right)$"
    assert latex(Order(x)) == r"$\operatorname{\mathcal{O}}\left(x\right)$"
def test_ansi_math1_codegen():
    # not included: log10
    from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, \
        sin, sinh, sqrt, tan, tanh, N
    x = symbols('x')
    name_expr = [
        ("test_fabs", abs(x)),
        ("test_acos", acos(x)),
        ("test_asin", asin(x)),
        ("test_atan", atan(x)),
        ("test_ceil", ceiling(x)),
        ("test_cos", cos(x)),
        ("test_cosh", cosh(x)),
        ("test_floor", floor(x)),
        ("test_log", log(x)),
        ("test_ln", ln(x)),
        ("test_sin", sin(x)),
        ("test_sinh", sinh(x)),
        ("test_sqrt", sqrt(x)),
        ("test_tan", tan(x)),
        ("test_tanh", tanh(x)),
    ]
    numerical_tests = []
    for name, expr in name_expr:
        for xval in 0.2, 0.5, 0.8:
            expected = N(expr.subs(x, xval))
            numerical_tests.append((name, (xval,), expected, 1e-14))
    run_cc_test("ansi_math1", name_expr, numerical_tests)
Exemple #25
0
def test_intrinsic_math1_codegen():
    # not included: log10
    from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, \
        sin, sinh, sqrt, tan, tanh, N
    x = symbols('x')
    name_expr = [
        ("test_fabs", abs(x)),
        ("test_acos", acos(x)),
        ("test_asin", asin(x)),
        ("test_atan", atan(x)),
        ("test_cos", cos(x)),
        ("test_cosh", cosh(x)),
        ("test_log", log(x)),
        ("test_ln", ln(x)),
        ("test_sin", sin(x)),
        ("test_sinh", sinh(x)),
        ("test_sqrt", sqrt(x)),
        ("test_tan", tan(x)),
        ("test_tanh", tanh(x)),
    ]
    numerical_tests = []
    for name, expr in name_expr:
        for xval in 0.2, 0.5, 0.8:
            expected = N(expr.subs(x, xval))
            numerical_tests.append((name, (xval,), expected, 1e-14))
    for lang, commands in valid_lang_commands:
        if lang == "C":
            name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))]
        else:
            name_expr_C = []
        run_test("intrinsic_math1", name_expr + name_expr_C, numerical_tests, lang, commands)
Exemple #26
0
def test_floor_requires_robust_assumptions():
    assert limit(floor(sin(x)), x, 0, "+") == 0
    assert limit(floor(sin(x)), x, 0, "-") == -1
    assert limit(floor(cos(x)), x, 0, "+") == 0
    assert limit(floor(cos(x)), x, 0, "-") == 0
    assert limit(floor(5 + sin(x)), x, 0, "+") == 5
    assert limit(floor(5 + sin(x)), x, 0, "-") == 4
    assert limit(floor(5 + cos(x)), x, 0, "+") == 5
    assert limit(floor(5 + cos(x)), x, 0, "-") == 5
Exemple #27
0
def less_than(a, b):
    if issig('qr', a, b):
        return a[:sym.floor(b)]

    if issig('rr', a, b) or issig('ll', a, b) or issig('ss', a, b):
        return Real(bool(a < b))

    raise BadTypeCombinationError('less_than', a, b)
Exemple #28
0
def greater_than(a, b):
    if issig('qr', a, b):
        return a[sym.floor(b):]

    if issig('rr', a, b) or issig('ll', a, b) or issig('ss', a, b):
        return Real(bool(a > b))

    raise BadTypeCombinationError('greater_than', a, b)
Exemple #29
0
 def gridpoints(self):
     if self.coordinates._data is None:
         raise ValueError("No coordinates attached to this SparseFunction")
     ret = []
     for coords in self.coordinates.data._local:
         ret.append(tuple(int(sympy.floor((c - o.data)/i.spacing.data)) for c, o, i in
                          zip(coords, self.grid.origin, self.grid.dimensions)))
     return ret
Exemple #30
0
def test_uniformsum():
    n = Symbol("n", integer=True)
    x = Symbol("x")
    _k = Symbol("k")

    X = UniformSum(n, symbol=x)
    assert Density(X) == (Lambda(_x, Sum((-1)**_k*(-_k + _x)**(n - 1)
                         *binomial(n, _k), (_k, 0, floor(_x)))/factorial(n - 1)))
Exemple #31
0
def test_issue9474():
    mods = [None, 'math']
    if numpy:
        mods.append('numpy')
    if mpmath:
        mods.append('mpmath')
    for mod in mods:
        f = lambdify(x, S.One / x, modules=mod)
        assert f(2) == 0.5
        f = lambdify(x, floor(S.One / x), modules=mod)
        assert f(2) == 0

    for absfunc, modules in product([Abs, abs], mods):
        f = lambdify(x, absfunc(x), modules=modules)
        assert f(-1) == 1
        assert f(1) == 1
        assert f(3 + 4j) == 5
Exemple #32
0
def test_uniformsum():
    n = Symbol("n", integer=True)
    _k = Dummy("k")
    x = Symbol("x")

    X = UniformSum('x', n)
    res = Sum((-1)**_k*(-_k + x)**(n - 1)*binomial(n, _k), (_k, 0, floor(x)))/factorial(n - 1)
    assert density(X)(x).dummy_eq(res)

    #Tests set functions
    assert X.pspace.domain.set == Interval(0, n)

    #Tests the characteristic_function
    assert characteristic_function(X)(x) == (-I*(exp(I*x) - 1)/x)**n

    #Tests the moment_generating_function
    assert moment_generating_function(X)(x) == ((exp(x) - 1)/x)**n
 def _infer_Resize(self, node):
     assert get_opset(
         self.out_mp_) <= 10  # only support opset 10 Resize for now
     scales = self._try_get_value(node, 1)
     if scales is not None:
         input_sympy_shape = self._get_sympy_shape(node, 0)
         new_sympy_shape = [
             sympy.simplify(sympy.floor(d * s))
             for d, s in zip(input_sympy_shape, scales)
         ]
         self._update_computed_dims(new_sympy_shape)
         vi = self.known_vi_[node.output[0]]
         vi.CopyFrom(
             helper.make_tensor_value_info(
                 node.output[0],
                 self.known_vi_[node.input[0]].type.tensor_type.elem_type,
                 get_shape_from_sympy_shape(new_sympy_shape)))
Exemple #34
0
    def _next_raw(self, c, context):
        n = len(context) + 1

        # Check if the context can be found for this order model and what are
        # its cumulative frequencies
        context_row = self.get_row_by_words(context)

        if context_row is None:
            # Back off to a lower-order model or raise an exception
            if n > 1:
                return self._next_raw(c, context[1:])
            else:
                raise Exception("1-grams context table broken.")
        else:
            # Calculate the cumulative probabilities interval the next word must
            # contain. Explanation of variables:
            #
            # cf - cumulative frequencies of the ngram [context + (w)]
            # CF - cumulative frequencies of the ngram [context]
            # c  - cumulative probabilities of w with the given context

            c1, c2 = c
            CF1, CF2 = context_row
            cf1 = floor(CF1 + c1 * (CF2 - CF1))
            cf2 = ceiling(CF1 + c2 * (CF2 - CF1))

            table = get_table_name(self.dataset, "{n}grams".format(**locals()))

            self.cur.execute("""
              SELECT
                w{n}
              FROM
                {table}
              WHERE
                cf1 <= {cf1} AND cf2 >= {cf2}
              LIMIT 1;
              """.format(**locals())
            )

            ngram_row = self.cur.fetchone()

            if ngram_row is None:
                return None
            else:
                return ngram_row[0]
Exemple #35
0
def test_frac():
    assert isinstance(frac(x), frac)

    assert frac(n) == 0
    assert frac(nan) == nan
    assert frac(Rational(4, 3)) == Rational(1, 3)
    assert frac(-Rational(4, 3)) == Rational(2, 3)

    r = Symbol('r', real=True)
    assert frac(I * r) == I * frac(r)
    assert frac(1 + I * r) == I * frac(r)
    assert frac(0.5 + I * r) == 0.5 + I * frac(r)
    assert frac(n + I * r) == I * frac(r)
    assert frac(n + I * k) == 0
    assert frac(x + I * x) == frac(x + I * x)
    assert frac(x + I * n) == frac(x)

    assert frac(x).rewrite(floor) == x - floor(x)
def _floor_div_nth_cf__end_v1(poly, q):
    '''
it seems N(RootOf(...)) is too slow
I try to use refine_root instead.
'''
    rs = real_roots(poly)
    qt = max(rs)
    Q = floor(qt)

    upper = zero_upper_bound_of_positive_poly(poly)

    ndigit = num_radix_digits(upper, 10)
    Q = int(neval(Q, ndigit + 3))

    assert Q >= 1
    assert not poly.subs(q, Q) > 0
    assert not poly.subs(q, Q + 1) <= 0
    return Q
Exemple #37
0
def apply_grover(oracle, nqubits, iterations=None):
    """Applies grover's algorithm.

    Parameters
    ==========

    oracle : callable
        The unknown callable function that returns true when applied to the
        desired qubits and false otherwise.

    Returns
    =======

    state : Expr
        The resulting state after Grover's algorithm has been iterated.

    Examples
    ========

    Apply grover's algorithm to an even superposition of 2 qubits::

        >>> from sympy.physics.quantum.qapply import qapply
        >>> from sympy.physics.quantum.qubit import IntQubit
        >>> from sympy.physics.quantum.grover import apply_grover
        >>> f = lambda qubits: qubits == IntQubit(2)
        >>> qapply(apply_grover(f, 2))
        |2>

    """
    if nqubits <= 0:
        raise QuantumError(
            'Grover\'s algorithm needs nqubits > 0, received %r qubits'
            % nqubits
        )
    if iterations is None:
        iterations = floor(sqrt(2**nqubits)*(pi/4))

    v = OracleGate(nqubits, oracle)
    iterated = superposition_basis(nqubits)
    for iter in range(iterations):
        iterated = grover_iteration(iterated, v)
        iterated = qapply(iterated)

    return iterated
Exemple #38
0
 def render_BinOp(self, node):
     op_name = node.op.__class__.__name__
     # Sympy implements division and subtraction as multiplication/addition
     if op_name == 'Div':
         op = self.expression_ops['Mult']
         return op(self.render_node(node.left),
                   1 / self.render_node(node.right))
     elif op_name == 'FloorDiv':
         op = self.expression_ops['Mult']
         left = self.render_node(node.left)
         right = self.render_node(node.right)
         return sympy.floor(op(left, 1 / right))
     elif op_name == 'Sub':
         op = self.expression_ops['Add']
         return op(self.render_node(node.left),
                   -self.render_node(node.right))
     else:
         op = self.expression_ops[op_name]
         return op(self.render_node(node.left), self.render_node(node.right))
Exemple #39
0
def test_issue9474():
    mods = [None, 'math']
    if numpy:
        mods.append('numpy')
    if mpmath:
        mods.append('mpmath')
    for mod in mods:
        f = lambdify(x, sympy.S(1) / x, modules=mod)
        assert f(2) == 0.5
        f = lambdify(x, floor(sympy.S(1) / x), modules=mod)
        assert f(2) == 0

    if mpmath:
        f = lambdify(x, sympy.S(1) / sympy.Abs(x), modules=['mpmath'])
        assert isinstance(f(2), mpmath.mpf)

    for absfunc, modules in product([Abs, abs], mods):
        f = lambdify(x, absfunc(x), modules=modules)
        assert f(-1) == 1
        assert f(1) == 1
        assert f(3 + 4j) == 5
def premRSA():
    n = int(
        '0x6c451672f63e8ece9c3bde03f4483ed3d0e286c908a55b78e2d235021d95f4ba403e6cbaf14d15928867bb14ac855d7fbdc6ebbf99f151ab49832e70fdd19e8d29dfc4c4ca7329564a1d4182c1b02ef040d7e347e13db768203319357abe07b1ecaf5d099d3326d2639e0a5991ded8cb46b825709e0942e67f770520c26306e5f44c8ca72313106ff0dd9a90294edaa7e0097997ff2425c266e1d52c6935799a8cf7ebf12f88edd1dc683ffd252facf7fb3e9bca0467ebbb1dbe731e7ff9b245a78ca50e8f810202eef4e44ea0c01443584baf727b13aa2ba8978445345981a264fb15709f7b71b9611e0ef3f0b69c6a3ba9f12ea703bf742b3aa3fc1522d8d20466223bdfe5c2cc726d66a1416bcb26cab2976a915e6646143500e012896f355dea77e10a7ec36aacd547f66bf543a7d7841acbcd4f54ec267ad185984ef74a995ad7c141fa34f46956bb3d66db54c5f8f84252800d968cb1bd47b30030f3c54c8d45b2ed9e1809ae7aad3367a7d3b11c80539282b3deaa8e23bda567e09b87f33a60666e9247cc38c0d09666346d54e18fcd58e987fcfc1796ad4bc0cb498d5e100d640abdbdfcb45039464fe023679ad70fce916a5adffcb58520a22bbf1870cfe5fcbf651a30ace03a716b2a283bfaa076330abd502e1460f2182e64b565c3c1b3a77312fe98e77dd1b8eca1f80fe11d6f2675f9ea90cc533abd507dc285',
        0)
    e = int('0x10001', 0)
    d0 = int(
        '0xa5cb79ef8059485d8ee47a9da0ed128ea83febf509c009aafcada53d35b28a7b020f7308078257aae306052f2086fa89ad9c810a4fd9afe498825bdc16b3050e6e26c2ebcc49de22ab34c09e53a699f29252adc01c1a3c036f192105154d94858bbaf42bf1dfadc0cdf7338c5c9e9fdf9c508bdc9d260df831b781e5ce33b874999ebb0f07d72bbe6d0971a2164b660e1d3df4cb265e8edbc63ec56c2b05ce2eb32cf9808931a3968f1045c38ea022bfd750c3925073d1c5befec2268efe0bd047f2411f081aee2b71c443c5fd26fed6a75c9e31b89dfd93180215eaa51117bcf4be54f140fc39322c5deb32ae1ec164f4ae451a1391d7b612645c06cdf83541',
        0)
    c = int(
        '0x36e7437512d71ca2a412fa411f7d376feaf02db7a6c301284ed9dc7dcffa8a658c24d199aa14d008ed72a88e36e2c5520caf95c88e5deb0d311d4fe2641732455bde7bc1c64a7274bcbe3825cd59b66727354fbbd01ab4ea39dbddd765395fa9c653556987f2f7efbdf86e741573338699e7fb7ad8405eeb02bc8fbca39a55870255328fcd44998bb5339805298575c0aef9bcfe791e8330bac92cd11620ad837ac2f7e9fcc4bf61da3c09cb8455e6d46890d5beb0b1af0bf989c10c6d83604de862bbb82fc697c2513488a9e3321d2590e9f5c0eb4a1882aa26c455da6e45f1fff42e233208ebd494365e89fb8e1ae89ea5b2f800e07b9e6b362bf4caaec11e81a8fc04377a7820f1392057f44bcbac03e9846b29989106e0dcf98559af1d5221aea01dd0d64667eb6615f7cce13e004249f2a0ccf065044450c1bd6661a986a53c983bf810d961f5c0a551fa66a08cf6cabf4e08291f1a08c7ee73c3b7c51a6d1620c9005530b8c1ce883eae095b1949eb4df159a35c7ce654cfc18527f08c8483d3630803bd688040a4b4bae86766f5535421bb8ec9c6e071b280f9e0db26c1cc90b56dba1cd09adeb520a996d6fd6ce135edb9e496986770cff49abc68473edc51ce0c79db915aae4ce1bb6fd42adb62b6b350cb84d37c52f30fe1e4943babf868bed50fa912ca431500ecb18643bb3df560450f673769818fdc48cdcdf6',
        0)

    bitLenN = int(sp.floor(sp.log(n) / sp.log(2)) + 1)
    bitLenD0 = 2048

    assert bitLenD0 >= bitLenN / 2

    d = halfdPartialKeyRecoveryAttack(d0, 2048, 4096, n, e)
    c = pow(c, d, n)
    plaintext = str(bytearray.fromhex(hex(c)[2:]), 'utf-8')
    print(plaintext)
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1)+exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}\\left(x\\right)'

    beta = Function('beta')

    assert latex(beta(x)) == r"\operatorname{beta}\left(x\right)"
    assert latex(sin(x)) == r"\operatorname{sin}\left(x\right)"
    assert latex(sin(x), fold_func_brackets=True) == r"\operatorname{sin}x"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
    r"\operatorname{sin}2 x^{2}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
    r"\operatorname{sin}x^{2}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}\left(x\right)"
    assert latex(asin(x)**2,inv_trig_style="full") == \
        r"\operatorname{arcsin}^{2}\left(x\right)"
    assert latex(asin(x)**2,inv_trig_style="power") == \
        r"\operatorname{sin}^{-1}\left(x\right)^{2}"
    assert latex(asin(x**2),inv_trig_style="power",fold_func_brackets=True) == \
        r"\operatorname{sin}^{-1}x^{2}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\operatorname{\Gamma}\left(x\right)"
    assert latex(Order(x)) == r"\operatorname{\mathcal{O}}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\operatorname{\gamma}\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\operatorname{\Gamma}\left(x, y\right)'
Exemple #42
0
def test_symbolic_Range():
    n = Symbol('n')
    raises(ValueError, lambda: Range(n)[0])
    raises(IndexError, lambda: Range(n, n)[0])
    raises(ValueError, lambda: Range(n, n+1)[0])
    raises(ValueError, lambda: Range(n).size)

    n = Symbol('n', integer=True)
    raises(ValueError, lambda: Range(n)[0])
    raises(IndexError, lambda: Range(n, n)[0])
    assert Range(n, n+1)[0] == n
    raises(ValueError, lambda: Range(n).size)
    assert Range(n, n+1).size == 1

    n = Symbol('n', integer=True, nonnegative=True)
    raises(ValueError, lambda: Range(n)[0])
    raises(IndexError, lambda: Range(n, n)[0])
    assert Range(n+1)[0] == 0
    assert Range(n, n+1)[0] == n
    assert Range(n).size == n
    assert Range(n+1).size == n+1
    assert Range(n, n+1).size == 1

    n = Symbol('n', integer=True, positive=True)
    assert Range(n)[0] == 0
    assert Range(n, n+1)[0] == n
    assert Range(n).size == n
    assert Range(n, n+1).size == 1

    m = Symbol('m', integer=True, positive=True)

    assert Range(n, n+m)[0] == n
    assert Range(n, n+m).size == m
    assert Range(n, n+1).size == 1
    assert Range(n, n+m, 2).size == floor(m/2)

    m = Symbol('m', integer=True, positive=True, even=True)
    assert Range(n, n+m, 2).size == m/2
Exemple #43
0
def test_bng_printer():
    # Constants
    assert _bng_print(sympy.pi) == '_pi'
    assert _bng_print(sympy.E) == '_e'

    x, y = sympy.symbols('x y')

    # Binary functions
    assert _bng_print(sympy.sympify('x & y')) == 'x && y'
    assert _bng_print(sympy.sympify('x | y')) == 'x || y'

    # Trig functions
    assert _bng_print(sympy.sin(x)) == 'sin(x)'
    assert _bng_print(sympy.cos(x)) == 'cos(x)'
    assert _bng_print(sympy.tan(x)) == 'tan(x)'
    assert _bng_print(sympy.asin(x)) == 'asin(x)'
    assert _bng_print(sympy.acos(x)) == 'acos(x)'
    assert _bng_print(sympy.atan(x)) == 'atan(x)'
    assert _bng_print(sympy.sinh(x)) == 'sinh(x)'
    assert _bng_print(sympy.cosh(x)) == 'cosh(x)'
    assert _bng_print(sympy.tanh(x)) == 'tanh(x)'
    assert _bng_print(sympy.asinh(x)) == 'asinh(x)'
    assert _bng_print(sympy.acosh(x)) == 'acosh(x)'
    assert _bng_print(sympy.atanh(x)) == 'atanh(x)'

    # Logs and powers
    assert _bng_print(sympy.log(x)) == 'ln(x)'
    assert _bng_print(sympy.exp(x)) == 'exp(x)'
    assert _bng_print(sympy.sqrt(x)) == 'sqrt(x)'

    # Rounding
    assert _bng_print(sympy.Abs(x)) == 'abs(x)'
    assert _bng_print(sympy.floor(x)) == 'rint(x - 0.5)'
    assert _bng_print(sympy.ceiling(x)) == '(rint(x + 1) - 1)'

    # Min/max
    assert _bng_print(sympy.Min(x, y)) == 'min(x, y)'
    assert _bng_print(sympy.Max(x, y)) == 'max(x, y)'
Exemple #44
0
def test_naturals():
    N = S.Naturals
    assert 5 in N
    assert -5 not in N
    assert 5.5 not in N
    ni = iter(N)
    a, b, c, d = next(ni), next(ni), next(ni), next(ni)
    assert (a, b, c, d) == (1, 2, 3, 4)
    assert isinstance(a, Basic)

    assert N.intersect(Interval(-5, 5)) == Range(1, 6)
    assert N.intersect(Interval(-5, 5, True, True)) == Range(1, 5)

    assert N.boundary == N

    assert N.inf == 1
    assert N.sup is oo
    assert not N.contains(oo)
    for s in (S.Naturals0, S.Naturals):
        assert s.intersection(S.Reals) is s
        assert s.is_subset(S.Reals)

    assert N.as_relational(x) == And(Eq(floor(x), x), x >= 1, x < oo)
Exemple #45
0
def test_integers():
    Z = S.Integers
    assert 5 in Z
    assert -5 in Z
    assert 5.5 not in Z
    assert not Z.contains(oo)
    assert not Z.contains(-oo)

    zi = iter(Z)
    a, b, c, d = next(zi), next(zi), next(zi), next(zi)
    assert (a, b, c, d) == (0, 1, -1, 2)
    assert isinstance(a, Basic)

    assert Z.intersect(Interval(-5, 5)) == Range(-5, 6)
    assert Z.intersect(Interval(-5, 5, True, True)) == Range(-4, 5)
    assert Z.intersect(Interval(5, S.Infinity)) == Range(5, S.Infinity)
    assert Z.intersect(Interval.Lopen(5, S.Infinity)) == Range(6, S.Infinity)

    assert Z.inf is -oo
    assert Z.sup is oo

    assert Z.boundary == Z

    assert Z.as_relational(x) == And(Eq(floor(x), x), -oo < x, x < oo)
Exemple #46
0
def test_latex_functions():
    assert latex(exp(x)) == "$e^{x}$"
    assert latex(exp(1) + exp(2)) == "$e + e^{2}$"

    f = Function('f')
    assert latex(f(x)) == '$\\operatorname{f}\\left(x\\right)$'

    beta = Function('beta')

    assert latex(beta(x)) == r"$\operatorname{beta}\left(x\right)$"
    assert latex(sin(x)) == r"$\operatorname{sin}\left(x\right)$"
    assert latex(sin(x), fold_func_brackets=True) == r"$\operatorname{sin}x$"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
    r"$\operatorname{sin}2 x^{2}$"
    assert latex(sin(x**2), fold_func_brackets=True) == \
    r"$\operatorname{sin}x^{2}$"

    assert latex(asin(x)**2) == r"$\operatorname{asin}^{2}\left(x\right)$"
    assert latex(asin(x)**2,inv_trig_style="full") == \
        r"$\operatorname{arcsin}^{2}\left(x\right)$"
    assert latex(asin(x)**2,inv_trig_style="power") == \
        r"$\operatorname{sin}^{-1}\left(x\right)^{2}$"
    assert latex(asin(x**2),inv_trig_style="power",fold_func_brackets=True) == \
        r"$\operatorname{sin}^{-1}x^{2}$"

    assert latex(factorial(k)) == r"$k!$"
    assert latex(factorial(-k)) == r"$\left(- k\right)!$"

    assert latex(floor(x)) == r"$\lfloor{x}\rfloor$"
    assert latex(ceiling(x)) == r"$\lceil{x}\rceil$"
    assert latex(abs(x)) == r"$\lvert{x}\rvert$"
    assert latex(re(x)) == r"$\Re{x}$"
    assert latex(im(x)) == r"$\Im{x}$"
    assert latex(conjugate(x)) == r"$\overline{x}$"
    assert latex(gamma(x)) == r"$\operatorname{\Gamma}\left(x\right)$"
    assert latex(Order(x)) == r"$\operatorname{\mathcal{O}}\left(x\right)$"
Exemple #47
0
def test_issue_4149():
    assert floor(3 + pi * I + y * I) == 3 + floor(pi + y) * I
    assert floor(3 * I + pi * I + y * I) == floor(3 + pi + y) * I
    assert floor(3 + E + pi * I + y * I) == 5 + floor(pi + y) * I
Exemple #48
0
def test_floor():

    assert floor(nan) == nan

    assert floor(oo) == oo
    assert floor(-oo) == -oo

    assert floor(0) == 0

    assert floor(1) == 1
    assert floor(-1) == -1

    assert floor(E) == 2
    assert floor(-E) == -3

    assert floor(2 * E) == 5
    assert floor(-2 * E) == -6

    assert floor(pi) == 3
    assert floor(-pi) == -4

    assert floor(Rational(1, 2)) == 0
    assert floor(-Rational(1, 2)) == -1

    assert floor(Rational(7, 3)) == 2
    assert floor(-Rational(7, 3)) == -3

    assert floor(Float(17.0)) == 17
    assert floor(-Float(17.0)) == -17

    assert floor(Float(7.69)) == 7
    assert floor(-Float(7.69)) == -8

    assert floor(I) == I
    assert floor(-I) == -I
    e = floor(i)
    assert e.func is floor and e.args[0] == i

    assert floor(oo * I) == oo * I
    assert floor(-oo * I) == -oo * I

    assert floor(2 * I) == 2 * I
    assert floor(-2 * I) == -2 * I

    assert floor(I / 2) == 0
    assert floor(-I / 2) == -I

    assert floor(E + 17) == 19
    assert floor(pi + 2) == 5

    assert floor(E + pi) == floor(E + pi)
    assert floor(I + pi) == floor(I + pi)

    assert floor(floor(pi)) == 3
    assert floor(floor(y)) == floor(y)
    assert floor(floor(x)) == floor(floor(x))

    assert floor(x) == floor(x)
    assert floor(2 * x) == floor(2 * x)
    assert floor(k * x) == floor(k * x)

    assert floor(k) == k
    assert floor(2 * k) == 2 * k
    assert floor(k * n) == k * n

    assert floor(k / 2) == floor(k / 2)

    assert floor(x + y) == floor(x + y)

    assert floor(x + 3) == floor(x + 3)
    assert floor(x + k) == floor(x + k)

    assert floor(y + 3) == floor(y) + 3
    assert floor(y + k) == floor(y) + k

    assert floor(3 + I * y + pi) == 6 + floor(y) * I

    assert floor(k + n) == k + n

    assert floor(x * I) == floor(x * I)
    assert floor(k * I) == k * I

    assert floor(Rational(23, 10) - E * I) == 2 - 3 * I

    assert floor(sin(1)) == 0
    assert floor(sin(-1)) == -1

    assert floor(exp(2)) == 7

    assert floor(log(8) / log(2)) != 2
    assert int(floor(log(8) / log(2)).evalf(chop=True)) == 3

    assert floor(factorial(50)/exp(1)) == \
        11188719610782480504630258070757734324011354208865721592720336800

    assert (floor(y) <= y) == True
    assert (floor(y) > y) == False
    assert (floor(x) <= x).is_Relational  # x could be non-real
    assert (floor(x) > x).is_Relational
    assert (floor(x) <= y).is_Relational  # arg is not same as rhs
    assert (floor(x) > y).is_Relational
Exemple #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()
Exemple #50
0
def test_floor():
    assert limit(floor(x), x, -2, "+") == -2
    assert limit(floor(x), x, -2, "-") == -3
    assert limit(floor(x), x, -1, "+") == -1
    assert limit(floor(x), x, -1, "-") == -2
    assert limit(floor(x), x, 0, "+") == 0
    assert limit(floor(x), x, 0, "-") == -1
    assert limit(floor(x), x, 1, "+") == 1
    assert limit(floor(x), x, 1, "-") == 0
    assert limit(floor(x), x, 2, "+") == 2
    assert limit(floor(x), x, 2, "-") == 1
    assert limit(floor(x), x, 248, "+") == 248
    assert limit(floor(x), x, 248, "-") == 247
Exemple #51
0
    def _eval_expand_func(self, **hints):
        from sympy import exp, I, floor, Add, Poly, Dummy, exp_polar, unpolarify

        z, s, a = self.args
        if z == 1:
            return zeta(s, a)
        if s.is_Integer and s <= 0:
            t = Dummy("t")
            p = Poly((t + a) ** (-s), t)
            start = 1 / (1 - t)
            res = S.Zero
            for c in reversed(p.all_coeffs()):
                res += c * start
                start = t * start.diff(t)
            return res.subs(t, z)

        if a.is_Rational:
            # See section 18 of
            #   Kelly B. Roach.  Hypergeometric Function Representations.
            #   In: Proceedings of the 1997 International Symposium on Symbolic and
            #   Algebraic Computation, pages 205-211, New York, 1997. ACM.
            # TODO should something be polarified here?
            add = S.Zero
            mul = S.One
            # First reduce a to the interaval (0, 1]
            if a > 1:
                n = floor(a)
                if n == a:
                    n -= 1
                a -= n
                mul = z ** (-n)
                add = Add(*[-(z ** (k - n)) / (a + k) ** s for k in range(n)])
            elif a <= 0:
                n = floor(-a) + 1
                a += n
                mul = z ** n
                add = Add(*[z ** (n - 1 - k) / (a - k - 1) ** s for k in range(n)])

            m, n = S([a.p, a.q])
            zet = exp_polar(2 * pi * I / n)
            root = z ** (1 / n)
            return add + mul * n ** (s - 1) * Add(
                *[
                    polylog(s, zet ** k * root)._eval_expand_func(**hints)
                    / (unpolarify(zet) ** k * root) ** m
                    for k in range(n)
                ]
            )

        # TODO use minpoly instead of ad-hoc methods when issue 5888 is fixed
        if (
            isinstance(z, exp)
            and (z.args[0] / (pi * I)).is_Rational
            or z in [-1, I, -I]
        ):
            # TODO reference?
            if z == -1:
                p, q = S([1, 2])
            elif z == I:
                p, q = S([1, 4])
            elif z == -I:
                p, q = S([-1, 4])
            else:
                arg = z.args[0] / (2 * pi * I)
                p, q = S([arg.p, arg.q])
            return Add(
                *[
                    exp(2 * pi * I * k * p / q) / q ** s * zeta(s, (k + a) / q)
                    for k in range(q)
                ]
            )

        return lerchphi(z, s, a)
Exemple #52
0
def test_floor():
    x = Symbol("x")
    e1 = sympy.floor(sympy.Symbol("x"))
    e2 = floor(x)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1
Exemple #53
0
 def LP(P, b):
     return sp.integrate(P, (x, 0, sp.floor((b + 1) / 4))).evalf()
Exemple #54
0
def sympy_intdiv_fix(expr):
    """ Fix for SymPy printing out reciprocal values when they should be
        integral in "ceiling/floor" sympy functions.
    """
    nexpr = expr
    if not isinstance(expr, sympy.Basic):
        return expr

    # The properties avoid matching the silly case "ceiling(N/32)" as
    # ceiling of 1/N and 1/32
    a = sympy.Wild('a', properties=[lambda k: k.is_Symbol or k.is_Integer])
    b = sympy.Wild('b', properties=[lambda k: k.is_Symbol or k.is_Integer])
    c = sympy.Wild('c')
    d = sympy.Wild('d')
    int_ceil = sympy.Function('int_ceil')
    int_floor = sympy.Function('int_floor')

    processed = 1
    while processed > 0:
        processed = 0
        for ceil in nexpr.find(sympy.ceiling):
            # Simple ceiling
            m = ceil.match(sympy.ceiling(a / b))
            if m is not None:
                nexpr = nexpr.subs(ceil, int_ceil(m[a], m[b]))
                processed += 1
                continue
            # Ceiling of ceiling: "ceil(ceil(c/d) / b)"
            m = ceil.match(sympy.ceiling(int_ceil(c, d) / b))
            if m is not None:
                nexpr = nexpr.subs(ceil, int_ceil(int_ceil(m[c], m[d]), m[b]))
                processed += 1
                continue
            # Ceiling of ceiling: "ceil(a / ceil(c/d))"
            m = ceil.match(sympy.ceiling(a / int_ceil(c, d)))
            if m is not None:
                nexpr = nexpr.subs(ceil, int_ceil(m[a], int_ceil(m[c], m[d])))
                processed += 1
                continue
            # Match ceiling of multiplication with our custom integer functions
            m = ceil.match(sympy.ceiling(a * int_floor(c, d)))
            if m is not None:
                nexpr = nexpr.subs(ceil, m[a] * int_floor(m[c], m[d]))
                processed += 1
                continue
            m = ceil.match(sympy.ceiling(a * int_ceil(c, d)))
            if m is not None:
                nexpr = nexpr.subs(ceil, m[a] * int_ceil(m[c], m[d]))
                processed += 1
                continue
        for floor in nexpr.find(sympy.floor):
            # Simple floor
            m = floor.match(sympy.floor(a / b))
            if m is not None:
                nexpr = nexpr.subs(floor, int_floor(m[a], m[b]))
                processed += 1
                continue
            # Floor of floor: "floor(floor(c/d) / b)"
            m = floor.match(sympy.floor(int_floor(c, d) / b))
            if m is not None:
                nexpr = nexpr.subs(floor, int_floor(int_floor(m[c], m[d]),
                                                    m[b]))
                processed += 1
                continue
            # Floor of floor: "floor(a / floor(c/d))"
            m = floor.match(sympy.floor(a / int_floor(c, d)))
            if m is not None:
                nexpr = nexpr.subs(floor, int_floor(m[a],
                                                    int_floor(m[c], m[d])))
                processed += 1
                continue

    return nexpr
Exemple #55
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}{\\left (x \\right )}'

    beta = Function('beta')

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
        r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
        r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2), inv_trig_style="power",
                 fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(subfactorial(k)) == r"!k"
    assert latex(subfactorial(-k)) == r"!\left(- k\right)"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3,
                                  k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta\left(x\right)'

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(polylog(x,
                         y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(Ei(x)) == r'\operatorname{Ei}{\left (x \right )}'
    assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left (x \right )}'
    assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
    assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left (x \right )}'
    assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left (x \right )}'
    assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left (x \right )}'
    assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}{\left (x \right )}'

    assert latex(jacobi(n, a, b,
                        x)) == r'P_{n}^{\left(a,b\right)}\left(x\right)'
    assert latex(jacobi(
        n, a, b,
        x)**2) == r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}'
    assert latex(gegenbauer(n, a,
                            x)) == r'C_{n}^{\left(a\right)}\left(x\right)'
    assert latex(gegenbauer(
        n, a,
        x)**2) == r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)'
    assert latex(chebyshevt(n,
                            x)**2) == r'\left(T_{n}\left(x\right)\right)^{2}'
    assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)'
    assert latex(chebyshevu(n,
                            x)**2) == r'\left(U_{n}\left(x\right)\right)^{2}'
    assert latex(legendre(n, x)) == r'P_{n}\left(x\right)'
    assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}'
    assert latex(assoc_legendre(n, a,
                                x)) == r'P_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_legendre(
        n, a,
        x)**2) == r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)'
    assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}'
    assert latex(assoc_laguerre(n, a,
                                x)) == r'L_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_laguerre(
        n, a,
        x)**2) == r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(hermite(n, x)) == r'H_{n}\left(x\right)'
    assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}'

    # Test latex printing of function names with "_"
    assert latex(
        polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(0)**
                 3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"
Exemple #56
0
def floor_divide(x1, x2):
    """floor_divide(x1, x2)

    Return the largest integer smaller or equal to the division of the inputs.
    """
    return floor(divide(x1, x2))
Exemple #57
0
 def apply_real(self, x, evaluation):
     'Floor[x_]'
     x = x.to_sympy()
     return from_sympy(sympy.floor(x))
Exemple #58
0
def test_issue_14313_comment():
    assert limit(floor(n / 2), n, oo) is oo
Exemple #59
0
def test_floor():
    x = Symbol('x')
    assert floor(x).series(x) == 0
    assert floor(-x).series(x) == -1
    assert floor(sin(x)).series(x) == 0
    assert floor(sin(-x)).series(x) == -1
    assert floor(x**3).series(x) == 0
    assert floor(-x**3).series(x) == -1
    assert floor(cos(x)).series(x) == 0
    assert floor(cos(-x)).series(x) == 0
    assert floor(5 + sin(x)).series(x) == 5
    assert floor(5 + sin(-x)).series(x) == 4

    assert floor(x).series(x, 2) == 2
    assert floor(-x).series(x, 2) == -3

    x = Symbol('x', negative=True)
    assert floor(x + 1.5).series(x) == 1
Exemple #60
0
def test_issue_13098():
    assert floor(log(S('9.' + '9' * 20), 10)) == 0
    assert ceiling(log(S('9.' + '9' * 20), 10)) == 1
    assert floor(log(20 - S('9.' + '9' * 20), 10)) == 1
    assert ceiling(log(20 - S('9.' + '9' * 20), 10)) == 2