def test_m_not_supported(): f = Function('f') name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ("function [out1, out2] = test(x)\n" " % unsupported: Derivative(f(x), x)\n" " % unsupported: zoo\n" " out1 = Derivative(f(x), x);\n" " out2 = zoo;\n" "end\n") assert source == expected
def test_split_symbols_function(): transformations = standard_transformations + \ (split_symbols, implicit_multiplication,) x = Symbol('x') y = Symbol('y') a = Symbol('a') f = Function('f') assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1) assert parse_expr("af(x+1)", transformations=transformations, local_dict={'f':f}) == a*f(x+1)
def test_octave_not_supported(): assert mcode(S.ComplexInfinity) == ( "% Not supported in Octave:\n" "% ComplexInfinity\n" "zoo" ) f = Function('f') assert mcode(f(x).diff(x)) == ( "% Not supported in Octave:\n" "% Derivative\n" "Derivative(f(x), x)" )
def test_sho_R_nl(): omega, r = symbols('omega r') l = symbols('l', integer=True) u = Function('u') # check that it obeys the Schrodinger equation for n in range(5): schreq = (-diff(u(r), r, 2) / 2 + ( (l * (l + 1)) / (2 * r**2) + omega**2 * r**2 / 2 - E_nl(n, l, omega)) * u(r)) result = schreq.subs(u(r), r * R_nl(n, l, omega / 2, r)) assert simplify(result.doit()) == 0
def test_nth_order_linear_euler_eq_homogeneous(): x, t, a, b, c = symbols('x t a b c') y = Function('y') our_hint = "nth_linear_euler_eq_homogeneous" eq = diff(f(t), t, 4) * t**4 - 13 * diff(f(t), t, 2) * t**2 + 36 * f(t) assert our_hint in classify_ode(eq) eq = a * y(t) + b * t * diff(y(t), t) + c * t**2 * diff(y(t), t, 2) assert our_hint in classify_ode(eq) _ode_solver_test(_get_examples_ode_sol_euler_homogeneous())
def test_julia_not_supported(): assert julia_code(S.ComplexInfinity) == ( "# Not supported in Julia:\n" "# ComplexInfinity\n" "zoo" ) f = Function('f') assert julia_code(f(x).diff(x)) == ( "# Not supported in Julia:\n" "# Derivative\n" "Derivative(f(x), x)" )
def test_functional_diffgeom_ch4(): x0, y0, theta0 = symbols('x0, y0, theta0', real=True) x, y, r, theta = symbols('x, y, r, theta', real=True) r0 = symbols('r0', positive=True) f = Function('f') b1 = Function('b1') b2 = Function('b2') p_r = R2_r.point([x0, y0]) p_p = R2_p.point([r0, theta0]) f_field = b1(R2.x, R2.y)*R2.dx + b2(R2.x, R2.y)*R2.dy assert f_field.rcall(R2.e_x).rcall(p_r) == b1(x0, y0) assert f_field.rcall(R2.e_y).rcall(p_r) == b2(x0, y0) s_field_r = f(R2.x, R2.y) df = Differential(s_field_r) assert df(R2.e_x).rcall(p_r).doit() == Derivative(f(x0, y0), x0) assert df(R2.e_y).rcall(p_r).doit() == Derivative(f(x0, y0), y0) s_field_p = f(R2.r, R2.theta) df = Differential(s_field_p) assert trigsimp(df(R2.e_x).rcall(p_p).doit()) == ( cos(theta0)*Derivative(f(r0, theta0), r0) - sin(theta0)*Derivative(f(r0, theta0), theta0)/r0) assert trigsimp(df(R2.e_y).rcall(p_p).doit()) == ( sin(theta0)*Derivative(f(r0, theta0), r0) + cos(theta0)*Derivative(f(r0, theta0), theta0)/r0) assert R2.dx(R2.e_x).rcall(p_r) == 1 assert R2.dx(R2.e_x) == 1 assert R2.dx(R2.e_y).rcall(p_r) == 0 assert R2.dx(R2.e_y) == 0 circ = -R2.y*R2.e_x + R2.x*R2.e_y assert R2.dx(circ).rcall(p_r).doit() == -y0 assert R2.dy(circ).rcall(p_r) == x0 assert R2.dr(circ).rcall(p_r) == 0 assert simplify(R2.dtheta(circ).rcall(p_r)) == 1 assert (circ - R2.e_theta).rcall(s_field_r).rcall(p_r) == 0
def test_ufunc_support(): f = Function('f') g = Function('g') x = IndexedBase('x') y = IndexedBase('y') i, j = Idx('i'), Idx('j') a = symbols('a') assert get_indices(f(x[i])) == ({i}, {}) assert get_indices(f(x[i], y[j])) == ({i, j}, {}) assert get_indices(f(y[i])*g(x[i])) == (set(), {}) assert get_indices(f(a, x[i])) == ({i}, {}) assert get_indices(f(a, y[i], x[j])*g(x[i])) == ({j}, {}) assert get_indices(g(f(x[i]))) == ({i}, {}) assert get_contraction_structure(f(x[i])) == {None: {f(x[i])}} assert get_contraction_structure( f(y[i])*g(x[i])) == {(i,): {f(y[i])*g(x[i])}} assert get_contraction_structure( f(y[i])*g(f(x[i]))) == {(i,): {f(y[i])*g(f(x[i]))}} assert get_contraction_structure( f(x[j], y[i])*g(x[i])) == {(i,): {f(x[j], y[i])*g(x[i])}}
def test_not_supported(): f = Function('f') name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ("fn test(x: f64) -> (f64, f64) {\n" " // unsupported: Derivative(f(x), x)\n" " // unsupported: zoo\n" " let out1 = Derivative(f(x), x);\n" " let out2 = zoo;\n" " (out1, out2)\n" "}\n") assert source == expected
def test_jl_not_supported(): f = Function('f') name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ("function test(x)\n" " # unsupported: Derivative(f(x), x)\n" " # unsupported: zoo\n" " out1 = Derivative(f(x), x)\n" " out2 = zoo\n" " return out1, out2\n" "end\n") assert source == expected
def test_split_symbols_function(): transformations = standard_transformations + ( split_symbols, implicit_multiplication, ) x = Symbol("x") y = Symbol("y") a = Symbol("a") f = Function("f") assert parse_expr("ay(x+1)", transformations=transformations) == a * y * (x + 1) assert parse_expr("af(x+1)", transformations=transformations, local_dict={"f": f}) == a * f(x + 1)
def _eval_derivative(self, s): # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s) i = 0 l = [] for a in self.args: i += 1 da = a.diff(s) if da is S.Zero: continue try: df = self.fdiff(i) except ArgumentIndexError: df = Function.fdiff(self, i) l.append(df * da) return Add(*l)
def _eval_derivative(self, s): # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s) i = 0 l = [] for a in self.args: i += 1 da = a.diff(s) if da.is_zero: continue try: df = self.fdiff(i) except ArgumentIndexError: df = Function.fdiff(self, i) l.append(df * da) return Add(*l)
def test_nth_algebraic(): eqn = Eq(Derivative(f(x), x), Derivative(g(x), x)) sol = Eq(f(x), C1 + g(x)) assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), hint='nth_algebraic'), dsolve(eqn, f(x), hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) eqn = (diff(f(x)) - x)*(diff(f(x)) + x) sol = [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)] assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert set(sol) == set(dsolve(eqn, f(x), hint='nth_algebraic')) assert set(sol) == set(dsolve(eqn, f(x))) eqn = (1 - sin(f(x))) * f(x).diff(x) sol = Eq(f(x), C1) assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) M, m, r, t = symbols('M m r t') phi = Function('phi') eqn = Eq(-M * phi(t).diff(t), Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t)) solns = [Eq(phi(t), C1), Eq(phi(t), C1 + C2*t - M*t**2/(3*m*r**2))] assert checkodesol(eqn, solns[0], order=2, solve_for_func=False)[0] assert checkodesol(eqn, solns[1], order=2, solve_for_func=False)[0] assert set(solns) == set(dsolve(eqn, phi(t), hint='nth_algebraic')) assert set(solns) == set(dsolve(eqn, phi(t))) eqn = f(x) * f(x).diff(x) * f(x).diff(x, x) sol = Eq(f(x), C1 + C2*x) assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) eqn = f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) sol = Eq(f(x), C1 + C2*x) assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) eqn = f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) * (f(x).diff(x) - x) solns = [Eq(f(x), C1 + x**2/2), Eq(f(x), C1 + C2*x)] assert checkodesol(eqn, solns[0], order=2, solve_for_func=False)[0] assert checkodesol(eqn, solns[1], order=2, solve_for_func=False)[0] assert set(solns) == set(dsolve(eqn, f(x), hint='nth_algebraic')) assert set(solns) == set(dsolve(eqn, f(x)))
def _get_examples_ode_sol_almost_linear(): from sympy import Ei A = Symbol('A', positive=True) f = Function('f') d = f(x).diff(x) return { 'hint': "almost_linear", 'func': f(x), 'examples':{ 'almost_lin_01': { 'eq': x**2*f(x)**2*d + f(x)**3 + 1, 'sol': [Eq(f(x), (C1*exp(3/x) - 1)**Rational(1, 3)), Eq(f(x), (-1 - sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2), Eq(f(x), (-1 + sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2)], }, 'almost_lin_02': { 'eq': x*f(x)*d + 2*x*f(x)**2 + 1, 'sol': [Eq(f(x), -sqrt((C1 - 2*Ei(4*x))*exp(-4*x))), Eq(f(x), sqrt((C1 - 2*Ei(4*x))*exp(-4*x)))] }, 'almost_lin_03': { 'eq': x*d + x*f(x) + 1, 'sol': [Eq(f(x), (C1 - Ei(x))*exp(-x))] }, 'almost_lin_04': { 'eq': x*exp(f(x))*d + exp(f(x)) + 3*x, 'sol': [Eq(f(x), log(C1/x - x*Rational(3, 2)))], }, 'almost_lin_05': { 'eq': x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2, 'sol': [Eq(f(x), (C1 + Piecewise( (x, Eq(A + 1, 0)), ((-A*x + A - x - 1)*exp(x)/(A + 1), True)))*exp(-x))], }, } }
def _get_examples_ode_sol_nth_algebraic(): M, m, r, t = symbols('M m r t') phi = Function('phi') # This one needs a substitution f' = g. # 'algeb_12': { # 'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x, # 'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))], # }, return { 'hint': "nth_algebraic", 'func': f(x), 'examples': { 'algeb_01': { 'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) * (f(x).diff(x) - x), 'sol': [Eq(f(x), C1 + x**2 / 2), Eq(f(x), C1 + C2 * x)] }, 'algeb_02': { 'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1), 'sol': [Eq(f(x), C1 + C2 * x)] }, 'algeb_03': { 'eq': f(x) * f(x).diff(x) * f(x).diff(x, x), 'sol': [Eq(f(x), C1 + C2 * x)] }, 'algeb_04': { 'eq': Eq( -M * phi(t).diff(t), Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t, t)), 'sol': [ Eq(phi(t), C1), Eq(phi(t), C1 + C2 * t - M * t**2 / (3 * m * r**2)) ], 'func': phi(t) }, 'algeb_05': { 'eq': (1 - sin(f(x))) * f(x).diff(x), 'sol': [Eq(f(x), C1)], 'XFAIL': ['separable'] #It raised exception. }, 'algeb_06': { 'eq': (diff(f(x)) - x) * (diff(f(x)) + x), 'sol': [Eq(f(x), C1 - x**2 / 2), Eq(f(x), C1 + x**2 / 2)] }, 'algeb_07': { 'eq': Eq(Derivative(f(x), x), Derivative(g(x), x)), 'sol': [Eq(f(x), C1 + g(x))], }, 'algeb_08': { 'eq': f(x).diff(x) - C1, #this example is from issue 15999 'sol': [Eq(f(x), C1 * x + C2)], }, 'algeb_09': { 'eq': f(x) * f(x).diff(x), 'sol': [Eq(f(x), C1)], }, 'algeb_10': { 'eq': (diff(f(x)) - x) * (diff(f(x)) + x), 'sol': [Eq(f(x), C1 - x**2 / 2), Eq(f(x), C1 + x**2 / 2)], }, 'algeb_11': { 'eq': f(x) + f(x) * f(x).diff(x), 'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)], 'XFAIL': [ 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters' ] #nth_linear_constant_coeff_undetermined_coefficients raises exception rest all of them misses a solution. }, 'algeb_12': { 'eq': Derivative(x * f(x), x, x, x), 'sol': [Eq(f(x), (C1 + C2 * x + C3 * x**2) / x)], 'XFAIL': ['nth_algebraic' ] # It passes only when prep=False is set in dsolve. }, 'algeb_13': { 'eq': Eq(Derivative(x * Derivative(f(x), x), x) / x, exp(x)), 'sol': [Eq(f(x), C1 + C2 * log(x) + exp(x) - Ei(x))], 'XFAIL': ['nth_algebraic' ] # It passes only when prep=False is set in dsolve. }, } }
from sympy.core import pi, oo, symbols, Function, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt from sympy.utilities.pytest import raises from sympy.printing.ccode import CCodePrinter from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx # import test from sympy import ccode x, y, z = symbols('x,y,z') g = Function('g') def test_printmethod(): class fabs(Abs): def _ccode(self, printer): return "fabs(%s)" % printer._print(self.args[0]) assert ccode(fabs(x)) == "fabs(x)" def test_ccode_sqrt(): assert ccode(sqrt(x)) == "sqrt(x)" assert ccode(x**0.5) == "sqrt(x)" assert ccode(sqrt(x)) == "sqrt(x)" def test_ccode_Pow(): assert ccode(x**3) == "pow(x, 3)" assert ccode(x**(y**3)) == "pow(x, pow(y, 3))"
def test_maple_derivatives(): f = Function('f') assert maple_code(f(x).diff(x)) == 'diff(f(x), x)' assert maple_code(f(x).diff(x, 2)) == 'diff(f(x), x$2)'
def test_get_indices_Idx(): f = Function("f") i, j = Idx("i"), Idx("j") assert get_indices(f(i) * j) == (set([i, j]), {}) assert get_indices(f(j, i)) == (set([j, i]), {}) assert get_indices(f(i) * i) == (set(), {})
def apart(f, z=None, **args): """Computes partial fraction decomposition of a rational function. Given a rational function 'f', performing only gcd operations over the algebraic closure of the initial field of definition, compute full partial fraction decomposition with fractions having linear denominators. For all other kinds of expressions the input is returned in an unchanged form. Note however, that `apart` function can thread over sums and relational operators. Note that no factorization of the initial denominator of `f` is needed. The final decomposition is formed in terms of a sum of RootSum instances. By default RootSum tries to compute all its roots to simplify itself. This behavior can be however avoided by setting the keyword flag evaluate=False, which will make this function return a formal decomposition. >>> from sympy import apart >>> from sympy.abc import x, y >>> apart(y/(x+2)/(x+1), x) y/(1 + x) - y/(2 + x) >>> apart(1/(1+x**5), x, evaluate=False) RootSum(Lambda(_a, -_a/(5*(x - _a))), x**5 + 1, x, domain='ZZ') References ========== .. [Bronstein93] M. Bronstein, B. Salvy, Full partial fraction decomposition of rational functions, Proceedings ISSAC '93, ACM Press, Kiev, Ukraine, 1993, pp. 157-160. """ f = cancel(f) if z is None: symbols = f.atoms(Symbol) if not symbols: return f if len(symbols) == 1: z = list(symbols)[0] else: raise ValueError("multivariate partial fractions are not supported") P, Q = f.as_numer_denom() if not Q.has(z): return f partial, r = div(P, Q, z) f, q, U = r / Q, Q, [] u = Function('u')(z) a = Dummy('a') q = Poly(q, z) for d, n in q.sqf_list(all=True, include=True): b = d.as_basic() U += [ u.diff(z, n-1) ] h = cancel(f*b**n) / u**n H, subs = [h], [] for j in range(1, n): H += [ H[-1].diff(z) / j ] for j in range(1, n+1): subs += [ (U[j-1], b.diff(z, j) / j) ] for j in range(0, n): P, Q = cancel(H[j]).as_numer_denom() for i in range(0, j+1): P = P.subs(*subs[j-i]) Q = Q.subs(*subs[0]) P = Poly(P, z) Q = Poly(Q, z) G = P.gcd(d) D = d.exquo(G) B, g = Q.half_gcdex(D) b = (P * B.exquo(g)).rem(D) numer = b.as_basic() denom = (z-a)**(n-j) expr = numer.subs(z, a) / denom partial += RootSum(Lambda(a, expr), D, **args) return partial
# sympy/solvers/tests/test_ode.py # from sympy import (Derivative, diff, Eq, exp, log, Rational, sin, symbols, Ei) from sympy.core import Function, Symbol from sympy.solvers.ode import dsolve from sympy.solvers.ode.ode import _remove_redundant_solutions from sympy.solvers.ode.single import (FirstLinear, ODEMatchError, SingleODEProblem, SingleODESolver) from sympy.solvers.ode.subscheck import checkodesol from sympy.testing.pytest import XFAIL, raises x = Symbol('x') f = Function('f') g = Function('g') C1, C2, C3 = symbols('C1:4') def test_SingleODESolver(): # Test that not implemented methods give NotImplementedError # Subclasses should override these methods. problem = SingleODEProblem(f(x).diff(x), f(x), x) solver = SingleODESolver(problem) raises(NotImplementedError, lambda: solver.matches()) raises(NotImplementedError, lambda: solver.get_general_solution()) raises(NotImplementedError, lambda: solver._matches()) raises(NotImplementedError, lambda: solver._get_general_solution()) # This ODE can not be solved by the FirstLinear solver. Here we test that
def test_get_indices_Idx(): f = Function('f') i, j = Idx('i'), Idx('j') assert get_indices(f(i) * j) == (set([i, j]), {}) assert get_indices(f(j, i)) == (set([j, i]), {}) assert get_indices(f(i) * i) == (set(), {})
def test_maple_derivatives(): f = Function("f") assert maple_code(f(x).diff(x)) == "diff(f(x), x)" assert maple_code(f(x).diff(x, 2)) == "diff(f(x), x$2)"
def test_parse_function_issue_3539(): x = Symbol("x") f = Function("f") assert parse_expr("f(x)") == f(x)
def calculate_derivative_y(expr01, x, terminals, np_maps=None): """ Something error for reference: M. Schmidt, H. Lipson, Distilling free-form natural laws from experimental data, Science, 324 (2009), 81–85. Parameters ---------- expr01: Expr sympy expression. x: list of np.ndarray list of xi terminals: list of sympy.Symbol features and constants np_maps: Callable user np.ndarray function Returns ------- pre_dy_all:np.ndarray or float pre-dy dy_all: np.ndarray or float dy """ warnings.filterwarnings("ignore") if not isinstance(expr01, (Expr, NewArray)): return None, None if len(expr01.free_symbols) < 2: return None, None free_symbols = list( expr01.free_symbols)[:4] if len(expr01.free_symbols) > 4 else list( expr01.free_symbols) free_symbols.sort(key=lambda x: x.name) par = list(itertools.combinations(free_symbols, 2)) # free_symbols = [] # no dependence free_symbols = par # all denpendence # free_symbols = [par[0]] # free_symbols = par[-1:] # free_symbols = par[1:] try: pre_dy_all = [] dy_all = [] for pari in par: pari = list(pari) pari.sort(key=lambda x: x.name) i, j = pari subbb = {} subbb1 = { k: Function("{}f".format(k.name))(v) for k, v in free_symbols if k is not i and v is i } subbb2 = { k: Function("{}f".format(k.name))(v) for v, k in free_symbols if k is not i and v is i } subbb.update(subbb1) subbb.update(subbb2) subb_re = dict(zip(subbb.values(), subbb.keys())) fdv1 = diff(expr01.subs(subbb), i, evaluate=True) fdv1 = fdv1.subs(subb_re) subbb = {} subbb3 = { k: Function("{}f".format(k.name))(v) for k, v in free_symbols if k is not j and v is j } subbb4 = { k: Function("{}f".format(k.name))(v) for v, k in free_symbols if k is not j and v is j } subbb.update(subbb3) subbb.update(subbb4) subb_re = dict(zip(subbb.values(), subbb.keys())) fdv2 = diff(expr01.subs(subbb), j, evaluate=True).subs(subb_re) fdv = fdv2 / fdv1 func0 = utilities.lambdify(terminals, fdv, modules=[np_maps, "numpy"]) pre_dy = func0(*x) ff = diff(i, j, evaluate=False) func0 = utilities.lambdify(terminals, ff, modules=[np_maps, "numpy"]) dy = func0(*x) pre_dy_all.append(pre_dy) dy_all.append(dy) pre_dy_all = np.array(pre_dy_all) dy_all = np.array(dy_all) except (ValueError, RuntimeWarning, TypeError): pre_dy_all, dy_all = None, None return pre_dy_all, dy_all
def test_local_dict_symbol_to_fcn(): x = Symbol('x') d = {'foo': Function('bar')} assert parse_expr('foo(x)', local_dict=d) == d['foo'](x) d = {'foo': Symbol('baz')} raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d))
laguerre, assoc_laguerre, jacobi, gegenbauer, chebyshevt, chebyshevu, legendre, assoc_legendre, Li, LambertW, ) from sympy import mathematica_code as mcode x, y, z, w = symbols("x,y,z,w") f = Function("f") def test_Integer(): assert mcode(Integer(67)) == "67" assert mcode(Integer(-1)) == "-1" def test_Rational(): assert mcode(Rational(3, 7)) == "3/7" assert mcode(Rational(18, 9)) == "2" assert mcode(Rational(3, -7)) == "-3/7" assert mcode(Rational(-3, -7)) == "3/7" assert mcode(x + Rational(3, 7)) == "x + 3/7" assert mcode(Rational(3, 7) * x) == "(3/7)*x"
from sympy.integrals import Integral from sympy.concrete import Sum from sympy.functions import (exp, sin, cos, fresnelc, fresnels, conjugate, Max, Min, gamma, polygamma, loggamma, erf, erfi, erfc, erf2, expint, erfinv, erfcinv, Ei, Si, Ci, li, Shi, Chi, uppergamma, beta, subfactorial, erf2inv, factorial, factorial2, catalan, RisingFactorial, FallingFactorial, harmonic, atan2, sec, acsc, hermite, laguerre, assoc_laguerre, jacobi, gegenbauer, chebyshevt, chebyshevu, legendre, assoc_legendre) from sympy import mathematica_code as mcode x, y, z, w = symbols('x,y,z,w') f = Function('f') def test_Integer(): assert mcode(Integer(67)) == "67" assert mcode(Integer(-1)) == "-1" def test_Rational(): assert mcode(Rational(3, 7)) == "3/7" assert mcode(Rational(18, 9)) == "2" assert mcode(Rational(3, -7)) == "-3/7" assert mcode(Rational(-3, -7)) == "3/7" assert mcode(x + Rational(3, 7)) == "x + 3/7" assert mcode(Rational(3, 7)*x) == "(3/7)*x"
def test_parse_function_issue_3539(): x = Symbol('x') f = Function('f') assert parse_expr('f(x)') == f(x)
def apart_list_full_decomposition(P, Q, dummygen): """ Bronstein's full partial fraction decomposition algorithm. Given a univariate rational function ``f``, performing only GCD operations over the algebraic closure of the initial ground domain of definition, compute full partial fraction decomposition with fractions having linear denominators. Note that no factorization of the initial denominator of ``f`` is performed. The final decomposition is formed in terms of a sum of :class:`RootSum` instances. References ========== 1. [Bronstein93]_ """ f, x, U = P/Q, P.gen, [] u = Function('u')(x) a = Dummy('a') partial = [] for d, n in Q.sqf_list_include(all=True): b = d.as_expr() U += [ u.diff(x, n - 1) ] h = cancel(f*b**n) / u**n H, subs = [h], [] for j in range(1, n): H += [ H[-1].diff(x) / j ] for j in range(1, n + 1): subs += [ (U[j - 1], b.diff(x, j) / j) ] for j in range(0, n): P, Q = cancel(H[j]).as_numer_denom() for i in range(0, j + 1): P = P.subs(*subs[j - i]) Q = Q.subs(*subs[0]) P = Poly(P, x) Q = Poly(Q, x) G = P.gcd(d) D = d.quo(G) B, g = Q.half_gcdex(D) b = (P * B.quo(g)).rem(D) Dw = D.subs(x, dummygen.next()) numer = Lambda(a, b.as_expr().subs(x, a)) denom = Lambda(a, (x - a)) exponent = n-j partial.append((Dw, numer, denom, exponent)) return partial
from sympy.solvers.ode.ode import allhints, _remove_redundant_solutions from sympy.solvers.ode.single import (FirstLinear, ODEMatchError, SingleODEProblem, SingleODESolver) from sympy.solvers.ode.subscheck import checkodesol from sympy.testing.pytest import raises, slow import traceback from time import process_time import pytest x = Symbol('x') u = Symbol('u') i = Symbol('i') y = Function('y')(x) # arbitrary functions in the kamke ODEs f = Function('f') g = Function('g') h = Function('h') C1, C2, C3, C4, C5 = symbols('C1:6') a0,a1,a2,a3,a4,a,b,c,A,B,C,nu,m,n = symbols('a0, a1, a2, a3, a4, a, b, c, A, B, C, nu, m, n') kamke1_1 = [ 0, #/* 1 */ y.diff(x)-(a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**(-1/2), #/* 2 */ y.diff(x)+a*y-c*exp(b*x), #/* 3 */
def apart_list_full_decomposition(P, Q, dummygen): """ Bronstein's full partial fraction decomposition algorithm. Given a univariate rational function ``f``, performing only GCD operations over the algebraic closure of the initial ground domain of definition, compute full partial fraction decomposition with fractions having linear denominators. Note that no factorization of the initial denominator of ``f`` is performed. The final decomposition is formed in terms of a sum of :class:`RootSum` instances. References ========== .. [1] [Bronstein93]_ """ f, x, U = P/Q, P.gen, [] u = Function('u')(x) a = Dummy('a') partial = [] for d, n in Q.sqf_list_include(all=True): b = d.as_expr() U += [ u.diff(x, n - 1) ] h = cancel(f*b**n) / u**n H, subs = [h], [] for j in range(1, n): H += [ H[-1].diff(x) / j ] for j in range(1, n + 1): subs += [ (U[j - 1], b.diff(x, j) / j) ] for j in range(0, n): P, Q = cancel(H[j]).as_numer_denom() for i in range(0, j + 1): P = P.subs(*subs[j - i]) Q = Q.subs(*subs[0]) P = Poly(P, x) Q = Poly(Q, x) G = P.gcd(d) D = d.quo(G) B, g = Q.half_gcdex(D) b = (P * B.quo(g)).rem(D) Dw = D.subs(x, next(dummygen)) numer = Lambda(a, b.as_expr().subs(x, a)) denom = Lambda(a, (x - a)) exponent = n-j partial.append((Dw, numer, denom, exponent)) return partial
def apart(f, z, domain=None, index=None): """Computes full partial fraction decomposition of a univariate rational function over the algebraic closure of its field of definition. Although only gcd operations over the initial field are required, the expansion is returned in a formal form with linear denominators. However it is possible to force expansion of the resulting formal summations, and so factorization over a specified domain is performed. To specify the desired behavior of the algorithm use the 'domain' keyword. Setting it to None, which is done be default, will result in no factorization at all. Otherwise it can be assigned with one of Z, Q, R, C domain specifiers and the formal partial fraction expansion will be rewritten using all possible roots over this domain. If the resulting expansion contains formal summations, then for all those a single dummy index variable named 'a' will be generated. To change this default behavior issue new name via 'index' keyword. For more information on the implemented algorithm refer to: [1] M. Bronstein, B. Salvy, Full partial fraction decomposition of rational functions, in: M. Bronstein, ed., Proceedings ISSAC '93, ACM Press, Kiev, Ukraine, 1993, pp. 157-160. """ f = Basic.sympify(f) if isinstance(f, Basic.Add): return Add(*[ apart(g) for g in f ]) else: if f.is_fraction(z): f = normal(f, z) else: return f P, Q = f.as_numer_denom() if not Q.has(z): return f u = Function('u')(z) if index is None: A = Symbol('a', dummy=True) else: A = Symbol(index) partial, r = div(P, Q, z) f, q, U = r / Q, Q, [] for k, d in enumerate(sqf(q, z)): n, d = k + 1, d.as_basic() U += [ u.diff(z, k) ] h = normal(f * d**n, z) / u**n H, subs = [h], [] for j in range(1, n): H += [ H[-1].diff(z) / j ] for j in range(1, n+1): subs += [ (U[j-1], d.diff(z, j) / j) ] for j in range(0, n): P, Q = together(H[j]).as_numer_denom() for i in range(0, j+1): P = P.subs(*subs[j-i]) Q = Q.subs(*subs[0]) G = gcd(P, d, z) D = quo(d, G, z) g, B, _ = ext_gcd(Q, D, z) b = rem(P * B / g, D, z) term = b.subs(z, A) / (z - A)**(n-j) if domain is None: a = D.diff(z) if not a.has(z): partial += term.subs(A, -D.subs(z, 0) / a) else: partial += Basic.Sum(term, (A, Basic.RootOf(D, z))) else: raise NotImplementedError return partial