コード例 #1
0
ファイル: test_expr.py プロジェクト: FireJade/sympy
def test_equals():
    assert (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2).equals(0)
    assert (x**2 - 1).equals((x + 1)*(x - 1))
    assert (cos(x)**2 + sin(x)**2).equals(1)
    assert (a*cos(x)**2 + a*sin(x)**2).equals(a)
    r = sqrt(2)
    assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0)
    assert factorial(x + 1).equals((x + 1)*factorial(x))
    assert sqrt(3).equals(2*sqrt(3)) is False
    assert (sqrt(5)*sqrt(3)).equals(sqrt(3)) is False
    assert (sqrt(5) + sqrt(3)).equals(0) is False
    assert (sqrt(5) + pi).equals(0) is False
    assert meter.equals(0) is False
    assert (3*meter**2).equals(0) is False

    # from integrate(x*sqrt(1+2*x), x);
    # diff is zero only when assumptions allow
    i = 2*sqrt(2)*x**(S(5)/2)*(1 + 1/(2*x))**(S(5)/2)/5 + \
        2*sqrt(2)*x**(S(3)/2)*(1 + 1/(2*x))**(S(5)/2)/(-6 - 3/x)
    ans = sqrt(2*x + 1)*(6*x**2 + x - 1)/15
    diff = i - ans
    assert diff.equals(0) is False
    assert diff.subs(x, -S.Half/2) == 7*sqrt(2)/120
    # there are regions for x for which the expression is True, for
    # example, when x < -1/2 or x > 0 the expression is zero
    p = Symbol('p', positive=True)
    assert diff.subs(x, p).equals(0) is True
    assert diff.subs(x, -1).equals(0) is True
コード例 #2
0
ファイル: mgf_math.py プロジェクト: emkoch/quant_gen_fun
 def create_mgf_expr(self):
     """ Create sympy expression for the simple taylor expansion of the mgf. """
     indivs = range(self.n_indivs)
     branches = []
     for branch_size in range(1, self.n_indivs):
         branches += itertools.combinations(indivs, branch_size)
     mgf_base = sympy.Integer(1)
     num_loci = sympy.symbols("L", integer=True)
     for mom_order in range(1, self.moment_order + 1):
         m_max = self.moment_order - mom_order + 1
         branch_combos = itertools.combinations_with_replacement(branches, mom_order)
         for branch_combo in branch_combos:
             branch_mult = list(Counter(branch_combo).values())
             term_factor = sympy.Integer(1)
             for multi in branch_mult:
                 term_factor *= sympy.factorial(multi)
             bc_term = (make_subscr(branch_combo)*
                        sympy.symbols('theta')**mom_order*term_factor**-1)
             for branch in branch_combo:
                 branch_sum = sympy.Integer(0)
                 for indiv in branch:
                     branch_sum += sympy.symbols('k_' + str(indiv))
                 branch_term = sympy.Integer(0)
                 for mut_order in range(1, m_max + 1):
                     branch_term += (sympy.symbols('m_' + str(mut_order))/
                                     sympy.factorial(mut_order)*branch_sum**mut_order)
                 bc_term *= branch_term
             mgf_base += bc_term
     return mgf_base**num_loci
コード例 #3
0
def test_issue_9699():
    n, k = symbols('n k', real=True)
    x, y = symbols('x, y')
    assert combsimp((n + 1)*factorial(n)) == factorial(n + 1)
    assert combsimp((x + 1)*factorial(x)/gamma(y)) == gamma(x + 2)/gamma(y)
    assert combsimp(factorial(n)/n) == factorial(n - 1)
    assert combsimp(rf(x + n, k)*binomial(n, k)) == binomial(n, k)*gamma(k + n + x)/gamma(n + x)
コード例 #4
0
def test_simple_products():
    assert product(2, (k, a, n)) == 2**(n - a + 1)
    assert product(k, (k, 1, n)) == factorial(n)
    assert product(k**3, (k, 1, n)) == factorial(n)**3

    assert product(k + 1, (k, 0, n - 1)) == factorial(n)
    assert product(k + 1, (k, a, n - 1)) == rf(1 + a, n - a)

    assert product(cos(k), (k, 0, 5)) == cos(1)*cos(2)*cos(3)*cos(4)*cos(5)
    assert product(cos(k), (k, 3, 5)) == cos(3)*cos(4)*cos(5)
    assert product(cos(k), (k, 1, Rational(5, 2))) != cos(1)*cos(2)

    assert isinstance(product(k**k, (k, 1, n)), Product)

    assert Product(x**k, (k, 1, n)).variables == [k]

    raises(ValueError, lambda: Product(n))
    raises(ValueError, lambda: Product(n, k))
    raises(ValueError, lambda: Product(n, k, 1))
    raises(ValueError, lambda: Product(n, k, 1, 10))
    raises(ValueError, lambda: Product(n, (k, 1)))

    assert product(1, (n, 1, oo)) == 1  # issue 8301
    assert product(2, (n, 1, oo)) == oo
    assert product(-1, (n, 1, oo)).func is Product
コード例 #5
0
ファイル: test_str.py プロジェクト: bibile/sympy
def test_Factorial():
    n = Symbol('n', integer=True)
    assert str(factorial(-2)) == "0"
    assert str(factorial(0)) == "1"
    assert str(factorial(7)) == "5040"
    assert str(factorial(n)) == "n!"
    assert str(factorial(2*n)) == "(2*n)!"
コード例 #6
0
ファイル: monomials.py プロジェクト: A-turing-machine/sympy
def monomial_count(V, N):
    r"""
    Computes the number of monomials.

    The number of monomials is given by the following formula:

    .. math::

        \frac{(\#V + N)!}{\#V! N!}

    where `N` is a total degree and `V` is a set of variables.

    Examples
    ========

    >>> from sympy.polys.monomials import itermonomials, monomial_count
    >>> from sympy.polys.orderings import monomial_key
    >>> from sympy.abc import x, y

    >>> monomial_count(2, 2)
    6

    >>> M = itermonomials([x, y], 2)

    >>> sorted(M, key=monomial_key('grlex', [y, x]))
    [1, x, y, x**2, x*y, y**2]
    >>> len(M)
    6

    """
    from sympy import factorial
    return factorial(V + N) / factorial(V) / factorial(N)
コード例 #7
0
def test_factorial_diff():
    n = Symbol('n', integer=True)

    assert factorial(n).diff(n) == \
        gamma(1 + n)*polygamma(0, 1 + n)
    assert factorial(n**2).diff(n) == \
        2*n*gamma(1 + n**2)*polygamma(0, 1 + n**2)
コード例 #8
0
ファイル: rooted_trees.py プロジェクト: alexfikl/nodepy
    def symmetry(self):
        r"""
        The symmetry $\\sigma(t)$ of a rooted tree is...

        **Examples**::

            >>> from nodepy import rooted_trees as rt
            >>> tree=rt.RootedTree('{T^2{T{T}}}')
            >>> tree.symmetry()
            2

        **Reference**:

            - [butcher2003]_ p. 127, eq. 301(b)
        """
        from nodepy.strmanip import getint
        if self=='T': return 1
        sigma=1
        if self[1]=='T':
            try: sigma=factorial(getint(self[3:]))
            except: pass
        nleaves,subtrees=self._parse_subtrees()
        while len(subtrees)>0:
            st=subtrees[0]
            nst=subtrees.count(st)
            sigma*=factorial(nst)*st.symmetry()**nst
            while st in subtrees: subtrees.remove(st)
        return sigma
コード例 #9
0
ファイル: test_sums_products.py プロジェクト: Maihj/sympy
def test_simple_products():
    assert Product(S.NaN, (x, 1, 3)) is S.NaN
    assert product(S.NaN, (x, 1, 3)) is S.NaN
    assert Product(x, (n, a, a)).doit() == x
    assert Product(x, (x, a, a)).doit() == a
    assert Product(x, (y, 1, a)).doit() == x**a
    lo, hi = 1, 2
    s1 = Product(n, (n, lo, hi))
    s2 = Product(n, (n, hi, lo))
    assert s1 != s2
    assert s1.doit() == s2.doit() == 2
    lo, hi = x, x + 1
    s1 = Product(n, (n, lo, hi))
    s2 = Product(n, (n, hi, lo))
    assert s1 != s2
    assert s1.doit() == s2.doit() == x*(x + 1)
    assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \
        (y**2 + 1)*(y**2 + 3)
    assert product(2, (n, a, b)) == 2**(b - a + 1)
    assert product(n, (n, 1, b)) == factorial(b)
    assert product(n**3, (n, 1, b)) == factorial(b)**3
    assert product(3**(2 + n), (n, a, b)) \
        == 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2)
    assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5)
    assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2)
    assert isinstance(product(cos(n), (n, x, x + S.Half)), Product)
    # If Product managed to evaluate this one, it most likely got it wrong!
    assert isinstance(Product(n**n, (n, 1, b)), Product)
コード例 #10
0
ファイル: test_expr.py プロジェクト: Botouls/sympy
def test_equals():
    assert (-3 - sqrt(5) + (-sqrt(10) / 2 - sqrt(2) / 2) ** 2).equals(0)
    assert (x ** 2 - 1).equals((x + 1) * (x - 1))
    assert (cos(x) ** 2 + sin(x) ** 2).equals(1)
    assert (a * cos(x) ** 2 + a * sin(x) ** 2).equals(a)
    r = sqrt(2)
    assert (-1 / (r + r * x) + 1 / r / (1 + x)).equals(0)
    assert factorial(x + 1).equals((x + 1) * factorial(x))
    assert sqrt(3).equals(2 * sqrt(3)) is False
    assert (sqrt(5) * sqrt(3)).equals(sqrt(3)) is False
    assert (sqrt(5) + sqrt(3)).equals(0) is False
    assert (sqrt(5) + pi).equals(0) is False
    assert meter.equals(0) is False
    assert (3 * meter ** 2).equals(0) is False

    # from integrate(x*sqrt(1+2*x), x);
    # diff is zero, but differentiation does not show it
    i = 2 * sqrt(2) * x ** (S(5) / 2) * (1 + 1 / (2 * x)) ** (S(5) / 2) / 5 + 2 * sqrt(2) * x ** (S(3) / 2) * (
        1 + 1 / (2 * x)
    ) ** (S(5) / 2) / (-6 - 3 / x)
    ans = sqrt(2 * x + 1) * (6 * x ** 2 + x - 1) / 15
    diff = i - ans
    assert diff.equals(0) is not False  # should be True, but now it's None
    # XXX TODO add a force=True option to equals to posify both
    # self and other before beginning comparisions
    p = Symbol("p", positive=True)
    assert diff.subs(x, p).equals(0) is True
