Esempio n. 1
0
    def is_convergent(self):
        r"""Checks for the convergence of a Sum.

        We divide the study of convergence of infinite sums and products in
        two parts.

        First Part:
        One part is the question whether all the terms are well defined, i.e.,
        they are finite in a sum and also non-zero in a product. Zero
        is the analogy of (minus) infinity in products as
        :math:`e^{-\infty} = 0`.

        Second Part:
        The second part is the question of convergence after infinities,
        and zeros in products, have been omitted assuming that their number
        is finite. This means that we only consider the tail of the sum or
        product, starting from some point after which all terms are well
        defined.

        For example, in a sum of the form:

        .. math::

            \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}

        where a and b are numbers. The routine will return true, even if there
        are infinities in the term sequence (at most two). An analogous
        product would be:

        .. math::

            \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}

        This is how convergence is interpreted. It is concerned with what
        happens at the limit. Finding the bad terms is another independent
        matter.

        Note: It is responsibility of user to see that the sum or product
        is well defined.

        There are various tests employed to check the convergence like
        divergence test, root test, integral test, alternating series test,
        comparison tests, Dirichlet tests. It returns true if Sum is convergent
        and false if divergent and NotImplementedError if it can not be checked.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolutely_convergent()

        Product.is_convergent()
        """
        from sympy import Interval, Integral, Limit, log, symbols, Ge, Gt, simplify
        p, q = symbols('p q', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError(
                "convergence checking for more than one symbol "
                "containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity
        # and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        sym_ = Dummy(sym.name, integer=True, positive=True)
        sequence_term = sequence_term.xreplace({sym: sym_})
        sym = sym_

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func, cond in sequence_term.args:
                # see if it represents something going to oo
                if cond == True or cond.as_set().sup is S.Infinity:
                    s = Sum(func, (sym, lower_limit, upper_limit))
                    return s.is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit(sequence_term, sym, upper_limit)
            if lim_val.is_number and lim_val is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        try:
            lim_val_abs = limit(abs(sequence_term), sym, upper_limit)
            if lim_val_abs.is_number and lim_val_abs is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### ----------- ratio test ---------------- ###
        next_sequence_term = sequence_term.xreplace({sym: sym + 1})
        ratio = combsimp(powsimp(next_sequence_term / sequence_term))
        lim_ratio = limit(ratio, sym, upper_limit)
        if lim_ratio.is_number:
            if abs(lim_ratio) > 1:
                return S.false
            if abs(lim_ratio) < 1:
                return S.true

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] >= -1:
                return S.false

        p2_series_test = order.expr.match((1 / sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] <= 1:
                return S.false

        ### ------------- Limit comparison test -----------###
        # (1/n) comparison
        try:
            lim_comp = limit(sym * sequence_term, sym, S.Infinity)
            if lim_comp.is_number and lim_comp > 0:
                return S.false
        except NotImplementedError:
            pass

        ### ----------- root test ---------------- ###
        lim = Limit(abs(sequence_term)**(1 / sym), sym, S.Infinity)
        lim_evaluated = lim.doit()
        if lim_evaluated.is_number:
            if lim_evaluated < 1:
                return S.true
            if lim_evaluated > 1:
                return S.false

        ### ------------- alternating series test ----------- ###
        dict_val = sequence_term.match((-1)**(sym + p) * q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true

        ### ------------- comparison test ------------- ###
        # (1/log(n)**p) comparison
        log_test = order.expr.match(1 / (log(sym)**p))
        if log_test is not None:
            return S.false

        # (1/(n*log(n)**p)) comparison
        log_n_test = order.expr.match(1 / (sym * (log(sym))**p))
        if log_n_test is not None:
            if log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n*log(n)*log(log(n))*p)) comparison
        log_log_n_test = order.expr.match(1 / (sym *
                                               (log(sym) * log(log(sym))**p)))
        if log_log_n_test is not None:
            if log_log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n**p*log(n))) comparison
        n_log_test = order.expr.match(1 / (sym**p * log(sym)))
        if n_log_test is not None:
            if n_log_test[p] > 1:
                return S.true
            return S.false

        ### ------------- integral test -------------- ###
        maxima = solveset(sequence_term.diff(sym), sym, interval)
        if not maxima:
            check_interval = interval
        elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
            check_interval = Interval(maxima.sup, interval.sup)
            if (is_decreasing(sequence_term, check_interval)
                    or is_decreasing(-sequence_term, check_interval)):
                integral_val = Integral(sequence_term,
                                        (sym, lower_limit, upper_limit))
                try:
                    integral_val_evaluated = integral_val.doit()
                    if integral_val_evaluated.is_number:
                        return S(integral_val_evaluated.is_finite)
                except NotImplementedError:
                    pass

        ### ----- Dirichlet and bounded times convergent tests ----- ###
        # TODO
        #
        # Dirichlet_test
        # https://en.wikipedia.org/wiki/Dirichlet%27s_test
        #
        # Bounded times convergent test
        # It is based on comparison theorems for series.
        # In particular, if the general term of a series can
        # be written as a product of two terms a_n and b_n
        # and if a_n is bounded and if Sum(b_n) is absolutely
        # convergent, then the original series Sum(a_n * b_n)
        # is absolutely convergent and so convergent.
        #
        # The following code can grows like 2**n where n is the
        # number of args in order.expr
        # Possibly combined with the potentially slow checks
        # inside the loop, could make this test extremely slow
        # for larger summation expressions.

        if order.expr.is_Mul:
            args = order.expr.args
            argset = set(args)

            ### -------------- Dirichlet tests -------------- ###
            m = Dummy('m', integer=True)

            def _dirichlet_test(g_n):
                try:
                    ing_val = limit(
                        Sum(g_n, (sym, interval.inf, m)).doit(), m, S.Infinity)
                    if ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            ### -------- bounded times convergent test ---------###
            def _bounded_convergent_test(g1_n, g2_n):
                try:
                    lim_val = limit(g1_n, sym, upper_limit)
                    if lim_val.is_finite or (
                            isinstance(lim_val, AccumulationBounds) and
                        (lim_val.max - lim_val.min).is_finite):
                        if Sum(g2_n, (sym, lower_limit,
                                      upper_limit)).is_absolutely_convergent():
                            return S.true
                except NotImplementedError:
                    pass

            for n in range(1, len(argset)):
                for a_tuple in itertools.combinations(args, n):
                    b_set = argset - set(a_tuple)
                    a_n = Mul(*a_tuple)
                    b_n = Mul(*b_set)

                    if is_decreasing(a_n, interval):
                        dirich = _dirichlet_test(b_n)
                        if dirich is not None:
                            return dirich

                    bc_test = _bounded_convergent_test(a_n, b_n)
                    if bc_test is not None:
                        return bc_test

        _sym = self.limits[0][0]
        sequence_term = sequence_term.xreplace({sym: _sym})
        raise NotImplementedError(
            "The algorithm to find the Sum convergence of %s "
            "is not yet implemented" % (sequence_term))
