def test_issue_14456(): raises(NotImplementedError, lambda: Limit(exp(x), x, zoo).doit()) raises(NotImplementedError, lambda: Limit(x**2 / (x + 1), x, zoo).doit())
def test_doit(): f = Integral(2 * x, x) l = Limit(f, x, oo) assert l.doit() is oo
def test_Limit_dir(): raises(TypeError, lambda: Limit(x, x, 0, dir=0)) raises(ValueError, lambda: Limit(x, x, 0, dir='0'))
def test_issue_18442(): assert limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') == Limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-')
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, r = symbols('p q r', 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)) ### --------- 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 ### ------------- comparison test ------------- ### # 1/(n**p*log(n)**q*log(log(n))**r) comparison n_log_test = order.expr.match(1/(sym**p*log(sym)**q*log(log(sym))**r)) if n_log_test is not None: if (n_log_test[p] > 1 or (n_log_test[p] == 1 and n_log_test[q] > 1) or (n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)): return S.true 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 ### ----------- ratio test ---------------- ### next_sequence_term = sequence_term.xreplace({sym: sym + 1}) ratio = combsimp(powsimp(next_sequence_term/sequence_term)) try: 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 except NotImplementedError: pass ### ----------- root test ---------------- ### lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity) try: lim_evaluated = lim.doit() if lim_evaluated.is_number: if lim_evaluated < 1: return S.true if lim_evaluated > 1: return S.false except NotImplementedError: pass ### ------------- 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 ### ------------- integral test -------------- ### check_interval = None 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 (check_interval is not None and (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))
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
("\\left\\{x + y\\right\\} z", _Mul(_Add(x, y), z)), ("1+1", Add(1, 1, evaluate=False)), ("0+1", Add(0, 1, evaluate=False)), ("1*2", Mul(1, 2, evaluate=False)), ("0*1", Mul(0, 1, evaluate=False)), ("\\sin \\theta", sin(theta)), ("\\sin(\\theta)", sin(theta)), ("\\sin^{-1} a", asin(a)), ("\\sin a \\cos b", _Mul(sin(a), cos(b))), ("\\sin \\cos \\theta", sin(cos(theta))), ("\\sin(\\cos \\theta)", sin(cos(theta))), ("\\frac{a}{b}", a / b), ("\\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))), ("\\frac{7}{3}", _Mul(7, _Pow(3, -1))), ("(\\csc x)(\\sec y)", csc(x) * sec(y)), ("\\lim_{x \\to 3} a", Limit(a, x, 3)), ("\\lim_{x \\rightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\Rightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\longrightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\Longrightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\to 3^{+}} a", Limit(a, x, 3, dir='+')), ("\\lim_{x \\to 3^{-}} a", Limit(a, x, 3, dir='-')), ("\\infty", oo), ("\\lim_{x \\to \\infty} \\frac{1}{x}", Limit(_Pow(x, -1), x, oo)), ("\\frac{d}{dx} x", Derivative(x, x)), ("\\frac{d}{dt} x", Derivative(x, t)), ("f(x)", f(x)), ("f(x, y)", f(x, y)), ("f(x, y, z)", f(x, y, z)), ("\\frac{d f(x)}{dx}", Derivative(f(x), x)), ("\\frac{d\\theta(x)}{dx}", Derivative(Function('theta')(x), x)),
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))
def test_basic1(): assert limit(x, x, oo) is oo assert limit(x, x, -oo) is -oo assert limit(-x, x, oo) is -oo assert limit(x**2, x, -oo) is oo assert limit(-x**2, x, oo) is -oo assert limit(x * log(x), x, 0, dir="+") == 0 assert limit(1 / x, x, oo) == 0 assert limit(exp(x), x, oo) is oo assert limit(-exp(x), x, oo) is -oo assert limit(exp(x) / x, x, oo) is oo assert limit(1 / x - exp(-x), x, oo) == 0 assert limit(x + 1 / x, x, oo) is oo assert limit(x - x**2, x, oo) is -oo assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1 assert limit((1 + x)**oo, x, 0) == Limit((x + 1)**oo, x, 0) assert limit((1 + x)**oo, x, 0, dir='-') == Limit((x + 1)**oo, x, 0, dir='-') assert limit((1 + x + y)**oo, x, 0, dir='-') == Limit((x + y + 1)**oo, x, 0, dir='-') assert limit(y / x / log(x), x, 0) == -oo * sign(y) assert limit(cos(x + y) / x, x, 0) == sign(cos(y)) * oo assert limit(gamma(1 / x + 3), x, oo) == 2 assert limit(S.NaN, x, -oo) is S.NaN assert limit(Order(2) * x, x, S.NaN) is S.NaN assert limit(1 / (x - 1), x, 1, dir="+") is oo assert limit(1 / (x - 1), x, 1, dir="-") is -oo assert limit(1 / (5 - x)**3, x, 5, dir="+") is -oo assert limit(1 / (5 - x)**3, x, 5, dir="-") is oo assert limit(1 / sin(x), x, pi, dir="+") is -oo assert limit(1 / sin(x), x, pi, dir="-") is oo assert limit(1 / cos(x), x, pi / 2, dir="+") is -oo assert limit(1 / cos(x), x, pi / 2, dir="-") is oo assert limit(1 / tan(x**3), x, (2 * pi)**Rational(1, 3), dir="+") is oo assert limit(1 / tan(x**3), x, (2 * pi)**Rational(1, 3), dir="-") is -oo assert limit(1 / cot(x)**3, x, (pi * Rational(3, 2)), dir="+") is -oo assert limit(1 / cot(x)**3, x, (pi * Rational(3, 2)), dir="-") is oo # test bi-directional limits assert limit(sin(x) / x, x, 0, dir="+-") == 1 assert limit(x**2, x, 0, dir="+-") == 0 assert limit(1 / x**2, x, 0, dir="+-") is oo # test failing bi-directional limits assert limit(1 / x, x, 0, dir="+-") is zoo # approaching 0 # from dir="+" assert limit(1 + 1 / x, x, 0) is oo # from dir='-' # Add assert limit(1 + 1 / x, x, 0, dir='-') is -oo # Pow assert limit(x**(-2), x, 0, dir='-') is oo assert limit(x**(-3), x, 0, dir='-') is -oo assert limit(1 / sqrt(x), x, 0, dir='-') == (-oo) * I assert limit(x**2, x, 0, dir='-') == 0 assert limit(sqrt(x), x, 0, dir='-') == 0 assert limit(x**-pi, x, 0, dir='-') == oo * sign((-1)**(-pi)) assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0)
#limit tanımından türevi bulma from sympy import Symbol, Limit t = Symbol('t') 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}) limit = Limit((St1_delta - St1) / delta_t, delta_t, 0).doit() print(St, " fonksiyonunun limiti:", limit)
theta = Symbol('theta') # math.sin(theta) """ Burada hata var. Matematiksel sinüs alamıyor. Çünkü theta matematiksel bir büyüklük değil. """ print(sympy.sin(theta)*sympy.sin(theta)) u = Symbol('u') t = Symbol('t') g = Symbol('g') print(solve(u*sin(theta)-g*t, t)) # We find what is the value of t. / T değerinin ne olduğunu buluruz. 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}) # St'deki t değişkenlerini t1 ile güncelledik. st1_delta = (st.subs({t: t1+delta_t})) f_d = Limit(((st1_delta - st1) / delta_t), delta_t, 0) # St fonksiyonunun türevini bulduk. print(f_d.doit())
def test_pretty_limits(): assert pretty(Limit(x, x, oo)) == ' lim x\nx->oo ' assert pretty(Limit(x**2, x, 0)) == ' 2\nlim x \nx->0 ' assert pretty(Limit(1 / x, x, 0)) == ' 1\nlim -\nx->0x'
#3 t = symbol('t') 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})) Limit(((st1_delta - st1) / delta_t), delta_t, 0) #2 u = symbol('u') t = symbol('t') g = symbol('g') theta = symbol('theta') from sympy import solve, sin solve(u * sin(theta) - g * t, t) #output [u*sin(theta)/g] x = symbol('x') from sympy import Limit, s l = Limit(1 / x, x, S, dir='-') l.doit() #1 from sympy import symbol theta = symbol('theta') import math math.sin(theta)
import sys data = sys.stdin.readline().strip() print(data) a = '0010' print(f'print({a})') pow(2, 5) from sympy import Limit, S, Symbol x = Symbol('x') Limit(1/x, x, S.Infinity).doit() Limit(1/x, x, S.Infinity, dir = '-').doit() arr = [1,2,3] answer = [arr[0]] answer b = (1,2,3) b ########### n, k = map(int, input().split()) cnt = 0 while n != 1: if n % k == 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
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 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(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))
from sympy import Symbol, Limit, S n = Symbol( 'n' ) Limit( ( 1 + 1/n) ** n, n, S.Infinity ).doit() # Compound Interest p = Symbol( 'p', positive = True ) r = Symbol( 'r', positive = True ) t = Symbol( 't', positive = True ) Limit( p * ( 1 + r/n ) ** ( n*t ), n, S.Infinity ).doit()
from sympy import pprint from sympy import Symbol, Limit t = Symbol('t') 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}) print((St1_delta - St1) / delta_t) print("Limiti alınca:") print(Limit((St1_delta - St1) / delta_t, delta_t, 0).doit())
def test_Limit(): assert str(Limit(sin(x) / x, x, y)) == "Limit(sin(x)/x, x, y)" assert str(Limit(1 / x, x, 0)) == "Limit(1/x, x, 0)" assert str(Limit(sin(x) / x, x, y, dir="-")) == "Limit(sin(x)/x, x, y, dir='-')"
def lens_formula(focal_length=None, u=None, v=None): """ This function provides one of the three parameters when two of them are supplied. This is valid only for paraxial rays. Parameters ========== focal_length : sympifiable Focal length of the mirror. u : sympifiable Distance of object from the optical center on the principal axis. v : sympifiable Distance of the image from the optical center on the principal axis. Examples ======== >>> from sympy.physics.optics import lens_formula >>> from sympy.abc import f, u, v >>> lens_formula(focal_length=f, u=u) f*u/(f + u) >>> lens_formula(focal_length=f, v=v) f*v/(f - v) >>> lens_formula(u=u, v=v) u*v/(u - v) """ if focal_length and u and v: raise ValueError("Please provide only two parameters") focal_length = sympify(focal_length) u = sympify(u) v = sympify(v) if u is oo: _u = Symbol('u') if v is oo: _v = Symbol('v') if focal_length is oo: _f = Symbol('f') if focal_length is None: if u is oo and v is oo: return Limit(Limit(_v*_u/(_u - _v), _u, oo), _v, oo).doit() if u is oo: return Limit(v*_u/(_u - v), _u, oo).doit() if v is oo: return Limit(_v*u/(u - _v), _v, oo).doit() return v*u/(u - v) if u is None: if v is oo and focal_length is oo: return Limit(Limit(_v*_f/(_f - _v), _v, oo), _f, oo).doit() if v is oo: return Limit(_v*focal_length/(focal_length - _v), _v, oo).doit() if focal_length is oo: return Limit(v*_f/(_f - v), _f, oo).doit() return v*focal_length/(focal_length - v) if v is None: if u is oo and focal_length is oo: return Limit(Limit(_u*_f/(_u + _f), _u, oo), _f, oo).doit() if u is oo: return Limit(_u*focal_length/(_u + focal_length), _u, oo).doit() if focal_length is oo: return Limit(u*_f/(u + _f), _f, oo).doit() return u*focal_length/(u + focal_length)
def test_issue_17325(): assert Limit(sin(x)/x, x, 0, dir="+-").doit() == 1 assert Limit(x**2, x, 0, dir="+-").doit() == 0 assert Limit(1/x**2, x, 0, dir="+-").doit() is oo assert Limit(1/x, x, 0, dir="+-").doit() is zoo
''' 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)
from sympy import Limit, Symbol, S p = Symbol('p', positive=True) r = Symbol('r', positive=True) t = Symbol('t', positive=True) n = Symbol('n', positive=True) print(Limit(p * (1 + r / n)**(n * t), n, S.Infinity).doit())
# Importa operação Limit (limite) da biblioteca sympy # Importa Symbol - possibilidade de operações com símbolos # Importa função sympy S que transforma texto em algumas constantes padrão # limite x^3 -1 / x-1 com x tendendo a 1. # from sympy import Limit, Symbol, S # Define uma função def calcula_f(x): return (x**3 - 1) / (x - 1) x = Symbol('x') resultado = Limit(calcula_f(x), x, 1).doit() print(resultado)
def test_Limit(): assert Limit(sin(x) / x, x, 0) != 1 assert Limit(sin(x) / x, x, 0).doit() == 1 assert Limit(x, x, 0, dir='+-').args == (x, x, 0, Symbol('+-'))
def test_Limit(): assert Limit(sin(x)/x, x, 0) != 1 assert Limit(sin(x)/x, x, 0).doit() == 1
from sympy import Symbol import math theta=Symbol('theta') u=Symbol('u') t=Symbol('t') g=Symbol('g') theta=Symbol('theta') x=Symbol('x') from sympy import Limit,S l=Limit(1/x,x,S,dir='-') print(l) t=Symbol('t') t1=Symbol('t1') delta_t=Symbol('delta_t') st=5*t**2+2*t+8 st1=st.subs({t:t1}) st1_delta=(st.subs({t:t+delta_t})) f_d=Limit((st1_delta-st1)/delta_t),0) print(f_d)
def test_issue_9205(): x, y, a = symbols('x, y, a') assert Limit(x, x, a).free_symbols == {a} assert Limit(x, x, a, '-').free_symbols == {a} assert Limit(x + y, x + y, a).free_symbols == {a} assert Limit(-x**2 + y, x**2, a).free_symbols == {y, a}
def test_issue_17325(): assert Limit(sin(x) / x, x, 0, dir="+-").doit() == 1 assert Limit(x**2, x, 0, dir="+-").doit() == 0 assert Limit(1 / x**2, x, 0, dir="+-").doit() == oo raises(ValueError, lambda: Limit(1 / x, x, 0, dir="+-").doit())
def test_doit(): f = Integral(2 * x, x) l = Limit(f, x, oo) assert l.doit() == oo
def test_latex_limits(): assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x"
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))
def test_static_cases(self): test_cases = [ # Linear algebra 1 * x, Eq(8 * x, 0), Eq(10 * x, 5), Eq(x - 4 * x, -21), Eq(3 * x, 21), Eq(2 + 5, x), Eq(3 * (x - 4), x), Eq(12, 2 * x), Eq(3 * (x - 4) / x, 1), Eq(12 / x, 2), 0.5 * x + 0.1, Rational(1, 10) + Rational(1, 2) * x, Add(x, 2 * x, -3 * x, evaluate=False), # Trigonometry sin(x), cos(x), tan(x), csc(x), sec(x), cot(x), 1 - sin(x)**2, cos(x)**2, Eq(sin(x)**2, x), Eq(-x, 1 - cos(x)**2 - 2 * x), sin(2 * x), 2 * sin(x) * cos(x), Eq(1 - sin(2 * x), 0), Eq(sin(x)**2, 2 * sin(x) * cos(x) - cos(x)**2), cos(x * y), acos(x), Pow(cos(x), 1, evaluate=False), Pow(cos(x), 0, evaluate=False), # Hyperbolic functions sinh(x), cosh(x), tanh(x), #csch(x), #sech(x), #coth(x), # Exponential E, sqrt(E), E**x, exp(x), exp(ln(x), evaluate=False), # Imaginary/Complex I, 3 + 8 * I, re(x + I * y, evaluate=False), im(x + y * I, evaluate=False), re(1 - I, evaluate=False), im(1 - I, evaluate=False), E**(I * theta), # Infinity oo, Add(oo, oo, evaluate=False), Add(oo, Mul(3, oo, evaluate=False), evaluate=False), -oo, Add(-oo, -oo, evaluate=False), Mul(-2, oo, evaluate=False), Mul(-2, -oo, evaluate=False), Mul(-2, -oo, -5, evaluate=False), # Calculus Limit(x**2, x, theta), # Miscellaneous Abs(x), parse_expr('n!'), parse_expr('n!!'), factorial2(2 * x + y), pi, Pow(0, 0, evaluate=False), ] failed_tests = [] for expr in test_cases: try: s_l_expr = latex(expr) l_expr = process_sympy(s_l_expr) equiv = equivalent(expr, l_expr) e = None except Exception as e: # Parsing failed l_expr = None equiv = False if not equiv: print '%s %s' % (s_l_expr, 'PASSED' if equiv else 'FAILED') failed_tests.append((s_l_expr, l_expr)) print 'sympy: %s\nlatex: %s' % (expr, l_expr) if e is not None: print e print if failed_tests: print len(failed_tests), 'failed test cases' assert len(failed_tests) == 0