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))
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
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
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
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)
def test_upretty_ceiling(): assert upretty(ceiling(x)) == u'⌈x⌉' u = upretty( ceiling(1 / (y - ceiling(x))) ) s = \ u"""\ ⎡ 1 ⎤ ⎢───────⎥ ⎢y - ⌈x⌉⎥\ """ assert u == s
def test_evalf_integer_parts(): a = floor(log(8)/log(2) - exp(-1000), evaluate=False) b = floor(log(8)/log(2), evaluate=False) assert a.evalf() == 3 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(70)) == \ long(11188719610782480504630258070757734324011354208865721592720336800) assert int(ceiling(factorial(50)/E, evaluate=False).evalf(70)) == \ long(11188719610782480504630258070757734324011354208865721592720336801) 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) assert ceiling(x).evalf(subs={x: 3}) == 3 assert ceiling(x).evalf(subs={x: 3*I}) == 3*I assert ceiling(x).evalf(subs={x: 2 + 3*I}) == 2 + 3*I assert ceiling(x).evalf(subs={x: 3.}) == 3 assert ceiling(x).evalf(subs={x: 3.*I}) == 3*I assert ceiling(x).evalf(subs={x: 2. + 3*I}) == 2 + 3*I assert float((floor(1.5, evaluate=False)+1/9).evalf()) == 1 + 1/9 assert float((floor(0.5, evaluate=False)+20).evalf()) == 20
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)
def eval(cls, ar, period): # Our strategy is to evaluate the argument on the riemann surface of the # logarithm, and then reduce. # NOTE evidently this means it is a rather bad idea to use this with # period != 2*pi and non-polar numbers. from sympy import ceiling, oo, atan2, atan, polar_lift, pi, Mul if not period.is_positive: return None if period == oo and isinstance(ar, principal_branch): return periodic_argument(*ar.args) if ar.func is polar_lift and period >= 2*pi: return periodic_argument(ar.args[0], period) if ar.is_Mul: newargs = [x for x in ar.args if not x.is_positive] if len(newargs) != len(ar.args): return periodic_argument(Mul(*newargs), period) unbranched = cls._getunbranched(ar) if unbranched is None: return None if unbranched.has(periodic_argument, atan2, arg, atan): return None if period == oo: return unbranched if period != oo: n = ceiling(unbranched/period - S(1)/2)*period if not n.has(ceiling): return unbranched - n
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_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})
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)
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)
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)$"
def test_ceiling_requires_robust_assumptions(): assert limit(ceiling(sin(x)), x, 0, "+") == 1 assert limit(ceiling(sin(x)), x, 0, "-") == 0 assert limit(ceiling(cos(x)), x, 0, "+") == 1 assert limit(ceiling(cos(x)), x, 0, "-") == 1 assert limit(ceiling(5 + sin(x)), x, 0, "+") == 6 assert limit(ceiling(5 + sin(x)), x, 0, "-") == 5 assert limit(ceiling(5 + cos(x)), x, 0, "+") == 6 assert limit(ceiling(5 + cos(x)), x, 0, "-") == 6
def test_ceiling(): assert ceiling(x).series(x) == 1 assert ceiling(-x).series(x) == 0 assert ceiling(sin(x)).series(x) == 1 assert ceiling(sin(-x)).series(x) == 0 assert ceiling(1 - cos(x)).series(x) == 1 assert ceiling(1 - cos(-x)).series(x) == 1 assert ceiling(x).series(x, 2) == 3 assert ceiling(-x).series(x, 2) == -2
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='+')
def _eval_nseries(self, x, n, logx): if len(self.args) == 1: from sympy import Order, ceiling, expand_multinomial arg = self.args[0].nseries(x, n=n, logx=logx) lt = arg.compute_leading_term(x, logx=logx) lte = 1 if lt.is_Pow: lte = lt.exp if ceiling(n/lte) >= 1: s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/ factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))]) s = expand_multinomial(s) else: s = S.Zero return s + Order(x**n, x) return super(LambertW, self)._eval_nseries(x, n, logx)
def test_variable_single_arg_func(): assert_equal( "\\floor(\\variable{x})", floor(Symbol('x' + hashlib.md5('x'.encode()).hexdigest(), real=True))) assert_equal( "\\ceil(\\variable{x})", ceiling(Symbol('x' + hashlib.md5('x'.encode()).hexdigest(), real=True)))
def test_ceiling(): x = Symbol('x') assert ceiling(x).series(x) == 1 assert ceiling(-x).series(x) == 0 assert ceiling(sin(x)).series(x) == 1 assert ceiling(sin(-x)).series(x) == 0 assert ceiling(1 - cos(x)).series(x) == 1 assert ceiling(1 - cos(-x)).series(x) == 1 assert ceiling(x).series(x, 2) == 3 assert ceiling(-x).series(x, 2) == -2
def test_ceiling(): x = Symbol('x') assert ceiling(x).series(x) == 1 assert ceiling(-x).series(x) == 0 assert ceiling(sin(x)).series(x) == 1 assert ceiling(sin(-x)).series(x) == 0 assert ceiling(1-cos(x)).series(x) == 1 assert ceiling(1-cos(-x)).series(x) == 1 assert ceiling(x).series(x, 2) == 3 assert ceiling(-x).series(x, 2) == -2
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, lambda: 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(70)) == \ long(11188719610782480504630258070757734324011354208865721592720336800) assert int(ceiling(factorial(50)/E, evaluate=False).evalf(70)) == \ long(11188719610782480504630258070757734324011354208865721592720336801) 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)
def test_own_module(): f = lambdify(x, sin(x), math) assert f(0) == 0.0 f = lambdify(x, sympy.ceiling(x), math) try: f(4.5) assert False except NameError: pass
def solve(a, b): s = sympy.fraction(sympy.Rational(a,b)) if sympy.log(s[1],2) % 1 != 0: return 'impossible' y = sympy.ceiling(sympy.log(s[1]/s[0],2)) if y > 40: return 'impossible' else: return str(y)
def test_own_module(): f = lambdify(x, sin(x), math) assert f(0)==0.0 f = lambdify(x, sympy.ceiling(x), math) try: f(4.5) assert False except NameError: pass
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 })
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(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(Abs(x)) == r"\lvert{x}\rvert" assert latex(re(x)) == r"\Re{x}" assert latex(re(x + y)) == r"\Re {\left (x + y \right )}" 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 )}'
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 _eval_evalf(self, prec): from sympy import ceiling, oo z, period = self.args if period == oo: unbranched = periodic_argument._getunbranched(z) if unbranched is None: return self return unbranched._eval_evalf(prec) ub = periodic_argument(z, oo)._eval_evalf(prec) return (ub - ceiling(ub/period - S(1)/2)*period)._eval_evalf(prec)
def size_exact(self): """ Returns the number of elements in each dimension. """ return [ ts * sp.ceiling( ((iMax.expr if isinstance(iMax, symbolic.SymExpr) else iMax) + 1 - (iMin.expr if isinstance(iMin, symbolic.SymExpr) else iMin)) / (step.expr if isinstance(step, symbolic.SymExpr) else step)) for (iMin, iMax, step), ts in zip(self.ranges, self.tile_sizes) ]
def zero_upper_bound_of_positive_poly(poly): poly = Poly(poly.expand()) cs = poly.all_coeffs() cs0 = abs(cs[0]) assert cs[0] == LC(poly) height = max(map(abs, cs)) upper = ceiling(two * height / cs0) upper = int(upper) assert upper >= 2 return upper
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(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(Abs(x)) == r"\lvert{x}\rvert" assert latex(re(x)) == r"\Re{x}" assert latex(re(x+y)) == r"\Re {\left (x + y \right )}" 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 )}'
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, Abs 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)), ] result = codegen(name_expr, "C", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' "double test_fabs(double x) {\n return fabs(x);\n}\n" "double test_acos(double x) {\n return acos(x);\n}\n" "double test_asin(double x) {\n return asin(x);\n}\n" "double test_atan(double x) {\n return atan(x);\n}\n" "double test_ceil(double x) {\n return ceil(x);\n}\n" "double test_cos(double x) {\n return cos(x);\n}\n" "double test_cosh(double x) {\n return cosh(x);\n}\n" "double test_floor(double x) {\n return floor(x);\n}\n" "double test_log(double x) {\n return log(x);\n}\n" "double test_ln(double x) {\n return log(x);\n}\n" "double test_sin(double x) {\n return sin(x);\n}\n" "double test_sinh(double x) {\n return sinh(x);\n}\n" "double test_sqrt(double x) {\n return sqrt(x);\n}\n" "double test_tan(double x) {\n return tan(x);\n}\n" "double test_tanh(double x) {\n return tanh(x);\n}\n" ) assert result[1][0] == "file.h" assert result[1][1] == ( "#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n" "double test_fabs(double x);\ndouble test_acos(double x);\n" "double test_asin(double x);\ndouble test_atan(double x);\n" "double test_ceil(double x);\ndouble test_cos(double x);\n" "double test_cosh(double x);\ndouble test_floor(double x);\n" "double test_log(double x);\ndouble test_ln(double x);\n" "double test_sin(double x);\ndouble test_sinh(double x);\n" "double test_sqrt(double x);\ndouble test_tan(double x);\n" "double test_tanh(double x);\n#endif\n" )
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, Abs) 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)), ] result = codegen(name_expr, "C", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' 'double test_fabs(double x) {\n return fabs(x);\n}\n' 'double test_acos(double x) {\n return acos(x);\n}\n' 'double test_asin(double x) {\n return asin(x);\n}\n' 'double test_atan(double x) {\n return atan(x);\n}\n' 'double test_ceil(double x) {\n return ceil(x);\n}\n' 'double test_cos(double x) {\n return cos(x);\n}\n' 'double test_cosh(double x) {\n return cosh(x);\n}\n' 'double test_floor(double x) {\n return floor(x);\n}\n' 'double test_log(double x) {\n return log(x);\n}\n' 'double test_ln(double x) {\n return log(x);\n}\n' 'double test_sin(double x) {\n return sin(x);\n}\n' 'double test_sinh(double x) {\n return sinh(x);\n}\n' 'double test_sqrt(double x) {\n return sqrt(x);\n}\n' 'double test_tan(double x) {\n return tan(x);\n}\n' 'double test_tanh(double x) {\n return tanh(x);\n}\n' ) assert result[1][0] == "file.h" assert result[1][1] == ( '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' 'double test_fabs(double x);\ndouble test_acos(double x);\n' 'double test_asin(double x);\ndouble test_atan(double x);\n' 'double test_ceil(double x);\ndouble test_cos(double x);\n' 'double test_cosh(double x);\ndouble test_floor(double x);\n' 'double test_log(double x);\ndouble test_ln(double x);\n' 'double test_sin(double x);\ndouble test_sinh(double x);\n' 'double test_sqrt(double x);\ndouble test_tan(double x);\n' 'double test_tanh(double x);\n#endif\n' )
def fermat_factor(n): num_digits = int(log(n, 10).evalf() + 1) a = ceiling( sqrt(n).evalf(num_digits) ) counter = 0 while not is_square(a*a - n): a += 1 counter += 1 b = sqrt(a*a - n) return(a+b, a-b, counter)
def round(a, n, places=None): if places is None: places = n multiplier = 10 ** n if a == 0: num = 0 elif a > 0: num = 1.0 * sym.floor(a * multiplier + 0.5) / multiplier else: num = 1.0 * sym.ceiling(a * multiplier - 0.5) / multiplier return f"{num:.{places}f}"
def cost(s=s, tau=tau, x=x, r=r, F=F, beta=beta, theta_r=theta_r): N_r = sym.ceiling(1 / theta_r) return ( F * (1 - r) ** beta * ( s * selective_time(r=r, tau=tau) + (1 - s) * indiscriminate_time(r=r, tau=tau, N_r=N_r) ) )
def run_copper_smith(f, N, h, k): X = s.S(s.ceiling((s.Pow(2, - 1 / 2) * s.Pow(h * k, -1 / (h * k - 1))) * s.Pow(N, (h - 1) / (h * k - 1))) - 1) gen = lll(generate(f, N, h, k, X), s.S(0.75)) final_poly = [gen[0][i] / s.Pow(X, i) for i in range(len(gen[0]))][::-1] roots = s.roots(final_poly) for r in roots: print(r) return roots
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, Abs) 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)), ] result = codegen(name_expr, "C89", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' 'double test_fabs(double x) {\n double test_fabs_result;\n test_fabs_result = fabs(x);\n return test_fabs_result;\n}\n' 'double test_acos(double x) {\n double test_acos_result;\n test_acos_result = acos(x);\n return test_acos_result;\n}\n' 'double test_asin(double x) {\n double test_asin_result;\n test_asin_result = asin(x);\n return test_asin_result;\n}\n' 'double test_atan(double x) {\n double test_atan_result;\n test_atan_result = atan(x);\n return test_atan_result;\n}\n' 'double test_ceil(double x) {\n double test_ceil_result;\n test_ceil_result = ceil(x);\n return test_ceil_result;\n}\n' 'double test_cos(double x) {\n double test_cos_result;\n test_cos_result = cos(x);\n return test_cos_result;\n}\n' 'double test_cosh(double x) {\n double test_cosh_result;\n test_cosh_result = cosh(x);\n return test_cosh_result;\n}\n' 'double test_floor(double x) {\n double test_floor_result;\n test_floor_result = floor(x);\n return test_floor_result;\n}\n' 'double test_log(double x) {\n double test_log_result;\n test_log_result = log(x);\n return test_log_result;\n}\n' 'double test_ln(double x) {\n double test_ln_result;\n test_ln_result = log(x);\n return test_ln_result;\n}\n' 'double test_sin(double x) {\n double test_sin_result;\n test_sin_result = sin(x);\n return test_sin_result;\n}\n' 'double test_sinh(double x) {\n double test_sinh_result;\n test_sinh_result = sinh(x);\n return test_sinh_result;\n}\n' 'double test_sqrt(double x) {\n double test_sqrt_result;\n test_sqrt_result = sqrt(x);\n return test_sqrt_result;\n}\n' 'double test_tan(double x) {\n double test_tan_result;\n test_tan_result = tan(x);\n return test_tan_result;\n}\n' 'double test_tanh(double x) {\n double test_tanh_result;\n test_tanh_result = tanh(x);\n return test_tanh_result;\n}\n' ) assert result[1][0] == "file.h" assert result[1][1] == ( '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' 'double test_fabs(double x);\ndouble test_acos(double x);\n' 'double test_asin(double x);\ndouble test_atan(double x);\n' 'double test_ceil(double x);\ndouble test_cos(double x);\n' 'double test_cosh(double x);\ndouble test_floor(double x);\n' 'double test_log(double x);\ndouble test_ln(double x);\n' 'double test_sin(double x);\ndouble test_sinh(double x);\n' 'double test_sqrt(double x);\ndouble test_tan(double x);\n' 'double test_tanh(double x);\n#endif\n' )
def test_utility(self): selective = self.H * (1 - self.r)**(1 - self.alpha) - self.F * ( self.r + self.tau * (1 - self.r)) * (1 - self.r)**(self.beta - 1) N_r = sym.ceiling(1 / self.theta_r) indiscriminate = self.H * (self.theta_r * self.r + 1 - self.r) * ( self.theta_r * self.r + 1 - self.r)**-self.alpha - self.F * ( 1 - self.r**N_r) * self.tau * (1 - self.r)**(self.beta - 1) - self.Gamma self.assertEqual((tools.utility(s=1, x=1) - selective).simplify(), 0) self.assertEqual((tools.utility(s=0, x=0) - indiscriminate).simplify(), 0)
def test_cost(self): selective_cost = (self.F * (1 - self.r)**self.beta * tools.selective_time(r=self.r, tau=self.tau)) N_r = sym.ceiling(1 / self.theta_r) indiscriminate_cost = ( self.F * (1 - self.r)**self.beta * tools.indiscriminate_time(r=self.r, tau=self.tau, N_r=N_r)) self.assertEqual(selective_cost.simplify(), tools.cost(s=1, tau=self.tau).simplify()) self.assertEqual(indiscriminate_cost.simplify(), tools.cost(s=0, tau=self.tau).simplify())
def _raw_next(self, search_interval, context, backed_off): """Internal version of the next token method.""" tokens = tuple(self._iter_matching_tokens(context, backed_off)) # Find correct scaled interval full_count = tokens[-1].b + tokens[-1].l base = sympy.floor(search_interval.b * full_count) end = sympy.ceiling( (search_interval.b + search_interval.l) * full_count) length = end - base def interval_bs(tokens, base, end): """ Find using binary search a token whose counts are a superinterval of [base, end]. """ imin = 0 imax = len(tokens) - 1 while imin <= imax: imid = round((imin + imax) / 2) if (tokens[imid].b <= base and tokens[imid].b + tokens[imid].l >= base + length): return imid elif tokens[imid].b + tokens[imid].l <= base: imin = imid + 1 else: imax = imid - 1 i = interval_bs(tokens, base, end) if i is None: # No token can be found return None else: # We have found a token -- standard or back-off token = tokens[i] token_interval = create_interval(token.b, token.l, full_count) scaled_search_interval = find_ratio(search_interval, token_interval) if token.token == self.backoff: return self._raw_next(scaled_search_interval, context[1:], context[0]) else: return NextSymbolSearchResult(token.token, scaled_search_interval)
class ScalableFlow(Modello): """ Something that has input and output, which can be scaled and has associated costs. Input and output are assumed to be something like frequency (Hz) >>> sde = ScalableFlow("flow", fulfilment=2, scale=1, unit_output=1) >>> sde.fulfilment, sde.scale, sde.unit_output (2, 1, 1) >>> sde.input, sde.output (1/2, 1) >>> sde.unit_cost, sde.cost (_flow_unit_cost, _flow_unit_cost) """ # latency calculations could also be included input = InstanceDummy("input", positive=True, rational=True) unit_output = InstanceDummy("unit_output", positive=True, rational=True) unit_cost = InstanceDummy("unit_cost", positive=True, rational=True) scale = InstanceDummy("scale", positive=True, rational=True) cost = unit_cost * ceiling(scale) output = unit_output * scale fulfilment = output / input utilization = output / (ceiling(scale) * unit_output)
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)
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 raises(PrecisionExhausted, "b.evalf()") raises(PrecisionExhausted, "b.evalf(maxn=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)
def acquire(this_much): required = defaultdict(int, {Symbol('FUEL'): this_much}) while True: for symbol, amount in required.items(): if amount > 0 and symbol != ORE: break else: break coef, equation = equations[symbol] required[symbol] -= coef * (base_mats := ceiling(amount / coef)) for symbol in equation.free_symbols: required[symbol] += equation.coeff(symbol) * base_mats return required[ORE]
def fermat_factor(n): # Optimización de la num_digits = int(log(n, 10).evalf() + 1) a = ceiling( sqrt(n).evalf(num_digits) ) counter = 0 while not is_square(a*a - n): a += 1 counter += 1 if a > n: return (0, 0, 0) b = sqrt(a*a - n) return(a+b, a-b, counter + 1)
def _infer_Range(self, node): vi = self.known_vi_[node.output[0]] input_data = self._get_int_values(node) if all([i is not None for i in input_data]): start = as_scalar(input_data[0]) limit = as_scalar(input_data[1]) delta = as_scalar(input_data[2]) new_shape = [sympy.Max(sympy.ceiling((limit - start) / delta), 0)] else: new_dim = self._new_symbolic_dim_from_output(node) new_shape = [self.symbolic_dims_[new_dim]] 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_shape)))
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, ) 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.startswith("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)
def get_conv_padding(in_length, out_length, kernel_size=1, stride=1, dilation=1): padding = sympy.symbols("p") # TODO write the link to equation numerator = in_length + 2 * padding - dilation * (kernel_size - 1) - 1 right_side = (numerator / stride) + 1 equation = out_length - right_side # choose the smallest solution padding = sympy.solve(equation)[0] padding = sympy.ceiling(padding) padding = int(padding) return padding
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]
def duration(self) -> ExpressionScalar: step_size = self._loop_range.step.sympified_expression loop_index = sympy.symbols(self._loop_index) sum_index = sympy.symbols(self._loop_index) # replace loop_index with sum_index dependable expression body_duration = self.body.duration.sympified_expression.subs({loop_index: self._loop_range.start.sympified_expression + sum_index*step_size}) # number of sum contributions step_count = sympy.ceiling((self._loop_range.stop.sympified_expression-self._loop_range.start.sympified_expression) / step_size) sum_start = 0 sum_stop = sum_start + (sympy.functions.Max(step_count, 1) - 1) # expression used if step_count >= 0 finite_duration_expression = sympy.Sum(body_duration, (sum_index, sum_start, sum_stop)) duration_expression = sympy.Piecewise((0, step_count <= 0), (finite_duration_expression, True)) return ExpressionScalar(duration_expression)
def denpendency_plots_from_keys_in_compartments(self, fig): # Automatically produce denpendency plots from keys in compartments # 1st get all component keys target_keys_set = set() for m in self: for el in m.get_component_keys(): if el != "state_vector_derivative": target_keys_set.add(el) target_keys = list(target_keys_set) nr_hist = len(target_keys) fig.set_figheight(fig.get_figwidth() / 8 * nr_hist) # 2nd iterate over them for target_key in target_keys: # 3rd check wich models actually provide the target_key sublist = ModelList([m for m in self if m.has_key(target_key)]) # Plot! count = target_keys.index(target_key) + 1 nr_columns = 2 nr_rows = ceiling(nr_hist / nr_columns) ax = fig.add_subplot(nr_rows, nr_columns, count) sublist.plot_model_key_dependencies_scatter_plot(target_key, ax)
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)'
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)'
def _eval_nseries(self, x, n, logx): # NOTE! This function is an important part of the gruntz algorithm # for computing limits. It has to return a generalized power # series with coefficients in C(log, log(x)). In more detail: # It has to return an expression # c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms) # where e_i are numbers (not necessarily integers) and c_i are # expressions involving only numbers, the log function, and log(x). from sympy import powsimp, collect, exp, log, O, ceiling b, e = self.args if e.is_Integer: if e > 0: # positive integer powers are easy to expand, e.g.: # sin(x)**4 = (x-x**3/3+...)**4 = ... return expand_multinomial(self.func(b._eval_nseries(x, n=n, logx=logx), e), deep=False) elif e is S.NegativeOne: # this is also easy to expand using the formula: # 1/(1 + x) = 1 - x + x**2 - x**3 ... # so we need to rewrite base to the form "1+x" nuse = n cf = 1 try: ord = b.as_leading_term(x) cf = C.Order(ord, x).getn() if cf and cf.is_Number: nuse = n + 2*ceiling(cf) else: cf = 1 except NotImplementedError: pass b_orig, prefactor = b, O(1, x) while prefactor.is_Order: nuse += 1 b = b_orig._eval_nseries(x, n=nuse, logx=logx) prefactor = b.as_leading_term(x) # express "rest" as: rest = 1 + k*x**l + ... + O(x**n) rest = expand_mul((b - prefactor)/prefactor) if rest.is_Order: return 1/prefactor + rest/prefactor + O(x**n, x) k, l = rest.leadterm(x) if l.is_Rational and l > 0: pass elif l.is_number and l > 0: l = l.evalf() elif l == 0: k = k.simplify() if k == 0: # if prefactor == w**4 + x**2*w**4 + 2*x*w**4, we need to # factor the w**4 out using collect: return 1/collect(prefactor, x) else: raise NotImplementedError() else: raise NotImplementedError() if cf < 0: cf = S.One/abs(cf) try: dn = C.Order(1/prefactor, x).getn() if dn and dn < 0: pass else: dn = 0 except NotImplementedError: dn = 0 terms = [1/prefactor] for m in xrange(1, ceiling((n - dn)/l*cf)): new_term = terms[-1]*(-rest) if new_term.is_Pow: new_term = new_term._eval_expand_multinomial( deep=False) else: new_term = expand_mul(new_term, deep=False) terms.append(new_term) terms.append(O(x**n, x)) return powsimp(Add(*terms), deep=True, combine='exp') else: # negative powers are rewritten to the cases above, for # example: # sin(x)**(-4) = 1/( sin(x)**4) = ... # and expand the denominator: nuse, denominator = n, O(1, x) while denominator.is_Order: denominator = (b**(-e))._eval_nseries(x, n=nuse, logx=logx) nuse += 1 if 1/denominator == self: return self # now we have a type 1/f(x), that we know how to expand return (1/denominator)._eval_nseries(x, n=n, logx=logx) if e.has(Symbol): return exp(e*log(b))._eval_nseries(x, n=n, logx=logx) # see if the base is as simple as possible bx = b while bx.is_Pow and bx.exp.is_Rational: bx = bx.base if bx == x: return self # work for b(x)**e where e is not an Integer and does not contain x # and hopefully has no other symbols def e2int(e): """return the integer value (if possible) of e and a flag indicating whether it is bounded or not.""" n = e.limit(x, 0) unbounded = n.is_unbounded if not unbounded: # XXX was int or floor intended? int used to behave like floor # so int(-Rational(1, 2)) returned -1 rather than int's 0 try: n = int(n) except TypeError: #well, the n is something more complicated (like 1+log(2)) try: n = int(n.evalf()) + 1 # XXX why is 1 being added? except TypeError: pass # hope that base allows this to be resolved n = _sympify(n) return n, unbounded order = O(x**n, x) ei, unbounded = e2int(e) b0 = b.limit(x, 0) if unbounded and (b0 is S.One or b0.has(Symbol)): # XXX what order if b0 is S.One: resid = (b - 1) if resid.is_positive: return S.Infinity elif resid.is_negative: return S.Zero raise ValueError('cannot determine sign of %s' % resid) return b0**ei if (b0 is S.Zero or b0.is_unbounded): if unbounded is not False: return b0**e # XXX what order if not ei.is_number: # if not, how will we proceed? raise ValueError( 'expecting numerical exponent but got %s' % ei) nuse = n - ei if e.is_real and e.is_positive: lt = b.as_leading_term(x) # Try to correct nuse (= m) guess from: # (lt + rest + O(x**m))**e = # lt**e*(1 + rest/lt + O(x**m)/lt)**e = # lt**e + ... + O(x**m)*lt**(e - 1) = ... + O(x**n) try: cf = C.Order(lt, x).getn() nuse = ceiling(n - cf*(e - 1)) except NotImplementedError: pass bs = b._eval_nseries(x, n=nuse, logx=logx) terms = bs.removeO() if terms.is_Add: bs = terms lt = terms.as_leading_term(x) # bs -> lt + rest -> lt*(1 + (bs/lt - 1)) return ((self.func(lt, e) * self.func((bs/lt).expand(), e).nseries( x, n=nuse, logx=logx)).expand() + order) if bs.is_Add: from sympy import O # So, bs + O() == terms c = Dummy('c') res = [] for arg in bs.args: if arg.is_Order: arg = c*arg.expr res.append(arg) bs = Add(*res) rv = (bs**e).series(x).subs(c, O(1, x)) rv += order return rv rv = bs**e if terms != bs: rv += order return rv # either b0 is bounded but neither 1 nor 0 or e is unbounded # b -> b0 + (b-b0) -> b0 * (1 + (b/b0-1)) o2 = order*(b0**-e) z = (b/b0 - 1) o = O(z, x) #r = self._compute_oseries3(z, o2, self.taylor_term) if o is S.Zero or o2 is S.Zero: unbounded = True else: if o.expr.is_number: e2 = log(o2.expr*x)/log(x) else: e2 = log(o2.expr)/log(o.expr) n, unbounded = e2int(e2) if unbounded: # requested accuracy gives infinite series, # order is probably non-polynomial e.g. O(exp(-1/x), x). r = 1 + z else: l = [] g = None for i in xrange(n + 2): g = self._taylor_term(i, z, g) g = g.nseries(x, n=n, logx=logx) l.append(g) r = Add(*l) return expand_mul(r*b0**e) + order