Esempio n. 2
0
    def is_convergent(self):
        r"""Checks for the convergence of a Sum.

        We divide the study of convergence of infinite sums and products in
        two parts.

        First Part:
        One part is the question whether all the terms are well defined, i.e.,
        they are finite in a sum and also non-zero in a product. Zero
        is the analogy of (minus) infinity in products as
        :math:`e^{-\infty} = 0`.

        Second Part:
        The second part is the question of convergence after infinities,
        and zeros in products, have been omitted assuming that their number
        is finite. This means that we only consider the tail of the sum or
        product, starting from some point after which all terms are well
        defined.

        For example, in a sum of the form:

        .. math::

            \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}

        where a and b are numbers. The routine will return true, even if there
        are infinities in the term sequence (at most two). An analogous
        product would be:

        .. math::

            \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}

        This is how convergence is interpreted. It is concerned with what
        happens at the limit. Finding the bad terms is another independent
        matter.

        Note: It is responsibility of user to see that the sum or product
        is well defined.

        There are various tests employed to check the convergence like
        divergence test, root test, integral test, alternating series test,
        comparison tests, Dirichlet tests. It returns true if Sum is convergent
        and false if divergent and NotImplementedError if it can not be checked.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolutely_convergent()

        Product.is_convergent()
        """
        from sympy import Interval, Integral, Limit, log, symbols, Ge, Gt, simplify
        p, q = symbols('p q', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError("convergence checking for more than one symbol "
                                      "containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity
        # and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        sym_ = Dummy(sym.name, integer=True, positive=True)
        sequence_term = sequence_term.xreplace({sym: sym_})
        sym = sym_

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func, cond in sequence_term.args:
                # see if it represents something going to oo
                if cond == True or cond.as_set().sup is S.Infinity:
                    s = Sum(func, (sym, lower_limit, upper_limit))
                    return s.is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit(sequence_term, sym, upper_limit)
            if lim_val.is_number and lim_val is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        try:
            lim_val_abs = limit(abs(sequence_term), sym, upper_limit)
            if lim_val_abs.is_number and lim_val_abs is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### ----------- ratio test ---------------- ###
        next_sequence_term = sequence_term.xreplace({sym: sym + 1})
        ratio = combsimp(powsimp(next_sequence_term/sequence_term))
        lim_ratio = limit(ratio, sym, upper_limit)
        if lim_ratio.is_number:
            if abs(lim_ratio) > 1:
                return S.false
            if abs(lim_ratio) < 1:
                return S.true

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] >= -1:
                return S.false

        p2_series_test = order.expr.match((1/sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] <= 1:
                return S.false

        ### ------------- Limit comparison test -----------###
        # (1/n) comparison
        try:
            lim_comp = limit(sym*sequence_term, sym, S.Infinity)
            if lim_comp.is_number and lim_comp > 0:
                    return S.false
        except NotImplementedError:
            pass

        ### ----------- root test ---------------- ###
        lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
        lim_evaluated = lim.doit()
        if lim_evaluated.is_number:
            if lim_evaluated < 1:
                return S.true
            if lim_evaluated > 1:
                return S.false

        ### ------------- alternating series test ----------- ###
        dict_val = sequence_term.match((-1)**(sym + p)*q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true

        ### ------------- comparison test ------------- ###
        # (1/log(n)**p) comparison
        log_test = order.expr.match(1/(log(sym)**p))
        if log_test is not None:
            return S.false

        # (1/(n*log(n)**p)) comparison
        log_n_test = order.expr.match(1/(sym*(log(sym))**p))
        if log_n_test is not None:
            if log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n*log(n)*log(log(n))*p)) comparison
        log_log_n_test = order.expr.match(1/(sym*(log(sym)*log(log(sym))**p)))
        if log_log_n_test is not None:
            if log_log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n**p*log(n))) comparison
        n_log_test = order.expr.match(1/(sym**p*log(sym)))
        if n_log_test is not None:
            if n_log_test[p] > 1:
                return S.true
            return S.false

        ### ------------- integral test -------------- ###
        maxima = solveset(sequence_term.diff(sym), sym, interval)
        if not maxima:
            check_interval = interval
        elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
            check_interval = Interval(maxima.sup, interval.sup)
            if (
                    is_decreasing(sequence_term, check_interval) or
                    is_decreasing(-sequence_term, check_interval)):
                integral_val = Integral(
                    sequence_term, (sym, lower_limit, upper_limit))
                try:
                    integral_val_evaluated = integral_val.doit()
                    if integral_val_evaluated.is_number:
                        return S(integral_val_evaluated.is_finite)
                except NotImplementedError:
                    pass

        ### -------------- Dirichlet tests -------------- ###
        if order.expr.is_Mul:
            a_n, b_n = order.expr.args[0], order.expr.args[1]
            m = Dummy('m', integer=True)

            def _dirichlet_test(g_n):
                try:
                    ing_val = limit(Sum(g_n, (sym, interval.inf, m)).doit(), m, S.Infinity)
                    if ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            if is_decreasing(a_n, interval):
                dirich1 = _dirichlet_test(b_n)
                if dirich1 is not None:
                    return dirich1

            if is_decreasing(b_n, interval):
                dirich2 = _dirichlet_test(a_n)
                if dirich2 is not None:
                    return dirich2

        _sym = self.limits[0][0]
        sequence_term = sequence_term.xreplace({sym: _sym})
        raise NotImplementedError("The algorithm to find the Sum convergence of %s "
                                  "is not yet implemented" % (sequence_term))