コード例 #11
0
ファイル: test_latex.py プロジェクト: hazelnusse/sympy-old
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)$"
コード例 #12
0
ファイル: test_recurr.py プロジェクト: Vance-Turner/sympy
def test_rsolve():
    f = y(n+2) - y(n+1) - y(n)
    h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \
      - sqrt(5)*(S.Half - S.Half*sqrt(5))**n

    assert rsolve(f, y(n)) in [
        C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
        C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
    ]

    assert rsolve(f, y(n), [      0,      5 ]) == h
    assert rsolve(f, y(n), {   0 :0,   1 :5 }) == h
    assert rsolve(f, y(n), { y(0):0, y(1):5 }) == h
    assert rsolve(y(n) - y(n-1) - y(n-2), y(n), [0, 5]) == h

    f = (n-1)*y(n+2) - (n**2+3*n-2)*y(n+1) + 2*n*(n+1)*y(n)
    g = C1*factorial(n) + C0*2**n
    h = -3*factorial(n) + 3*2**n

    assert rsolve(f, y(n)) == g
    assert rsolve(f, y(n), []) == g
    assert rsolve(f, y(n), {}) == g

    assert rsolve(f, y(n), [      0,      3 ]) == h
    assert rsolve(f, y(n), {   0 :0,   1 :3 }) == h
    assert rsolve(f, y(n), { y(0):0, y(1):3 }) == h
コード例 #13
0
ファイル: test_gosper.py プロジェクト: ArchKaine/sympy
def test_gosper_sum_AeqB_part1():
    f1a = n**4
    f1b = n**3*2**n
    f1c = 1/(n**2 + sqrt(5)*n - 1)
    f1d = n**4*4**n/binomial(2*n, n)
    f1e = factorial(3*n)/(factorial(n)*factorial(n + 1)*factorial(n + 2)*27**n)
    f1f = binomial(2*n, n)**2/((n + 1)*4**(2*n))
    f1g = (4*n - 1)*binomial(2*n, n)**2/((2*n - 1)**2*4**(2*n))
    f1h = n*factorial(n - S(1)/2)**2/factorial(n + 1)**2

    g1a = m*(m + 1)*(2*m + 1)*(3*m**2 + 3*m - 1)/30
    g1b = 26 + 2**(m + 1)*(m**3 - 3*m**2 + 9*m - 13)
    g1c = (m + 1)*(m*(m**2 - 7*m + 3)*sqrt(5) - (3*m**3 - 7*m**2 + 19*m - 6))/(2*m**3*sqrt(5) + m**4 + m**2 - 1)/6
    g1d = -S(2)/231 + 24**m*(m + 1)*(63*m**4 + 112*m**3 + 18*m**2 - 22*m + 3)/(693*binomial(2*m, m))
    g1e = -S(9)/2 + (81*m**2 + 261*m + 200)*factorial(3*m + 2)/(40*27**m*factorial(m)*factorial(m + 1)*factorial(m + 2))
    g1f = (2*m + 1)**2*binomial(2*m, m)**2/(4**(2*m)*(m + 1))
    g1g = -binomial(2*m, m)**2/4**(2*m)
    g1h = -(2*m + 1)**2*(3*m + 4)*factorial(m - S(1)/2)**2/factorial(m + 1)**2

    g = gosper_sum(f1a, (n, 0, m))
    assert g is not None  and simplify(g - g1a) == 0
    g = gosper_sum(f1b, (n, 0, m))
    assert g is not None  and simplify(g - g1b) == 0
    g = gosper_sum(f1c, (n, 0, m))
    assert g is not None # and simplify(g - g1c) == 0
    g = gosper_sum(f1d, (n, 0, m))
    assert g is not None # and simplify(g - g1d) == 0
    g = gosper_sum(f1e, (n, 0, m))
    assert g is not None # and simplify(g - g1e) == 0
    g = gosper_sum(f1f, (n, 0, m))
    assert g is not None # and simplify(g - g1f) == 0
    g = gosper_sum(f1g, (n, 0, m))
    assert g is not None # and simplify(g - g1g) == 0
    g = gosper_sum(f1h, (n, 0, m))
    assert g is not None # and simplify(g - g1h) == 0
コード例 #14
0
ファイル: test_expr.py プロジェクト: Kimay/sympy
def test_equals():
    assert (x**2 - 1).equals((x + 1)*(x - 1))
    assert (cos(x)**2 + sin(x)**2).equals(1)
    assert (a*cos(x)**2 + a*sin(x)**2).equals(a)
    r = sqrt(2)
    assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0)
    assert factorial(x + 1).equals((x + 1)*factorial(x))
コード例 #15
0
ファイル: test_simplify.py プロジェクト: Vance-Turner/sympy
def test_combsimp():
    from sympy.abc import n, k

    assert combsimp(factorial(n)) == factorial(n)
    assert combsimp(binomial(n, k)) == binomial(n, k)

    assert combsimp(factorial(n)/factorial(n - 3)) == n*(-1 + n)*(-2 + n)
    assert combsimp(binomial(n + 1, k + 1)/binomial(n, k)) == (1 + n)/(1 + k)

    assert combsimp(binomial(3*n + 4, n + 1)/binomial(3*n + 1, n)) == \
        S(3)/2*((3*n + 2)*(3*n + 4)/((n + 1)*(2*n + 3)))

    assert combsimp(factorial(n)**2/factorial(n - 3)) == factorial(n)*n*(-1 + n)*(-2 + n)
    assert combsimp(factorial(n)*binomial(n+1, k+1)/binomial(n, k)) == factorial(n)*(1 + n)/(1 + k)

    assert combsimp(binomial(n - 1, k)) == -((-n + k)*binomial(n, k))/n

    assert combsimp(binomial(n + 2, k + S(1)/2)) == \
        4*((n + 1)*(n + 2)*binomial(n, k + S(1)/2))/((2*k - 2*n - 1)*(2*k - 2*n - 3))
    assert combsimp(binomial(n + 2, k + 2.0)) == \
        -((1.0*n + 2.0)*binomial(n + 1.0, k + 2.0))/(k - n)

    # coverage tests
    assert combsimp(factorial(n*(1 + n) - n**2 - n)) == 1
    assert combsimp(binomial(n + k - 2, n)) \
        == k*(k - 1)*binomial(n + k, n)/((n + k)*(n + k - 1))
    i = Symbol('i', integer=True)
    e = gamma(i + 3)
    assert combsimp(e) == e
    e = gamma(exp(i))
    assert combsimp(e) == e
    e = gamma(n + S(1)/3)*gamma(n + S(2)/3)
    assert combsimp(e) == e
    assert combsimp(gamma(4*n + S(1)/2)/gamma(2*n - S(3)/4)) \
        == 2**(4*n - S(5)/2)*(8*n - 3)*gamma(2*n + S(3)/4)/sqrt(pi)
コード例 #16
0
ファイル: equations.py プロジェクト: Genas2/diplom
    def Theta_Equation(self, l="undef", m="undef", theta=theta):
        """ l - orbital quantum number
            m - magnetic quantum number """

        if l == "undef":
            l = self.l_val
        if m == "undef":
            m = self.m_val

        # Prevents integer division and float l,m
        l = int(l)
        m = int(m)

        mode = self.select_exec_mode(theta)

        gL = self.Generalized_Legendre(l, m, theta).subs(theta, sympy.cos(theta))

        if gL:
            rat_part = sympy.sqrt(
                Rational((2 * l + 1), 2) * Rational(factorial(l - sympy.abs(m)), factorial(l + sympy.abs(m)))
            )
            if mode == "numer":
                return (rat_part * gL).evalf()
            elif mode == "analit":
                return (rat_part * gL).expand()

        return False
コード例 #17
0
ファイル: test_latex.py プロジェクト: jcockayne/sympy-rkern
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)$"
コード例 #18
0
ファイル: queue_dist.py プロジェクト: MthwRobinson/APPLPy
def cases(n):         
    """
    Procedure Name: cases
    Purpose: Generates all possible arrival/departure sequences for
                n customers in an M/M/1 queue initially empty and
                idle.
    Arguments:  1. n: the total number of customers in the system
    Output:     1. C: a list of sequences consisting of 1s and -1s,
                        where 1s represent an arrival and -1s
                        represent a departure
    """
    # Compute the nth Catalan number
    c=factorial(2*n)/factorial(n)/factorial(n+1)
    C=np.zeros((c,2*n))
    for i in range(c):
        # Initialize the matrix C
        if i==0:
            C[i]=ini(n)
        # Produce the successor the C[i]
        else:
            C[i]=swapa(n,C[i-1])
        # Check to see if the successor is legal
        #   If not, call swapb
        if okay(n,C[i])==False:
            C[i]=swapb(n,C[i-1])
    return C
コード例 #19
0
ファイル: trajectory.py プロジェクト: rihe/pyinduct
    def __init__(self, states, interval, differential_order):
        """
        :param states: tuple of states in beginning and end of interval
        :param interval: time interval (tuple)
        :param differential_order: grade of differential flatness :math:`\\gamma`
        """
        self.yd = states
        self.t0 = interval[0]
        self.t1 = interval[1]
        self.dt = interval[1] - interval[0]
        gamma = differential_order  # + 1 # TODO check this against notes

        # setup symbolic expressions
        tau, k = sp.symbols('tau, k')

        alpha = sp.factorial(2 * gamma + 1)

        f = sp.binomial(gamma, k) * (-1) ** k * tau ** (gamma + k + 1) / (gamma + k + 1)
        phi = alpha / sp.factorial(gamma) ** 2 * sp.summation(f, (k, 0, gamma))

        # differentiate phi(tau), index in list corresponds to order
        dphi_sym = [phi]  # init with phi(tau)
        for order in range(differential_order):
            dphi_sym.append(dphi_sym[-1].diff(tau))

        # lambdify
        self.dphi_num = []
        for der in dphi_sym:
            self.dphi_num.append(sp.lambdify(tau, der, 'numpy'))