Esempio n. 3
0
def test_doit2():
    f = Integral(2 * x, x)
    l = Limit(f, x, oo)
    # limit() breaks on the contained Integral.
    assert l.doit(deep=False) == l
Esempio n. 4
0
# Finding the limit of 1/x in the infinity

from sympy import Limit, Symbol, S, sin
x = Symbol('x')
Limit(1 / x, x, S.Infinity)

l = Limit(1 / x, x, S.Infinity)

var = input("For what variable do you want to solve the limit? (maybe x..)\n")

tendence = input(
    "X tends for what? For infinity type infinity, for minus infinity type -infinity\n"
)

if (tendence == "infinity"):
    tendence = S.Infinity

elif (tendence == "-infinity"):
    tendence = S.Infinity * -1

# Using Limit to solve, guess what? Limits!
limit_equation = input("Insert the equation that you want to calculate:\n")

lim = Limit(limit_equation, var, tendence)

print(lim.doit(hints=True))
Esempio n. 5
0
from matplotlib import pyplot as plt
from sympy import Limit, Symbol, S
import numpy as np

def f(x):
    return 1/x

fx_name = r'$f(x)=\frac{1}{x}$'
# using 101 steps results in in array including the value 0
x = np.linspace(-10,10,101)
# f(0) = nan -> a nan value creates a gap
y = f(x)
plt.plot(x, y, label=fx_name)
plt.legend(loc='upper left')
plt.show()