コード例 #20
0
def test_factorials():
    n = Symbol('n', integer=True)
    assert factorial(-2) == 0
    assert factorial(0) == 1
    assert factorial(7) == 5040
    assert factorial(n).func == Factorial
    assert factorial(2*n).func == Factorial
コード例 #21
0
def test_jacobi():
    n = Symbol("n")
    a = Symbol("a")
    b = Symbol("b")

    assert jacobi(0, a, b, x) == 1
    assert jacobi(1, a, b, x) == a/2 - b/2 + x*(a/2 + b/2 + 1)

    assert jacobi(n, a, a, x) == RisingFactorial(a + 1, n)*gegenbauer(n, a + S(1)/2, x)/RisingFactorial(2*a + 1, n)
    assert jacobi(n, a, -a, x) == ((-1)**a*(-x + 1)**(-a/2)*(x + 1)**(a/2)*assoc_legendre(n, a, x)*
                                   factorial(-a + n)*gamma(a + n + 1)/(factorial(a + n)*gamma(n + 1)))
    assert jacobi(n, -b, b, x) == ((-x + 1)**(b/2)*(x + 1)**(-b/2)*assoc_legendre(n, b, x)*
                                   gamma(-b + n + 1)/gamma(n + 1))
    assert jacobi(n, 0, 0, x) == legendre(n, x)
    assert jacobi(n, S.Half, S.Half, x) == RisingFactorial(S(3)/2, n)*chebyshevu(n, x)/factorial(n + 1)
    assert jacobi(n, -S.Half, -S.Half, x) == RisingFactorial(S(1)/2, n)*chebyshevt(n, x)/factorial(n)

    X = jacobi(n, a, b, x)
    assert isinstance(X, jacobi)

    assert jacobi(n, a, b, -x) == (-1)**n*jacobi(n, b, a, x)
    assert jacobi(n, a, b, 0) == 2**(-n)*gamma(a + n + 1)*hyper((-b - n, -n), (a + 1,), -1)/(factorial(n)*gamma(a + 1))
    assert jacobi(n, a, b, 1) == RisingFactorial(a + 1, n)/factorial(n)

    m = Symbol("m", positive=True)
    assert jacobi(m, a, b, oo) == oo*RisingFactorial(a + b + m + 1, m)

    assert conjugate(jacobi(m, a, b, x)) == jacobi(m, conjugate(a), conjugate(b), conjugate(x))

    assert diff(jacobi(n,a,b,x), n) == Derivative(jacobi(n, a, b, x), n)
    assert diff(jacobi(n,a,b,x), x) == (a/2 + b/2 + n/2 + S(1)/2)*jacobi(n - 1, a + 1, b + 1, x)
コード例 #22
0
def test_factorials():
    n = Symbol('n', integer=True)
    assert factorial(-2) == 0
    assert factorial(0) == 1
    assert factorial(7) == 5040
    assert isinstance(factorial(n), Factorial)
    assert isinstance(factorial(2*n), Factorial)
コード例 #23
0
ファイル: test_simplify.py プロジェクト: pabloferz/sympy
def test_simplify_other():
    assert simplify(sin(x) ** 2 + cos(x) ** 2) == 1
    assert simplify(gamma(x + 1) / gamma(x)) == x
    assert simplify(sin(x) ** 2 + cos(x) ** 2 + factorial(x) / gamma(x)) == 1 + x
    assert simplify(Eq(sin(x) ** 2 + cos(x) ** 2, factorial(x) / gamma(x))) == Eq(x, 1)
    nc = symbols("nc", commutative=False)
    assert simplify(x + x * nc) == x * (1 + nc)
    # issue 6123
    # f = exp(-I*(k*sqrt(t) + x/(2*sqrt(t)))**2)
    # ans = integrate(f, (k, -oo, oo), conds='none')
    ans = I * (
        -pi
        * x
        * exp(-3 * I * pi / 4 + I * x ** 2 / (4 * t))
        * erf(x * exp(-3 * I * pi / 4) / (2 * sqrt(t)))
        / (2 * sqrt(t))
        + pi * x * exp(-3 * I * pi / 4 + I * x ** 2 / (4 * t)) / (2 * sqrt(t))
    ) * exp(-I * x ** 2 / (4 * t)) / (sqrt(pi) * x) - I * sqrt(pi) * (
        -erf(x * exp(I * pi / 4) / (2 * sqrt(t))) + 1
    ) * exp(
        I * pi / 4
    ) / (
        2 * sqrt(t)
    )
    assert simplify(ans) == -(-1) ** (S(3) / 4) * sqrt(pi) / sqrt(t)
    # issue 6370
    assert simplify(2 ** (2 + x) / 4) == 2 ** x
コード例 #24
0
ファイル: test_evalf.py プロジェクト: cklb/sympy
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
コード例 #25
0
ファイル: test_comb_factorials.py プロジェクト: scopatz/sympy
def test_binomial_rewrite():
    n = Symbol("n", integer=True)
    k = Symbol("k", integer=True)

    assert binomial(n, k).rewrite(factorial) == factorial(n) / (factorial(k) * factorial(n - k))
    assert binomial(n, k).rewrite(gamma) == gamma(n + 1) / (gamma(k + 1) * gamma(n - k + 1))
    assert binomial(n, k).rewrite(ff) == ff(n, k) / factorial(k)
コード例 #26
0
ファイル: test_simplify.py プロジェクト: Kimay/sympy
def test_simplify_other():
    assert simplify(sin(x)**2 + cos(x)**2) == 1
    assert simplify(gamma(x + 1)/gamma(x)) == x
    assert simplify(sin(x)**2 + cos(x)**2 + factorial(x)/gamma(x)) == 1 + x
    assert simplify(Eq(sin(x)**2 + cos(x)**2, factorial(x)/gamma(x))) == Eq(1, x)
    nc = symbols('nc', commutative=False)
    assert simplify(x + x*nc) == x*(1 + nc)
コード例 #27
0
ファイル: spin.py プロジェクト: wxgeo/sympy
 def d(cls, j, m, mp, beta):
     """Wigner's lowercase d function."""
     # TODO: This does not do a good job of simplifying the trig functions.
     # The Jacobi Polynomial expansion is probably best as it is a simple
     # sum. But, this version does give correct answers and uses
     # Eq. 7 in Section 4.3.2 of Varshalovich.
     j = sympify(j)
     cosbeta = Symbol('cosbeta')
     x = 1-cosbeta
     y = 1+cosbeta
     jmmp = j-mp
     jpm = j+m
     jpmp = j+mp
     jmm = j-m
     mpmm2 = (mp-m)//2
     mpmp2 = (m+mp)//2
     result = (-1)**jmmp
     result *= 2**(-j)
     result *= sqrt(factorial(jpm)/(factorial(jmm)*factorial(jpmp)*factorial(jmmp)))
     result *= (x**mpmm2)*(y**(-mpmp2))
     result *= diff((x**jmmp)*(y**jpmp), cosbeta, jmm)
     if (2*j).is_Integer and not j.is_Integer:
         result = result.subs(1+cosbeta, 2*cos(beta/2)**2)
         result = result.subs(1-cosbeta, 2*sin(beta/2)**2)
     else:
         result = result.subs(cosbeta, cos(beta))
     return result
コード例 #28
0
def test_rf_eval_apply():
    x, y = symbols('x,y')
    n, k = symbols('n k', integer=True)
    m = Symbol('m', integer=True, nonnegative=True)

    assert rf(nan, y) == nan
    assert rf(x, nan) == nan

    assert rf(x, y) == rf(x, y)

    assert rf(oo, 0) == 1
    assert rf(-oo, 0) == 1

    assert rf(oo, 6) == oo
    assert rf(-oo, 7) == -oo

    assert rf(oo, -6) == oo
    assert rf(-oo, -7) == oo

    assert rf(x, 0) == 1
    assert rf(x, 1) == x
    assert rf(x, 2) == x*(x + 1)
    assert rf(x, 3) == x*(x + 1)*(x + 2)
    assert rf(x, 5) == x*(x + 1)*(x + 2)*(x + 3)*(x + 4)

    assert rf(x, -1) == 1/(x - 1)
    assert rf(x, -2) == 1/((x - 1)*(x - 2))
    assert rf(x, -3) == 1/((x - 1)*(x - 2)*(x - 3))

    assert rf(1, 100) == factorial(100)

    assert rf(x**2 + 3*x, 2) == (x**2 + 3*x)*(x**2 + 3*x + 1)
    assert isinstance(rf(x**2 + 3*x, 2), Mul)
    assert rf(x**3 + x, -2) == 1/((x**3 + x - 1)*(x**3 + x - 2))

    assert rf(Poly(x**2 + 3*x, x), 2) == Poly(x**4 + 8*x**3 + 19*x**2 + 12*x, x)
    assert isinstance(rf(Poly(x**2 + 3*x, x), 2), Poly)
    raises(ValueError, lambda: rf(Poly(x**2 + 3*x, x, y), 2))
    assert rf(Poly(x**3 + x, x), -2) == 1/(x**6 - 9*x**5 + 35*x**4 - 75*x**3 + 94*x**2 - 66*x + 20)
    raises(ValueError, lambda: rf(Poly(x**3 + x, x, y), -2))

    assert rf(x, m).is_integer is None
    assert rf(n, k).is_integer is None
    assert rf(n, m).is_integer is True
    assert rf(n, k + pi).is_integer is False
    assert rf(n, m + pi).is_integer is False
    assert rf(pi, m).is_integer is False

    assert rf(x, k).rewrite(ff) == ff(x + k - 1, k)
    assert rf(x, k).rewrite(binomial) == factorial(k)*binomial(x + k - 1, k)
    assert rf(n, k).rewrite(factorial) == \
        factorial(n + k - 1) / factorial(n - 1)

    import random
    from mpmath import rf as mpmath_rf
    for i in range(100):
        x = -500 + 500 * random.random()
        k = -500 + 500 * random.random()
        assert (abs(mpmath_rf(x, k) - rf(x, k)) < 10**(-15))