# Limit

x = Symbol( 'x' )
# lim x -> +inf
l = Limit( '1/x', x, S.Infinity )
l.doit()

# lim x -> 0, from -inf
l = Limit( '1/x', x, 0, dir='-' )
l.doit()

# lim x -> 0, from +inf
l = Limit( '1/x', x, 0, dir='+' )
l.doit()
Esempio n. 6
0
def test_doit():
    f = Integral(2 * x, x)
    l = Limit(f, x, oo)
    assert l.doit() == oo
Esempio n. 7
0
import sympy
import math
from sympy import Symbol, solve, sin, Limit, S, oo

theta = Symbol('theta')
# math.sin(theta)

print(sympy.sin(theta) * sympy.sin(theta))

u = Symbol('u')
t = Symbol('t')
g = Symbol('g')

print(solve(u * sin(theta) - g * t, t))

x = Symbol('x')
l = Limit(1 / x, x, oo)
print(l.doit())

st = 5 * t**2 + 2 * t + 8
t1 = Symbol('t1')
delta_t = Symbol('delta_t')

st1 = st.subs({t: t1})
st1_delta = (st.subs({t: t1 + delta_t}))
f_d = Limit(((st1_delta - st1) / delta_t), delta_t, 0)
print(f_d.doit())
'''
Chapter 7: Solving Calculus Problems
'''
#Finding the limit of a function

>>> from sympy import Limit, Symbol, S
>>> x=Symbol('x')
>>> Limit(1/x,x,S.Infinity)
Limit(1/x, x, oo, dir='-')


          #We must initialize it

>>> l=Limit(1/x,x,S.Infinity)
>>> l.doit()
0

          #We can choose from which side the limit comes
>>> Limit(1/x,x,0,dir='-').doit()
-oo

>>> Limit(1/x,x,0,dir='+').doit()
oo

          #The limit can also csolve limits of indeterminante forms (0/0)

>>> Limit(sin(x)/x,x,0).doit()
1

     #Continuous Comund interest
               #The compound interest is calculated as follows (p- principal amount, r- rate of interest ,t-number of years, n- number of compundings)
Esempio n. 9
0
import math
import sympy
from sympy import Symbol, Limit, S

x = Symbol('x')
print("Limit {0} ".format(Limit(1 / x, x, S.Infinity)))
l = Limit(1 / x, x, S.Infinity)
print("Limit {0} ".format(l.doit()))
Esempio n. 10
0
# %%
from sympy import Symbol, Limit, init_printing

init_printing(use_latex=True)

x = Symbol('x')


def f(x):
    return (x**3 + x**2 + x)**101


def g(x):
    return (x**2 - (2 * x)) / (x + 1)


print('Considerando a função f(x)')
display(f(x))
print('\ne a função g(x)')
display(g(x))

limite_fx = Limit(f(x), x, -1)
limite_gx = Limit(g(x), x, 3)

print('\nCalcule o valor do seguinte limite:')
display(limite_fx - 4 * limite_gx)

print('\nResultado: {}'.format(limite_fx.doit() - (4 * limite_gx.doit())))
Esempio n. 11
0
'''
    Finding the Limit of Functions
'''

from sympy import Limit, Symbol, S

# Unevaluated
x = Symbol('x')

# Find the value of the limit
l = Limit(1/x, x, S.Infinity)
print(Limit(1/x, x, S.Infinity), '=', l.doit())

Esempio n. 12
0
    def is_convergent(self):
        """
        Convergence tests are used for checking the convergence of
        a series. There are various tests employed to check the convergence,
        returns true if convergent and false if divergent and NotImplementedError
        if can not be checked. Like divergence test, root test, integral test,
        alternating series test, comparison tests, Dirichlet tests.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import Interval, factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolute_convergent()
        """
        from sympy import Interval, Integral, Limit, log, symbols, Ge, Gt, simplify
        p, q = symbols('p q', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError(
                "convergence checking for more that one symbol \
                                        containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func_cond in sequence_term.args:
                if func_cond[1].func is Ge or func_cond[
                        1].func is Gt or func_cond[1] == True:
                    return Sum(
                        func_cond[0],
                        (sym, lower_limit, upper_limit)).is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit(abs(sequence_term), sym, upper_limit)
            if lim_val.is_number and lim_val != S.Zero:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] > -1:
                return S.false

        p2_series_test = order.expr.match((1 / sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] < 1:
                return S.false

        ### ----------- root test ---------------- ###
        lim = Limit(abs(sequence_term)**(1 / sym), sym, S.Infinity)
        lim_evaluated = lim.doit()
        if lim_evaluated.is_number:
            if lim_evaluated < 1:
                return S.true
            if lim_evaluated > 1:
                return S.false

        ### ------------- alternating series test ----------- ###
        d = symbols('d', cls=Dummy)
        dict_val = sequence_term.match((-1)**(sym + p) * q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true

        ### ------------- comparison test ------------- ###
        # (1/log(n)**p) comparison
        log_test = order.expr.match(1 / (log(sym)**p))
        if log_test is not None:
            return S.false

        # (1/(n*log(n)**p)) comparison
        log_n_test = order.expr.match(1 / (sym * (log(sym))**p))
        if log_n_test is not None:
            if log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n*log(n)*log(log(n))*p)) comparison
        log_log_n_test = order.expr.match(1 / (sym *
                                               (log(sym) * log(log(sym))**p)))
        if log_log_n_test is not None:
            if log_log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n**p*log(n))) comparison
        n_log_test = order.expr.match(1 / (sym**p * log(sym)))
        if n_log_test is not None:
            if n_log_test[p] > 1:
                return S.true
            return S.false

        ### ------------- integral test -------------- ###
        if is_decreasing(sequence_term, interval):
            integral_val = Integral(sequence_term,
                                    (sym, lower_limit, upper_limit))
            try:
                integral_val_evaluated = integral_val.doit()
                if integral_val_evaluated.is_number:
                    return S(integral_val_evaluated.is_finite)
            except NotImplementedError:
                pass

        ### -------------- Dirichlet tests -------------- ###
        if order.expr.is_Mul:
            a_n, b_n = order.expr.args[0], order.expr.args[1]
            m = Dummy('m', integer=True)

            def _dirichlet_test(g_n):
                try:
                    ing_val = limit(
                        Sum(g_n, (sym, interval.inf, m)).doit(), m, S.Infinity)
                    if ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            if is_decreasing(a_n, interval):
                dirich1 = _dirichlet_test(b_n)
                if dirich1 is not None:
                    return dirich1

            if is_decreasing(b_n, interval):
                dirich2 = _dirichlet_test(a_n)
                if dirich2 is not None:
                    return dirich2

        raise NotImplementedError(
            "The algorithm to find the convergence of %s "
            "is not yet implemented" % (sequence_term))
Esempio n. 13
0
from sympy import symbols, Limit, S, pprint