コード例 #29
0
ファイル: test_sums_products.py プロジェクト: Maihj/sympy
def test_rational_products():
    assert Product(1 + 1/n, (n, a, b)) == (1 + b)/a
    assert Product(n + 1, (n, a, b)) == factorial(1 + b)/factorial(a)
    assert Product((n + 1)/(n - 1), (n, a, b)) == b*(1 + b)/(a*(a - 1))
    assert Product(n/(n + 1)/(n + 2), (n, a, b)) \
        == a*factorial(a + 1)/(b + 1)/factorial(b + 2)
    assert Product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b)) \
        == b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2))
コード例 #30
0
ファイル: test_assumptions.py プロジェクト: baoqchau/sympy
def test_issue_9115_9150():
    n = Dummy('n', integer=True, nonnegative=True)
    assert (factorial(n) >= 1) == True
    assert (factorial(n) < 1) == False

    assert factorial(n + 1).is_even is None
    assert factorial(n + 2).is_even is True
    assert factorial(n + 2) >= 2
コード例 #31
0
def test_inverse_mellin_transform():
    from sympy import (sin, simplify, Max, Min, expand,
                       powsimp, exp_polar, cos, cot)
    IMT = inverse_mellin_transform

    assert IMT(gamma(s), s, x, (0, oo)) == exp(-x)
    assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1/x)
    assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \
        (x**2 + 1)*Heaviside(1 - x)/(4*x)

    # test passing "None"
    assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \
        -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
    assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \
        -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)

    # test expansion of sums
    assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1)*exp(-x)/x

    # test factorisation of polys
    r = symbols('r', real=True)
    assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo)
              ).subs(x, r).rewrite(sin).simplify() \
        == sin(r)*Heaviside(1 - exp(-r))

    # test multiplicative substitution
    _a, _b = symbols('a b', positive=True)
    assert IMT(_b**(-s/_a)*factorial(s/_a)/s, s, x, (0, oo)) == exp(-_b*x**_a)
    assert IMT(factorial(_a/_b + s/_b)/(_a + s), s, x, (-_a, oo)) == x**_a*exp(-x**_b)

    def simp_pows(expr):
        return simplify(powsimp(expand_mul(expr, deep=False), force=True)).replace(exp_polar, exp)

    # Now test the inverses of all direct transforms tested above

    # Section 8.4.2
    nu = symbols('nu', real=True)
    assert IMT(-1/(nu + s), s, x, (-oo, None)) == x**nu*Heaviside(x - 1)
    assert IMT(1/(nu + s), s, x, (None, oo)) == x**nu*Heaviside(1 - x)
    assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \
        == (1 - x)**(beta - 1)*Heaviside(1 - x)
    assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
                         s, x, (-oo, None))) \
        == (x - 1)**(beta - 1)*Heaviside(x - 1)
    assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \
        == (1/(x + 1))**rho
    assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c)
                         *gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi,
                         s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \
        == (x**c - d**c)/(x - d)

    assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s)
                        *gamma(-c/2 - s)/gamma(1 - c - s),
                        s, x, (0, -re(c)/2))) == \
        (1 + sqrt(x + 1))**c
    assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s)
                        /gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \
        b**(a - 1)*(sqrt(1 + x/b**2) + 1)**(a - 1)*(b**2*sqrt(1 + x/b**2) +
        b**2 + x)/(b**2 + x)
    assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s)
                        / gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \
        b**c*(sqrt(1 + x/b**2) + 1)**c

    # Section 8.4.5
    assert IMT(24/s**5, s, x, (0, oo)) == log(x)**4*Heaviside(1 - x)
    assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \
        log(x)**3*Heaviside(x - 1)
    assert IMT(pi/(s*sin(pi*s)), s, x, (-1, 0)) == log(x + 1)
    assert IMT(pi/(s*sin(pi*s/2)), s, x, (-2, 0)) == log(x**2 + 1)
    assert IMT(pi/(s*sin(2*pi*s)), s, x, (Rational(-1, 2), 0)) == log(sqrt(x) + 1)
    assert IMT(pi/(s*sin(pi*s)), s, x, (0, 1)) == log(1 + 1/x)

    # TODO
    def mysimp(expr):
        from sympy import expand, logcombine, powsimp
        return expand(
            powsimp(logcombine(expr, force=True), force=True, deep=True),
            force=True).replace(exp_polar, exp)

    assert mysimp(mysimp(IMT(pi/(s*tan(pi*s)), s, x, (-1, 0)))) in [
        log(1 - x)*Heaviside(1 - x) + log(x - 1)*Heaviside(x - 1),
        log(x)*Heaviside(x - 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x +
        1)*Heaviside(-x + 1)]
    # test passing cot
    assert mysimp(IMT(pi*cot(pi*s)/s, s, x, (0, 1))) in [
        log(1/x - 1)*Heaviside(1 - x) + log(1 - 1/x)*Heaviside(x - 1),
        -log(x)*Heaviside(-x + 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x +
        1)*Heaviside(-x + 1), ]

    # 8.4.14
    assert IMT(-gamma(s + S.Half)/(sqrt(pi)*s), s, x, (Rational(-1, 2), 0)) == \
        erf(sqrt(x))

    # 8.4.19
    assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, Rational(3, 4)))) \
        == besselj(a, 2*sqrt(x))
    assert simplify(IMT(2**a*gamma(S.Half - 2*s)*gamma(s + (a + 1)/2)
                      / (gamma(1 - s - a/2)*gamma(1 - 2*s + a)),
                      s, x, (-(re(a) + 1)/2, Rational(1, 4)))) == \
        sin(sqrt(x))*besselj(a, sqrt(x))
    assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S.Half - 2*s)
                      / (gamma(S.Half - s - a/2)*gamma(1 - 2*s + a)),
                      s, x, (-re(a)/2, Rational(1, 4)))) == \
        cos(sqrt(x))*besselj(a, sqrt(x))
    # TODO this comes out as an amazing mess, but simplifies nicely
    assert simplify(IMT(gamma(a + s)*gamma(S.Half - s)
                      / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
                      s, x, (-re(a), S.Half))) == \
        besselj(a, sqrt(x))**2
    assert simplify(IMT(gamma(s)*gamma(S.Half - s)
                      / (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)),
                      s, x, (0, S.Half))) == \
        besselj(-a, sqrt(x))*besselj(a, sqrt(x))
    assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
                      / (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
                         *gamma(a/2 + b/2 - s + 1)),
                      s, x, (-(re(a) + re(b))/2, S.Half))) == \
        besselj(a, sqrt(x))*besselj(b, sqrt(x))

    # Section 8.4.20
    # TODO this can be further simplified!
    assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) *
                    gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) /
                    (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
                    s, x,
                    (Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S.Half))) == \
                    besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) -
                    besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b)
    # TODO more

    # for coverage

    assert IMT(pi/cos(pi*s), s, x, (0, S.Half)) == sqrt(x)/(x + 1)
コード例 #32
0
def test_ff_eval_apply():
    x, y = symbols("x,y")
    n, k = symbols("n k", integer=True)
    m = Symbol("m", integer=True, nonnegative=True)

    assert ff(nan, y) is nan
    assert ff(x, nan) is nan

    assert unchanged(ff, x, y)

    assert ff(oo, 0) == 1
    assert ff(-oo, 0) == 1

    assert ff(oo, 6) is oo
    assert ff(-oo, 7) is -oo
    assert ff(-oo, 6) is oo

    assert ff(oo, -6) is oo
    assert ff(-oo, -7) is oo

    assert ff(x, 0) == 1
    assert ff(x, 1) == x
    assert ff(x, 2) == x * (x - 1)
    assert ff(x, 3) == x * (x - 1) * (x - 2)
    assert ff(x, 5) == x * (x - 1) * (x - 2) * (x - 3) * (x - 4)

    assert ff(x, -1) == 1 / (x + 1)
    assert ff(x, -2) == 1 / ((x + 1) * (x + 2))
    assert ff(x, -3) == 1 / ((x + 1) * (x + 2) * (x + 3))

    assert ff(100, 100) == factorial(100)

    assert ff(2 * x ** 2 - 5 * x, 2) == (2 * x ** 2 - 5 * x) * (2 * x ** 2 - 5 * x - 1)
    assert isinstance(ff(2 * x ** 2 - 5 * x, 2), Mul)
    assert ff(x ** 2 + 3 * x, -2) == 1 / ((x ** 2 + 3 * x + 1) * (x ** 2 + 3 * x + 2))

    assert ff(Poly(2 * x ** 2 - 5 * x, x), 2) == Poly(
        4 * x ** 4 - 28 * x ** 3 + 59 * x ** 2 - 35 * x, x
    )
    assert isinstance(ff(Poly(2 * x ** 2 - 5 * x, x), 2), Poly)
    raises(ValueError, lambda: ff(Poly(2 * x ** 2 - 5 * x, x, y), 2))
    assert ff(Poly(x ** 2 + 3 * x, x), -2) == 1 / (
        x ** 4 + 12 * x ** 3 + 49 * x ** 2 + 78 * x + 40
    )
    raises(ValueError, lambda: ff(Poly(x ** 2 + 3 * x, x, y), -2))

    assert ff(x, m).is_integer is None
    assert ff(n, k).is_integer is None
    assert ff(n, m).is_integer is True
    assert ff(n, k + pi).is_integer is False
    assert ff(n, m + pi).is_integer is False
    assert ff(pi, m).is_integer is False

    assert isinstance(ff(x, x), ff)
    assert ff(n, n) == factorial(n)

    assert ff(x, k).rewrite(rf) == rf(x - k + 1, k)
    assert ff(x, k).rewrite(gamma) == (-1) ** k * gamma(k - x) / gamma(-x)
    assert ff(n, k).rewrite(factorial) == factorial(n) / factorial(n - k)
    assert ff(x, k).rewrite(binomial) == factorial(k) * binomial(x, k)
    assert ff(x, y).rewrite(factorial) == ff(x, y)
    assert ff(x, y).rewrite(binomial) == ff(x, y)

    import random
    from mpmath import ff as mpmath_ff

    for i in range(100):
        x = -500 + 500 * random.random()
        k = -500 + 500 * random.random()
        a = mpmath_ff(x, k)
        b = ff(x, k)
        assert abs(a - b) < abs(a) * 10 ** (-15)