t = symbols('t')
pT = .37 + .21 * t
lim = Limit(pT, t, S.Infinity)

pprint(lim.doit())

x = symbols('x')
fx = .37 + .21 * x
fx.subs({x: 2.99999})

.37 + .21 + .21
Esempio n. 14
0
def test_doit():
    f = Integral(2 * x, x)
    l = Limit(f, x, oo)
    assert l.doit() == oo
Esempio n. 15
0
    def is_convergent(self):
        r"""Checks for the convergence of a Sum.

        We divide the study of convergence of infinite sums and products in
        two parts.

        First Part:
        One part is the question whether all the terms are well defined, i.e.,
        they are finite in a sum and also non-zero in a product. Zero
        is the analogy of (minus) infinity in products as :math:`e^{-\infty} = 0`.

        Second Part:
        The second part is the question of convergence after infinities,
        and zeros in products, have been omitted assuming that their number
        is finite. This means that we only consider the tail of the sum or
        product, starting from some point after which all terms are well
        defined.

        For example, in a sum of the form:

        .. math::

            \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}

        where a and b are numbers. The routine will return true, even if there
        are infinities in the term sequence (at most two). An analogous
        product would be:

        .. math::

            \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}

        This is how convergence is interpreted. It is concerned with what
        happens at the limit. Finding the bad terms is another independent
        matter.

        Note: It is responsibility of user to see that the sum or product
        is well defined.

        There are various tests employed to check the convergence like
        divergence test, root test, integral test, alternating series test,
        comparison tests, Dirichlet tests. It returns true if Sum is convergent
        and false if divergent and NotImplementedError if it can not be checked.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolutely_convergent()

        Product.is_convergent()
        """
        from sympy import Interval, Integral, Limit, log, symbols, Ge, Gt, simplify
        p, q = symbols('p q', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError(
                "convergence checking for more than one symbol "
                "containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity
        # and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func_cond in sequence_term.args:
                if func_cond[1].func is Ge or func_cond[
                        1].func is Gt or func_cond[1] == True:
                    return Sum(
                        func_cond[0],
                        (sym, lower_limit, upper_limit)).is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit(sequence_term, sym, upper_limit)
            if lim_val.is_number and lim_val is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        try:
            lim_val_abs = limit(abs(sequence_term), sym, upper_limit)
            if lim_val_abs.is_number and lim_val_abs is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] > -1:
                return S.false

        p2_series_test = order.expr.match((1 / sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] < 1:
                return S.false

        ### ----------- root test ---------------- ###
        lim = Limit(abs(sequence_term)**(1 / sym), sym, S.Infinity)
        lim_evaluated = lim.doit()
        if lim_evaluated.is_number:
            if lim_evaluated < 1:
                return S.true
            if lim_evaluated > 1:
                return S.false

        ### ------------- alternating series test ----------- ###
        dict_val = sequence_term.match((-1)**(sym + p) * q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true

        ### ------------- comparison test ------------- ###
        # (1/log(n)**p) comparison
        log_test = order.expr.match(1 / (log(sym)**p))
        if log_test is not None:
            return S.false

        # (1/(n*log(n)**p)) comparison
        log_n_test = order.expr.match(1 / (sym * (log(sym))**p))
        if log_n_test is not None:
            if log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n*log(n)*log(log(n))*p)) comparison
        log_log_n_test = order.expr.match(1 / (sym *
                                               (log(sym) * log(log(sym))**p)))
        if log_log_n_test is not None:
            if log_log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n**p*log(n))) comparison
        n_log_test = order.expr.match(1 / (sym**p * log(sym)))
        if n_log_test is not None:
            if n_log_test[p] > 1:
                return S.true
            return S.false

        ### ------------- integral test -------------- ###
        if is_decreasing(sequence_term, interval):
            integral_val = Integral(sequence_term,
                                    (sym, lower_limit, upper_limit))
            try:
                integral_val_evaluated = integral_val.doit()
                if integral_val_evaluated.is_number:
                    return S(integral_val_evaluated.is_finite)
            except NotImplementedError:
                pass

        ### -------------- Dirichlet tests -------------- ###
        if order.expr.is_Mul:
            a_n, b_n = order.expr.args[0], order.expr.args[1]
            m = Dummy('m', integer=True)

            def _dirichlet_test(g_n):
                try:
                    ing_val = limit(
                        Sum(g_n, (sym, interval.inf, m)).doit(), m, S.Infinity)
                    if ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            if is_decreasing(a_n, interval):
                dirich1 = _dirichlet_test(b_n)
                if dirich1 is not None:
                    return dirich1

            if is_decreasing(b_n, interval):
                dirich2 = _dirichlet_test(a_n)
                if dirich2 is not None:
                    return dirich2

        raise NotImplementedError(
            "The algorithm to find the Sum convergence of %s "
            "is not yet implemented" % (sequence_term))