コード例 #33
0
def test_factorial_Mod():
    pr = Symbol("pr", prime=True)
    p, q = 10 ** 9 + 9, 10 ** 9 + 33  # prime modulo
    r, s = 10 ** 7 + 5, 33333333  # composite modulo
    assert Mod(factorial(pr - 1), pr) == pr - 1
    assert Mod(factorial(pr - 1), -pr) == -1
    assert Mod(factorial(r - 1, evaluate=False), r) == 0
    assert Mod(factorial(s - 1, evaluate=False), s) == 0
    assert Mod(factorial(p - 1, evaluate=False), p) == p - 1
    assert Mod(factorial(q - 1, evaluate=False), q) == q - 1
    assert Mod(factorial(p - 50, evaluate=False), p) == 854928834
    assert Mod(factorial(q - 1800, evaluate=False), q) == 905504050
    assert Mod(factorial(153, evaluate=False), r) == Mod(factorial(153), r)
    assert Mod(factorial(255, evaluate=False), s) == Mod(factorial(255), s)
    assert Mod(factorial(4, evaluate=False), 3) == S.Zero
    assert Mod(factorial(5, evaluate=False), 6) == S.Zero
コード例 #34
0
def test_rf_eval_apply():
    x, y = symbols("x,y")
    n, k = symbols("n k", integer=True)
    m = Symbol("m", integer=True, nonnegative=True)

    assert rf(nan, y) is nan
    assert rf(x, nan) is nan

    assert unchanged(rf, x, y)

    assert rf(oo, 0) == 1
    assert rf(-oo, 0) == 1

    assert rf(oo, 6) is oo
    assert rf(-oo, 7) is -oo
    assert rf(-oo, 6) is oo

    assert rf(oo, -6) is oo
    assert rf(-oo, -7) is oo

    assert rf(-1, pi) == 0
    assert rf(-5, 1 + I) == 0

    assert unchanged(rf, -3, k)
    assert unchanged(rf, x, Symbol("k", integer=False))
    assert rf(-3, Symbol("k", integer=False)) == 0
    assert rf(Symbol("x", negative=True, integer=True), Symbol("k", integer=False)) == 0

    assert rf(x, 0) == 1
    assert rf(x, 1) == x
    assert rf(x, 2) == x * (x + 1)
    assert rf(x, 3) == x * (x + 1) * (x + 2)
    assert rf(x, 5) == x * (x + 1) * (x + 2) * (x + 3) * (x + 4)

    assert rf(x, -1) == 1 / (x - 1)
    assert rf(x, -2) == 1 / ((x - 1) * (x - 2))
    assert rf(x, -3) == 1 / ((x - 1) * (x - 2) * (x - 3))

    assert rf(1, 100) == factorial(100)

    assert rf(x ** 2 + 3 * x, 2) == (x ** 2 + 3 * x) * (x ** 2 + 3 * x + 1)
    assert isinstance(rf(x ** 2 + 3 * x, 2), Mul)
    assert rf(x ** 3 + x, -2) == 1 / ((x ** 3 + x - 1) * (x ** 3 + x - 2))

    assert rf(Poly(x ** 2 + 3 * x, x), 2) == Poly(
        x ** 4 + 8 * x ** 3 + 19 * x ** 2 + 12 * x, x
    )
    assert isinstance(rf(Poly(x ** 2 + 3 * x, x), 2), Poly)
    raises(ValueError, lambda: rf(Poly(x ** 2 + 3 * x, x, y), 2))
    assert rf(Poly(x ** 3 + x, x), -2) == 1 / (
        x ** 6 - 9 * x ** 5 + 35 * x ** 4 - 75 * x ** 3 + 94 * x ** 2 - 66 * x + 20
    )
    raises(ValueError, lambda: rf(Poly(x ** 3 + x, x, y), -2))

    assert rf(x, m).is_integer is None
    assert rf(n, k).is_integer is None
    assert rf(n, m).is_integer is True
    assert rf(n, k + pi).is_integer is False
    assert rf(n, m + pi).is_integer is False
    assert rf(pi, m).is_integer is False

    assert rf(x, k).rewrite(ff) == ff(x + k - 1, k)
    assert rf(x, k).rewrite(binomial) == factorial(k) * binomial(x + k - 1, k)
    assert rf(n, k).rewrite(factorial) == factorial(n + k - 1) / factorial(n - 1)
    assert rf(x, y).rewrite(factorial) == rf(x, y)
    assert rf(x, y).rewrite(binomial) == rf(x, y)

    import random
    from mpmath import rf as mpmath_rf

    for i in range(100):
        x = -500 + 500 * random.random()
        k = -500 + 500 * random.random()
        assert abs(mpmath_rf(x, k) - rf(x, k)) < 10 ** (-15)
コード例 #35
0
ファイル: test_products.py プロジェクト: z-campbell/sympy
def test_rational_products():
    assert product(1 + 1 / k, (k, 1, n)) == rf(2, n) / factorial(n)
コード例 #36
0
ファイル: fomular-1.py プロジェクト: zqnet/fomular-sympy
#计算结果以小数方式显示
print("exp is e sqrt x")
print(S.exp(2).evalf())

#无穷大的表示方式
print(1 + S.oo)

#求平方根
print(S.sqrt(4))

#求n次方根
print(S.root(8, 3))

#求阶乘
print(S.factorial(4))

#求三角函数
print(S.sin(S.pi / 2))

#支持多元表达式
f = 2 * x + y
print(f.evalf(subs={x: 1, y: 2}))

#解方程组
print(S.solve([x + y - 1, x - y - 3], [x, y]))

#计算求和式 :x从1到100
print(S.summation(2 * x, (x, 1, 100)))

#解求和的方程
コード例 #37
0
def inverse_laplace_ratfun(expr, s, t):

    N, D, delay = Ratfun(expr, s).as_ratfun_delay()
    # The delay should be zero

    Q, M = sym.div(N, D, s)

    result1 = sym.S.Zero

    if Q:
        Qpoly = sym.Poly(Q, s)        
        C = Qpoly.all_coeffs()
        for n, c in enumerate(C):
            result1 += c * sym.diff(sym.DiracDelta(t), t, len(C) - n - 1)

    expr = M / D
    for factor in expr.as_ordered_factors():
        if factor == sym.oo:
            return factor

    sexpr = Ratfun(expr, s)
    P = sexpr.poles()
    result2 = sym.S.Zero

    P2 = P.copy()

    for p in P2:

        # Number of occurrences of the pole.
        N = P2[p]

        if N == 0:
            continue

        f = s - p

        if N == 1:
            r = sexpr.residue(p, P)

            pc = p.conjugate()
            if pc != p and pc in P:
                # Remove conjugate from poles and process pole with its
                # conjugate.  Unfortunately, for symbolic expressions
                # we cannot tell if a quadratic has two real poles,
                # a repeat real pole, or a complex conjugate pair of poles.
                P2[pc] = 0
                
                p_re = sym.re(p)
                p_im = sym.im(p)
                r_re = sym.re(r)
                r_im = sym.im(r)
                et = sym.exp(p_re * t)
                result2 += 2 * r_re * et * sym.cos(p_im * t)
                result2 -= 2 * r_im * et * sym.sin(p_im * t)
            else:
                result2 += r * sym.exp(p * t)
            continue

        # Handle repeated poles.
        expr2 = expr * f ** N
        for n in range(1, N + 1):
            m = N - n
            r = sym.limit(
                sym.diff(expr2, s, m), s, p) / sym.factorial(m)
            result2 += r * sym.exp(p * t) * t**(n - 1)

    # result1 is a sum of Dirac deltas and its derivatives so is known
    # to be causal.

    return result1, result2
コード例 #38
0
ファイル: test_gamma_functions.py プロジェクト: ronit19/sympy
def test_gamma_rewrite():
    assert gamma(n).rewrite(factorial) == factorial(n - 1)
コード例 #39
0
def test_is_convergent():
    # divergence tests --
    assert Sum(n / (2 * n + 1), (n, 1, oo)).is_convergent() is S.false
    assert Sum(factorial(n) / 5**n, (n, 1, oo)).is_convergent() is S.false
    assert Sum(3**(-2 * n - 1) * n**n, (n, 1, oo)).is_convergent() is S.false
    assert Sum((-1)**n * n, (n, 3, oo)).is_convergent() is S.false
    assert Sum((-1)**n, (n, 1, oo)).is_convergent() is S.false
    assert Sum(log(1 / n), (n, 2, oo)).is_convergent() is S.false

    # root test --
    assert Sum((-12)**n / n, (n, 1, oo)).is_convergent() is S.false

    # integral test --

    # p-series test --
    assert Sum(1 / (n**2 + 1), (n, 1, oo)).is_convergent() is S.true
    assert Sum(1 / n**(S(6) / 5), (n, 1, oo)).is_convergent() is S.true
    assert Sum(2 / (n * sqrt(n - 1)), (n, 2, oo)).is_convergent() is S.true
    assert Sum(1 / (sqrt(n) * sqrt(n)), (n, 2, oo)).is_convergent() is S.false

    # comparison test --
    assert Sum(1 / (n + log(n)), (n, 1, oo)).is_convergent() is S.false
    assert Sum(1 / (n**2 * log(n)), (n, 2, oo)).is_convergent() is S.true
    assert Sum(1 / (n * log(n)), (n, 2, oo)).is_convergent() is S.false
    assert Sum(2 / (n * log(n) * log(log(n))**2),
               (n, 5, oo)).is_convergent() is S.true
    assert Sum(2 / (n * log(n)**2), (n, 2, oo)).is_convergent() is S.true
    assert Sum((n - 1) / (n**2 * log(n)**3),
               (n, 2, oo)).is_convergent() is S.true
    assert Sum(1 / (n * log(n) * log(log(n))),
               (n, 5, oo)).is_convergent() is S.false
    assert Sum((n - 1) / (n * log(n)**3),
               (n, 3, oo)).is_convergent() is S.false
    assert Sum(2 / (n**2 * log(n)), (n, 2, oo)).is_convergent() is S.true
    assert Sum(1 / (n * sqrt(log(n)) * log(log(n))),
               (n, 100, oo)).is_convergent() is S.false
    assert Sum(log(log(n)) / (n * log(n)**2),
               (n, 100, oo)).is_convergent() is S.true
    assert Sum(log(n) / n**2, (n, 5, oo)).is_convergent() is S.true

    # alternating series tests --
    assert Sum((-1)**(n - 1) / (n**2 - 1),
               (n, 3, oo)).is_convergent() is S.true

    # with -negativeInfinite Limits
    assert Sum(1 / (n**2 + 1), (n, -oo, 1)).is_convergent() is S.true
    assert Sum(1 / (n - 1), (n, -oo, -1)).is_convergent() is S.false
    assert Sum(1 / (n**2 - 1), (n, -oo, -5)).is_convergent() is S.true
    assert Sum(1 / (n**2 - 1), (n, -oo, 2)).is_convergent() is S.true
    assert Sum(1 / (n**2 - 1), (n, -oo, oo)).is_convergent() is S.true

    # piecewise functions
    f = Piecewise((n**(-2), n <= 1), (n**2, n > 1))
    assert Sum(f, (n, 1, oo)).is_convergent() is S.false
    assert Sum(f, (n, -oo, oo)).is_convergent() is S.false
    #assert Sum(f, (n, -oo, 1)).is_convergent() is S.true

    # integral test

    assert Sum(log(n) / n**3, (n, 1, oo)).is_convergent() is S.true
    assert Sum(-log(n) / n**3, (n, 1, oo)).is_convergent() is S.true
    # the following function has maxima located at (x, y) =
    # (1.2, 0.43), (3.0, -0.25) and (6.8, 0.050)
    eq = (x - 2) * (x**2 - 6 * x + 4) * exp(-x)
    assert Sum(eq, (x, 1, oo)).is_convergent() is S.true