Esempio n. 16
0
def test_doit2():
    f = Integral(2 * x, x)
    l = Limit(f, x, oo)
    # limit() breaks on the contained Integral.
    assert l.doit(deep=False) == l
Esempio n. 17
0
    def is_convergent(self):
        """
        Convergence tests are used for checking the convergence of
        a series. There are various tests employed to check the convergence,
        returns true if convergent and false if divergent and NotImplementedError
        if can not be checked. Like divergence test, root test, integral test,
        alternating series test, comparison tests, Dirichlet tests.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import Interval, factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolute_convergent()
        """
        from sympy import Interval, Integral, Limit, log, symbols, Ge, Gt, simplify
        p, q = symbols('p q', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError("convergence checking for more that one symbol \
                                        containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func_cond in sequence_term.args:
                if func_cond[1].func is Ge or func_cond[1].func is Gt or func_cond[1] == True:
                    return Sum(func_cond[0], (sym, lower_limit, upper_limit)).is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit(abs(sequence_term), sym, upper_limit)
            if lim_val.is_number and lim_val != S.Zero:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] > -1:
                return S.false

        p2_series_test = order.expr.match((1/sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] < 1:
                return S.false

        ### ----------- root test ---------------- ###
        lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
        lim_evaluated = lim.doit()
        if lim_evaluated.is_number:
            if lim_evaluated < 1:
                return S.true
            if lim_evaluated > 1:
                return S.false

        ### ------------- alternating series test ----------- ###
        d = symbols('d', cls=Dummy)
        dict_val = sequence_term.match((-1)**(sym + p)*q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true

        ### ------------- comparison test ------------- ###
        # (1/log(n)**p) comparison
        log_test = order.expr.match(1/(log(sym)**p))
        if log_test is not None:
            return S.false

        # (1/(n*log(n)**p)) comparison
        log_n_test = order.expr.match(1/(sym*(log(sym))**p))
        if log_n_test is not None:
            if log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n*log(n)*log(log(n))*p)) comparison
        log_log_n_test = order.expr.match(1/(sym*(log(sym)*log(log(sym))**p)))
        if log_log_n_test is not None:
            if log_log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n**p*log(n))) comparison
        n_log_test = order.expr.match(1/(sym**p*log(sym)))
        if n_log_test is not None:
            if n_log_test[p] > 1:
                return S.true
            return S.false

        ### ------------- integral test -------------- ###
        if is_decreasing(sequence_term, interval):
            integral_val = Integral(sequence_term, (sym, lower_limit, upper_limit))
            try:
                integral_val_evaluated = integral_val.doit()
                if integral_val_evaluated.is_number:
                    return S(integral_val_evaluated.is_finite)
            except NotImplementedError:
                pass

        ### -------------- Dirichlet tests -------------- ###
        if order.expr.is_Mul:
            a_n, b_n = order.expr.args[0], order.expr.args[1]
            m = Dummy('m', integer=True)

            def _dirichlet_test(g_n):
                try:
                    ing_val = limit(Sum(g_n, (sym, interval.inf, m)).doit(), m, S.Infinity)
                    if ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            if is_decreasing(a_n, interval):
                dirich1 = _dirichlet_test(b_n)
                if dirich1 is not None:
                    return dirich1

            if is_decreasing(b_n, interval):
                dirich2 = _dirichlet_test(a_n)
                if dirich2 is not None:
                    return dirich2

        raise NotImplementedError("The algorithm to find the convergence of %s "
                                    "is not yet implemented" % (sequence_term))