コード例 #40
0
def test_issue_4171():
    assert summation(factorial(2 * k + 1) / factorial(2 * k), (k, 0, oo)) == oo
    assert summation(2 * k + 1, (k, 0, oo)) == oo
コード例 #41
0
def test_issue_4170():
    assert summation(1 / factorial(k), (k, 0, oo)) == E
コード例 #42
0
from __future__ import division
import numpy as np
from sympy import var, factorial, factorial2, sympify, diff
from sympy.printing import ccode

nmax = 30

xi = var('xi')

u = list(map(sympify, ['-(xi+1)/2 + 1', '(xi+1)/2']))

for r in range(5, nmax + 1):
    utmp = []
    for n in range(0, r // 2 + 1):
        den = 2**n * factorial(n) * factorial(r - 2 * n - 1)
        utmp.append((-1)**n * factorial2(2 * r - 2 * n - 7) / den *
                    xi**(r - 2 * n - 1) / 1.)
    u.append(sum(utmp))

with open('../../../panels/core/src/bardell_functions_uv.cpp', 'w') as f:
    f.write("// Bardell's hierarchical functions\n\n")
    f.write('// Number of terms: {0}\n\n'.format(len(u)))
    f.write('#include <stdlib.h>\n')
    f.write('#include <math.h>\n\n')
    f.write('#if defined(_WIN32) || defined(__WIN32__)\n')
    f.write('  #define EXPORTIT __declspec(dllexport)\n')
    f.write('#else\n')
    f.write('  #define EXPORTIT\n')
    f.write('#endif\n\n')
    f.write(
        'EXPORTIT void vec_fuv(double *f, double xi, double xi1t, double xi2t) {\n'
コード例 #43
0
def R_nl(n, l, r, Z=1):
    """
    Returns the Hydrogen radial wavefunction R_{nl}.

    n, l
        quantum numbers 'n' and 'l'
    r
        radial coordinate
    Z
        atomic number (1 for Hydrogen, 2 for Helium, ...)

    Everything is in Hartree atomic units.

    Examples
    ========

    >>> from sympy.physics.hydrogen import R_nl
    >>> from sympy import var
    >>> var("r Z")
    (r, Z)
    >>> R_nl(1, 0, r, Z)
    2*sqrt(Z**3)*exp(-Z*r)
    >>> R_nl(2, 0, r, Z)
    sqrt(2)*(-Z*r + 2)*sqrt(Z**3)*exp(-Z*r/2)/4
    >>> R_nl(2, 1, r, Z)
    sqrt(6)*Z*r*sqrt(Z**3)*exp(-Z*r/2)/12

    For Hydrogen atom, you can just use the default value of Z=1:

    >>> R_nl(1, 0, r)
    2*exp(-r)
    >>> R_nl(2, 0, r)
    sqrt(2)*(-r + 2)*exp(-r/2)/4
    >>> R_nl(3, 0, r)
    2*sqrt(3)*(2*r**2/9 - 2*r + 3)*exp(-r/3)/27

    For Silver atom, you would use Z=47:

    >>> R_nl(1, 0, r, Z=47)
    94*sqrt(47)*exp(-47*r)
    >>> R_nl(2, 0, r, Z=47)
    47*sqrt(94)*(-47*r + 2)*exp(-47*r/2)/4
    >>> R_nl(3, 0, r, Z=47)
    94*sqrt(141)*(4418*r**2/9 - 94*r + 3)*exp(-47*r/3)/27

    The normalization of the radial wavefunction is:

    >>> from sympy import integrate, oo
    >>> integrate(R_nl(1, 0, r)**2 * r**2, (r, 0, oo))
    1
    >>> integrate(R_nl(2, 0, r)**2 * r**2, (r, 0, oo))
    1
    >>> integrate(R_nl(2, 1, r)**2 * r**2, (r, 0, oo))
    1

    It holds for any atomic number:

    >>> integrate(R_nl(1, 0, r, Z=2)**2 * r**2, (r, 0, oo))
    1
    >>> integrate(R_nl(2, 0, r, Z=3)**2 * r**2, (r, 0, oo))
    1
    >>> integrate(R_nl(2, 1, r, Z=4)**2 * r**2, (r, 0, oo))
    1

    """
    # sympify arguments
    n, l, r, Z = S(n), S(l), S(r), S(Z)
    # radial quantum number
    n_r = n - l - 1
    # rescaled "r"
    a = 1/Z  # Bohr radius
    r0 = 2 * r / (n * a)
    # normalization coefficient
    C = sqrt((S(2)/(n*a))**3 * factorial(n_r) / (2*n*factorial(n + l)))
    # This is an equivalent normalization coefficient, that can be found in
    # some books. Both coefficients seem to be the same fast:
    # C =  S(2)/n**2 * sqrt(1/a**3 * factorial(n_r) / (factorial(n+l)))
    return C * r0**l * assoc_laguerre(n_r, 2*l + 1, r0).expand() * exp(-r0/2)
コード例 #44
0
 def pdf(self, *x):
     n, p = self.n, self.p
     term_1 = factorial(n)/Mul.fromiter([factorial(x_k) for x_k in x])
     term_2 = Mul.fromiter([p_k**x_k for p_k, x_k in zip(p, x)])
     return Piecewise((term_1 * term_2, Eq(sum(x), n)), (0, True))
コード例 #45
0
 def __call__(self, h):
     """Return the truncated Taylor series at x+h."""
     terms = self.f
     for i in range(1, self.N + 1):
         terms += sym.Rational(1, sym.factorial(i)) * self.df[i] * h**i
     return terms
コード例 #46
0
ファイル: test_gamma_functions.py プロジェクト: ronit19/sympy
def test_polygamma():
    from sympy import I

    assert polygamma(n, nan) == nan

    assert polygamma(0, oo) == oo
    assert polygamma(0, -oo) == oo
    assert polygamma(0, I*oo) == oo
    assert polygamma(0, -I*oo) == oo
    assert polygamma(1, oo) == 0
    assert polygamma(5, oo) == 0

    assert polygamma(0, -9) == zoo

    assert polygamma(0, -9) == zoo
    assert polygamma(0, -1) == zoo

    assert polygamma(0, 0) == zoo

    assert polygamma(0, 1) == -EulerGamma
    assert polygamma(0, 7) == Rational(49, 20) - EulerGamma

    assert polygamma(1, 1) == pi**2/6
    assert polygamma(1, 2) == pi**2/6 - 1
    assert polygamma(1, 3) == pi**2/6 - Rational(5, 4)
    assert polygamma(3, 1) == pi**4 / 15
    assert polygamma(3, 5) == 6*(Rational(-22369, 20736) + pi**4/90)
    assert polygamma(5, 1) == 8 * pi**6 / 63

    def t(m, n):
        x = S(m)/n
        r = polygamma(0, x)
        if r.has(polygamma):
            return False
        return abs(polygamma(0, x.n()).n() - r.n()).n() < 1e-10
    assert t(1, 2)
    assert t(3, 2)
    assert t(-1, 2)
    assert t(1, 4)
    assert t(-3, 4)
    assert t(1, 3)
    assert t(4, 3)
    assert t(3, 4)
    assert t(2, 3)
    assert t(123, 5)

    assert polygamma(0, x).rewrite(zeta) == polygamma(0, x)
    assert polygamma(1, x).rewrite(zeta) == zeta(2, x)
    assert polygamma(2, x).rewrite(zeta) == -2*zeta(3, x)
    assert polygamma(I, 2).rewrite(zeta) == polygamma(I, 2)
    n1 = Symbol('n1')
    n2 = Symbol('n2', real=True)
    n3 = Symbol('n3', integer=True)
    n4 = Symbol('n4', positive=True)
    n5 = Symbol('n5', positive=True, integer=True)
    assert polygamma(n1, x).rewrite(zeta) == polygamma(n1, x)
    assert polygamma(n2, x).rewrite(zeta) == polygamma(n2, x)
    assert polygamma(n3, x).rewrite(zeta) == polygamma(n3, x)
    assert polygamma(n4, x).rewrite(zeta) == polygamma(n4, x)
    assert polygamma(n5, x).rewrite(zeta) == (-1)**(n5 + 1) * factorial(n5) * zeta(n5 + 1, x)

    assert polygamma(3, 7*x).diff(x) == 7*polygamma(4, 7*x)

    assert polygamma(0, x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma
    assert polygamma(2, x).rewrite(harmonic) == 2*harmonic(x - 1, 3) - 2*zeta(3)
    ni = Symbol("n", integer=True)
    assert polygamma(ni, x).rewrite(harmonic) == (-1)**(ni + 1)*(-harmonic(x - 1, ni + 1)
                                                                 + zeta(ni + 1))*factorial(ni)

    # Polygamma of non-negative integer order is unbranched:
    from sympy import exp_polar
    k = Symbol('n', integer=True, nonnegative=True)
    assert polygamma(k, exp_polar(2*I*pi)*x) == polygamma(k, x)

    # but negative integers are branched!
    k = Symbol('n', integer=True)
    assert polygamma(k, exp_polar(2*I*pi)*x).args == (k, exp_polar(2*I*pi)*x)

    # Polygamma of order -1 is loggamma:
    assert polygamma(-1, x) == loggamma(x)

    # But smaller orders are iterated integrals and don't have a special name
    assert polygamma(-2, x).func is polygamma

    # Test a bug
    assert polygamma(0, -x).expand(func=True) == polygamma(0, -x)

    assert polygamma(2, 2.5).is_positive == False
    assert polygamma(2, -2.5).is_positive == False
    assert polygamma(3, 2.5).is_positive == True
    assert polygamma(3, -2.5).is_positive is None
    assert polygamma(-2, -2.5).is_positive is None
    assert polygamma(-3, -2.5).is_positive is None

    assert polygamma(2, 2.5).is_negative == True
    assert polygamma(3, 2.5).is_negative == False
    assert polygamma(3, -2.5).is_negative == False
    assert polygamma(2, -2.5).is_negative is None
    assert polygamma(-2, -2.5).is_negative is None
    assert polygamma(-3, -2.5).is_negative is None

    assert polygamma(I, 2).is_positive is None
    assert polygamma(I, 3).is_negative is None

    # issue 17350
    assert polygamma(pi, 3).evalf() == polygamma(pi, 3)
    assert (I*polygamma(I, pi)).as_real_imag() == \
           (-im(polygamma(I, pi)), re(polygamma(I, pi)))
    assert (tanh(polygamma(I, 1))).rewrite(exp) == \
           (exp(polygamma(I, 1)) - exp(-polygamma(I, 1)))/(exp(polygamma(I, 1)) + exp(-polygamma(I, 1)))
    assert (I / polygamma(I, 4)).rewrite(exp) == \
           I*sqrt(re(polygamma(I, 4))**2 + im(polygamma(I, 4))**2)\
           /((re(polygamma(I, 4)) + I*im(polygamma(I, 4)))*Abs(polygamma(I, 4)))
    assert unchanged(polygamma, 2.3, 1.0)

    # issue 12569
    assert unchanged(im, polygamma(0, I))
    assert polygamma(Symbol('a', positive=True), Symbol('b', positive=True)).is_real is True
    assert polygamma(0, I).is_real is None
コード例 #47
0
def compute_fdcoeffs_fdstencl(derivstring, FDORDER=-1):
    # Step 0: Set finite differencing order, stencil size, and up/downwinding
    if FDORDER == -1:
        FDORDER = par.parval_from_str("FD_CENTDERIVS_ORDER")
        if "dKOD" in derivstring:
            FDORDER += par.parval_from_str("FD_KO_ORDER__CENTDERIVS_PLUS")

    STENCILSIZE = FDORDER + 1
    UPDOWNWIND_stencil_shift = 0
    # dup/dnD = single-point-offset upwind/downwinding.
    if "dupD" in derivstring:
        UPDOWNWIND_stencil_shift = 1
    elif "ddnD" in derivstring:
        UPDOWNWIND_stencil_shift = -1
    # dfullup/dnD = full upwind/downwinding.
    elif "dfullupD" in derivstring:
        UPDOWNWIND_stencil_shift = int(FDORDER / 2)
    elif "dfulldnD" in derivstring:
        UPDOWNWIND_stencil_shift = -int(FDORDER / 2)

    # Step 1: Set up matrix based on the stencil size (FDORDER+1).
    #         See documentation above for details on how this
    #         matrix is set up.
    M = sp.zeros(STENCILSIZE, STENCILSIZE)
    for i in range(STENCILSIZE):
        for j in range(STENCILSIZE):
            if i == 0:
                M[(
                    i, j
                )] = 1  # Setting n^0 = 1 for all n, including n=0, because this matches the pattern
            else:
                dist_from_xeq0_col = j - sp.Rational(
                    (STENCILSIZE - 1), 2) + UPDOWNWIND_stencil_shift
                if dist_from_xeq0_col == 0:
                    M[(i, j)] = 0
                else:
                    M[(i, j)] = dist_from_xeq0_col**(i)
    Minv = sp.zeros(STENCILSIZE, STENCILSIZE)
    Minv = M**(-1)

    # Step 2:
    #     Based on the input derivative string,
    #     pick out the relevant row of the matrix
    #     inverse, as outlined in the detailed code
    #     comments prior to this function definition.
    derivtype = "FirstDeriv"
    matrixrow = 1
    if "DDD" in derivstring:
        print(
            "Error: Only derivatives up to second order currently supported.")
        print(
            "       Feel free to contribute to NRPy+ to extend its functionality!"
        )
        sys.exit(1)
    elif "DD" in derivstring:

        if derivstring[len(derivstring) - 1] == derivstring[len(derivstring) -
                                                            2]:
            # Assuming i==j, we call \partial_i \partial_j gf an "unmixed" second derivative,
            #     or more simply, just "SecondDeriv":
            derivtype = "SecondDeriv"
            matrixrow = 2
        else:
            # Assuming i!=j, we call \partial_i \partial_j gf a MIXED second derivative,
            #     which is computed using a composite of first derivative operations.
            derivtype = "MixedSecondDeriv"
    elif "dKOD" in derivstring:
        derivtype = "KreissOligerDeriv"
        matrixrow = STENCILSIZE - 1
    else:
        # Up/downwinded and first derivs are all of "FirstDeriv" type
        pass

    # Step 3:
    #     Set finite difference coefficients
    #     and stencil points corresponding to
    #     each finite difference coefficient.
    fdcoeffs = []
    fdstencl = []
    if derivtype != "MixedSecondDeriv":
        for i in range(STENCILSIZE):
            idx4 = [0, 0, 0, 0]
            # First compute finite difference coefficient.
            fdcoeff = sp.factorial(matrixrow) * Minv[(i, matrixrow)]
            # Do not store fdcoeff or fdstencil if
            # finite difference coefficient is zero.
            if fdcoeff != 0:
                fdcoeffs.append(fdcoeff)
                if derivtype == "KreissOligerDeriv":
                    fdcoeffs[i] *= (-1)**(sp.Rational(
                        (STENCILSIZE + 1), 2)) / 2**matrixrow

                # Next store finite difference stencil point
                # corresponding to coefficient.
                gridpt_posn = i - int(
                    (STENCILSIZE - 1) / 2) + UPDOWNWIND_stencil_shift
                if gridpt_posn != 0:
                    dirn = int(derivstring[len(derivstring) - 1])
                    idx4[dirn] = gridpt_posn
                fdstencl.append(idx4)
    else:
        # Mixed second derivative finite difference coeffs
        #     consist of products of first deriv coeffs,
        #     defined in first Minv matrix row.
        for i in range(STENCILSIZE):
            for j in range(STENCILSIZE):
                idx4 = [0, 0, 0, 0]

                # First compute finite difference coefficient.
                fdcoeff = (sp.factorial(matrixrow)*Minv[(i,matrixrow)]) * \
                          (sp.factorial(matrixrow)*Minv[(j,matrixrow)])

                # Do not store fdcoeff or fdstencil if
                # finite difference coefficient is zero.
                if fdcoeff != 0:
                    fdcoeffs.append(fdcoeff)

                    # Next store finite difference stencil point
                    # corresponding to coefficient.
                    gridpt_posn1 = i - int((STENCILSIZE - 1) / 2)
                    gridpt_posn2 = j - int((STENCILSIZE - 1) / 2)
                    dirn1 = int(derivstring[len(derivstring) - 1])
                    dirn2 = int(derivstring[len(derivstring) - 2])
                    idx4[dirn1] = gridpt_posn1
                    idx4[dirn2] = gridpt_posn2
                    fdstencl.append(idx4)
    return fdcoeffs, fdstencl
コード例 #48
0
ファイル: test_gamma_functions.py プロジェクト: ronit19/sympy
def test_gamma():
    assert gamma(nan) == nan
    assert gamma(oo) == oo

    assert gamma(-100) == zoo
    assert gamma(0) == zoo
    assert gamma(-100.0) == zoo

    assert gamma(1) == 1
    assert gamma(2) == 1
    assert gamma(3) == 2

    assert gamma(102) == factorial(101)

    assert gamma(Rational(1, 2)) == sqrt(pi)

    assert gamma(Rational(3, 2)) == Rational(1, 2)*sqrt(pi)
    assert gamma(Rational(5, 2)) == Rational(3, 4)*sqrt(pi)
    assert gamma(Rational(7, 2)) == Rational(15, 8)*sqrt(pi)

    assert gamma(Rational(-1, 2)) == -2*sqrt(pi)
    assert gamma(Rational(-3, 2)) == Rational(4, 3)*sqrt(pi)
    assert gamma(Rational(-5, 2)) == -Rational(8, 15)*sqrt(pi)

    assert gamma(Rational(-15, 2)) == Rational(256, 2027025)*sqrt(pi)

    assert gamma(Rational(
        -11, 8)).expand(func=True) == Rational(64, 33)*gamma(Rational(5, 8))
    assert gamma(Rational(
        -10, 3)).expand(func=True) == Rational(81, 280)*gamma(Rational(2, 3))
    assert gamma(Rational(
        14, 3)).expand(func=True) == Rational(880, 81)*gamma(Rational(2, 3))
    assert gamma(Rational(
        17, 7)).expand(func=True) == Rational(30, 49)*gamma(Rational(3, 7))
    assert gamma(Rational(
        19, 8)).expand(func=True) == Rational(33, 64)*gamma(Rational(3, 8))

    assert gamma(x).diff(x) == gamma(x)*polygamma(0, x)

    assert gamma(x - 1).expand(func=True) == gamma(x)/(x - 1)
    assert gamma(x + 2).expand(func=True, mul=False) == x*(x + 1)*gamma(x)

    assert conjugate(gamma(x)) == gamma(conjugate(x))

    assert expand_func(gamma(x + Rational(3, 2))) == \
        (x + Rational(1, 2))*gamma(x + Rational(1, 2))

    assert expand_func(gamma(x - Rational(1, 2))) == \
        gamma(Rational(1, 2) + x)/(x - Rational(1, 2))

    # Test a bug:
    assert expand_func(gamma(x + Rational(3, 4))) == gamma(x + Rational(3, 4))

    # XXX: Not sure about these tests. I can fix them by defining e.g.
    # exp_polar.is_integer but I'm not sure if that makes sense.
    assert gamma(3*exp_polar(I*pi)/4).is_nonnegative is False
    assert gamma(3*exp_polar(I*pi)/4).is_extended_nonpositive is True

    y = Symbol('y', nonpositive=True, integer=True)
    assert gamma(y).is_real == False
    y = Symbol('y', positive=True, noninteger=True)
    assert gamma(y).is_real == True

    assert gamma(-1.0, evaluate=False).is_real == False
    assert gamma(0, evaluate=False).is_real == False
    assert gamma(-2, evaluate=False).is_real == False
コード例 #49
0
ファイル: test_products.py プロジェクト: z-campbell/sympy
def test_infinite_product():
    # issue 5737
    assert isinstance(Product(2**(1 / factorial(n)), (n, 0, oo)), Product)
コード例 #50
0
def test_rsolve():
    f = y(n + 2) - y(n + 1) - y(n)
    h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \
      - sqrt(5)*(S.Half - S.Half*sqrt(5))**n

    assert rsolve(f, y(n)) in [
        C0 * (S.Half - S.Half * sqrt(5))**n + C1 *
        (S.Half + S.Half * sqrt(5))**n,
        C1 * (S.Half - S.Half * sqrt(5))**n + C0 *
        (S.Half + S.Half * sqrt(5))**n,
    ]

    assert rsolve(f, y(n), [0, 5]) == h
    assert rsolve(f, y(n), {0: 0, 1: 5}) == h
    assert rsolve(f, y(n), {y(0): 0, y(1): 5}) == h
    assert rsolve(y(n) - y(n - 1) - y(n - 2), y(n), [0, 5]) == h
    assert rsolve(Eq(y(n), y(n - 1) + y(n - 2)), y(n), [0, 5]) == h

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = (n - 1) * y(n + 2) - (n**2 + 3 * n - 2) * y(n + 1) + 2 * n * (n +
                                                                      1) * y(n)
    g = C1 * factorial(n) + C0 * 2**n
    h = -3 * factorial(n) + 3 * 2**n

    assert rsolve(f, y(n)) == g
    assert rsolve(f, y(n), []) == g
    assert rsolve(f, y(n), {}) == g

    assert rsolve(f, y(n), [0, 3]) == h
    assert rsolve(f, y(n), {0: 0, 1: 3}) == h
    assert rsolve(f, y(n), {y(0): 0, y(1): 3}) == h

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = y(n) - y(n - 1) - 2

    assert rsolve(f, y(n), {y(0): 0}) == 2 * n
    assert rsolve(f, y(n), {y(0): 1}) == 2 * n + 1
    assert rsolve(f, y(n), {y(0): 0, y(1): 1}) == None

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = 3 * y(n - 1) - y(n) - 1

    assert rsolve(f, y(n), {y(0): 0}) == -3**n / 2 + S.Half
    assert rsolve(f, y(n), {y(0): 1}) == 3**n / 2 + S.Half
    assert rsolve(f, y(n), {y(0): 2}) == 3 * 3**n / 2 + S.Half

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = y(n) - 1 / n * y(n - 1)
    assert rsolve(f, y(n)) == C0 / factorial(n)
    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = y(n) - 1 / n * y(n - 1) - 1
    assert rsolve(f, y(n)) == None

    f = 2 * y(n - 1) + (1 - n) * y(n) / n

    assert rsolve(f, y(n), {y(1): 1}) == 2**(n - 1) * n
    assert rsolve(f, y(n), {y(1): 2}) == 2**(n - 1) * n * 2
    assert rsolve(f, y(n), {y(1): 3}) == 2**(n - 1) * n * 3

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = (n - 1) * (n - 2) * y(n + 2) - (n + 1) * (n + 2) * y(n)

    assert rsolve(f, y(n), {y(3): 6, y(4): 24}) == n * (n - 1) * (n - 2)
    assert rsolve(f, y(n), {
        y(3): 6,
        y(4): -24
    }) == n * (n - 1) * (n - 2) * (-1)**(3 - n)

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
コード例 #51
0
ファイル: test_sums_products.py プロジェクト: vperic/sympy
def test_issue_1072():
    k = Symbol("k")
    assert summation(factorial(2 * k + 1) / factorial(2 * k), (k, 0, oo)) == oo
コード例 #52
0
ファイル: 180401026_hw_3.py プロジェクト: berayboztepe/Python
num = 180401026
l = Symbol(
    'lambda')  #verilen sabit aralıkta ortaya çıkma sayısının beklenen değeri
k = Symbol('k')  #istenen olasılık adedi

mod = sym.Mod(num, 4)  #sympy kütüphanesinde mod almak için kullanılır
#print(mod)

#Poisson_Distrubution olduğu anlamına gelir.
#Possion Dağılımı = Belli bir sabit zaman birim aralığında meydana gelme sayısının olasılığını ifade eder.Nadir gerçekleşen olaylar için kullanılır.
#örnek olarak bir internet sitesine 2 saatte tıklanma sayısı 6 olsun.
#k = 6, lambda = 2

poissoneq = ((l**k) * (sym.exp(-l))) / sym.factorial(
    k
)  #formülün bulunması. exp = e üzeri demek. factorial ile faktoryel aldık.
print("Formul aşağıdaki gibidir...\n")
pprint(poissoneq)  #formülün yazılması


#sympy ile grafik
def sympy_graph():
    sym.plot(poissoneq.subs({l: 2}), (k, 0, 6),
             title='Poisson Distrubition')  #0-6 arası gözüküyor


#matplotlib ile grafik
def matlib_graph():
    x__values = []
    y__values = []
コード例 #53
0
def test_factorial_series():
    n = Symbol("n", integer=True)

    assert factorial(n).series(n, 0, 3) == 1 - n * EulerGamma + n ** 2 * (
        EulerGamma ** 2 / 2 + pi ** 2 / 12
    ) + O(n ** 3)
コード例 #54
0
ファイル: test_latex.py プロジェクト: skolwind/sympy
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(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

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

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

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

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

    # Test latex printing of function names with "_"
    assert latex(
        polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(0)**
                 3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"
コード例 #55
0
def test_factorial():
    x = Symbol("x")
    n = Symbol("n", integer=True)
    k = Symbol("k", integer=True, nonnegative=True)
    r = Symbol("r", integer=False)
    s = Symbol("s", integer=False, negative=True)
    t = Symbol("t", nonnegative=True)
    u = Symbol("u", noninteger=True)

    assert factorial(-2) is zoo
    assert factorial(0) == 1
    assert factorial(7) == 5040
    assert factorial(19) == 121645100408832000
    assert factorial(31) == 8222838654177922817725562880000000
    assert factorial(n).func == factorial
    assert factorial(2 * n).func == factorial

    assert factorial(x).is_integer is None
    assert factorial(n).is_integer is None
    assert factorial(k).is_integer
    assert factorial(r).is_integer is None

    assert factorial(n).is_positive is None
    assert factorial(k).is_positive

    assert factorial(x).is_real is None
    assert factorial(n).is_real is None
    assert factorial(k).is_real is True
    assert factorial(r).is_real is None
    assert factorial(s).is_real is True
    assert factorial(t).is_real is True
    assert factorial(u).is_real is True

    assert factorial(x).is_composite is None
    assert factorial(n).is_composite is None
    assert factorial(k).is_composite is None
    assert factorial(k + 3).is_composite is True
    assert factorial(r).is_composite is None
    assert factorial(s).is_composite is None
    assert factorial(t).is_composite is None
    assert factorial(u).is_composite is None

    assert factorial(oo) is oo
コード例 #56
0
def drive_scale_exact(dim, L):
    L = sym.S(L)
    return sym.sqrt(2*L+1) * sym.factorial(L) / sym.factorial(2*L+1) * \
           sym.sqrt(np.prod([ dim + l for l in range(-L,L+1) ]))
コード例 #57
0
import sympy as sp
from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
from sympy.tensor.tensor import TensorIndex, tensor_indices, TensorIndexType

eps = LorentzIndex.epsilon
i0,i1,i2,i3,i4,i5 = tensor_indices('i_0:6', LorentzIndex)
G5 = 1j/ sp.factorial(4) * eps(-i0, -i1, -i2, -i3) * G(i0) * G(i1) * G(i2) * G(i3) 
print(G5)
コード例 #58
0
"""
    Barış KOL 180401073
    Github : https://github.com/baris-kol/ProgramlamaLab
"""
import sympy as sym
from sympy import Symbol
from sympy import pprint

p = Symbol('p')
x = Symbol('x')
n = Symbol('n')

my_f_3_part_0 = sym.factorial(n) / (sym.factorial(x) * sym.factorial(n - x))
pprint(my_f_3_part_0)

my_f_3_part_1 = p**x
pprint(my_f_3_part_1)

my_f_3_part_2 = (1 - p)**(n - x)
pprint(my_f_3_part_2)

my_f_3 = my_f_3_part_0 * my_f_3_part_1 * my_f_3_part_2
pprint(my_f_3)

sym.plot(my_f_3.subs({
    p: 0.5,
    n: 50
}), (x, 0, 50),
         title='Binomial Distribution Plot For n=50')

########### LİMİT week3_Lesson1 ##################
コード例 #59
0
ファイル: test_theanocode.py プロジェクト: ushukkla/sympy
def test_factorial():
    n = sy.Symbol('n')
    assert theano_code_(sy.factorial(n))
コード例 #60
0
 def pdf(self, *k):
     k0, p = self.k0, self.p
     term_1 = (gamma(k0 + sum(k))*(1 - sum(p))**k0)/gamma(k0)
     term_2 = Mul.fromiter([pi**ki/factorial(ki) for pi, ki in zip(p, k)])
     return term_1 * term_2