Пример #1
0
def test_derivative_subs2():
    x, y, z = symbols('x y z')
    f, g = symbols('f g', cls=Function)
    assert Derivative(f, x, y).subs(Derivative(f, x, y), g) == g
    assert Derivative(f, y, x).subs(Derivative(f, x, y), g) == g
    assert Derivative(f, x, y).subs(Derivative(f, x), g) == Derivative(g, y)
    assert Derivative(f, x, y).subs(Derivative(f, y), g) == Derivative(g, x)
    assert (Derivative(f(x, y, z), x, y, z).subs(Derivative(f(x, y, z), x, z),
                                                 g) == Derivative(g, y))
    assert (Derivative(f(x, y, z), x, y, z).subs(Derivative(f(x, y, z), z, y),
                                                 g) == Derivative(g, x))
    assert (Derivative(f(x, y, z), x, y,
                       z).subs(Derivative(f(x, y, z), z, y, x), g) == g)
Пример #2
0
def test_issue_12996():
    # foo=True imitates the sort of arguments that Derivative can get
    # from Integral when it passes doit to the expression
    assert Derivative(im(x), x).doit(foo=True) == Derivative(im(x), x)
Пример #3
0
 def _eval_derivative(self, symbol):
     new_expr = Derivative(self.expr, symbol)
     return DifferentialOperator(new_expr, self.args[-1])
Пример #4
0
def test_derivative_numerically():
    from random import random
    z0 = random() + I * random()
    assert abs(Derivative(sin(x), x).doit_numerically(z0) - cos(z0)) < 1e-15
Пример #5
0
def test_subs_in_derivative():
    expr = sin(x * exp(y))
    u = Function('u')
    v = Function('v')
    assert Derivative(expr, y).subs(expr, y) == Derivative(y, y)
    assert Derivative(expr, y).subs(y, x).doit() == \
        Derivative(expr, y).doit().subs(y, x)
    assert Derivative(f(x, y), y).subs(y, x) == Subs(Derivative(f(x, y), y), y,
                                                     x)
    assert Derivative(f(x, y), y).subs(x, y) == Subs(Derivative(f(x, y), y), x,
                                                     y)
    assert Derivative(f(x, y),
                      y).subs(y, g(x, y)) == Subs(Derivative(f(x, y), y), y,
                                                  g(x, y)).doit()
    assert Derivative(f(x, y),
                      y).subs(x, g(x, y)) == Subs(Derivative(f(x, y), y), x,
                                                  g(x, y))
    assert Derivative(f(x, y),
                      g(y)).subs(x, g(x,
                                      y)) == Derivative(f(g(x, y), y), g(y))
    assert Derivative(f(u(x), h(y)), h(y)).subs(h(y), g(x, y)) == \
        Subs(Derivative(f(u(x), h(y)), h(y)), h(y), g(x, y)).doit()
    assert Derivative(f(x, y), y).subs(y, z) == Derivative(f(x, z), z)
    assert Derivative(f(x, y), y).subs(y, g(y)) == Derivative(f(x, g(y)), g(y))
    assert Derivative(f(g(x), h(y)), h(y)).subs(h(y), u(y)) == \
        Derivative(f(g(x), u(y)), u(y))
    assert Derivative(f(x, f(x, x)), f(x, x)).subs(f, Lambda(
        (x, y), x + y)) == Subs(Derivative(z + x, z), z, 2 * x)
    assert Subs(Derivative(f(f(x)), x), f, cos).doit() == sin(x) * sin(cos(x))
    assert Subs(Derivative(f(f(x)), f(x)), f, cos).doit() == -sin(cos(x))
    # Issue 13791. No comparison (it's a long formula) but this used to raise an exception.
    assert isinstance(v(x, y, u(x, y)).diff(y).diff(x).diff(y), Expr)
    # This is also related to issues 13791 and 13795; issue 15190
    F = Lambda((x, y), exp(2 * x + 3 * y))
    abstract = f(x, f(x, x)).diff(x, 2)
    concrete = F(x, F(x, x)).diff(x, 2)
    assert (abstract.subs(f, F).doit() - concrete).simplify() == 0
    # don't introduce a new symbol if not necessary
    assert x in f(x).diff(x).subs(x, 0).atoms()
    # case (4)
    assert Derivative(f(x, f(x, y)), x,
                      y).subs(x, g(y)) == Subs(Derivative(f(x, f(x, y)), x, y),
                                               x, g(y))

    assert Derivative(f(x, x), x).subs(x, 0) == Subs(Derivative(f(x, x), x), x,
                                                     0)
    # issue 15194
    assert Derivative(f(y, g(x)),
                      (x, z)).subs(z, x) == Derivative(f(y, g(x)), (x, x))

    df = f(x).diff(x)
    assert df.subs(df, 1) is S.One
    assert df.diff(df) is S.One
    dxy = Derivative(f(x, y), x, y)
    dyx = Derivative(f(x, y), y, x)
    assert dxy.subs(Derivative(f(x, y), y, x), 1) is S.One
    assert dxy.diff(dyx) is S.One
    assert Derivative(f(x, y), x, 2, y,
                      3).subs(dyx, g(x, y)) == Derivative(g(x, y), x, 1, y, 2)
    assert Derivative(f(x, x - y),
                      y).subs(x, x + y) == Subs(Derivative(f(x, x - y), y), x,
                                                x + y)
Пример #6
0
def test_issue_15084_13166():
    eq = f(x, g(x))
    assert eq.diff((g(x), y)) == Derivative(f(x, g(x)), (g(x), y))
    # issue 13166
    assert eq.diff(
        x,
        2).doit() == ((Derivative(f(x, g(x)),
                                  (g(x), 2)) * Derivative(g(x), x) +
                       Subs(Derivative(f(x, _xi_2), _xi_2, x), _xi_2, g(x))) *
                      Derivative(g(x), x) +
                      Derivative(f(x, g(x)), g(x)) * Derivative(g(x), (x, 2)) +
                      Derivative(g(x), x) *
                      Subs(Derivative(f(_xi_1, g(x)), _xi_1, g(x)), _xi_1, x) +
                      Subs(Derivative(f(_xi_1, g(x)), (_xi_1, 2)), _xi_1, x))
    # issue 6681
    assert diff(f(x, t, g(x, t)), x).doit() == (
        Derivative(f(x, t, g(x, t)), g(x, t)) * Derivative(g(x, t), x) +
        Subs(Derivative(f(_xi_1, t, g(x, t)), _xi_1), _xi_1, x))
    # make sure the order doesn't matter when using diff
    assert eq.diff(x, g(x)) == eq.diff(g(x), x)
Пример #7
0
def test_doitdoit():
    done = Derivative(f(x, g(x)), x, g(x)).doit()
    assert done == done.doit()
Пример #8
0
def get_cumulant(xn, yn, zn):
    """
    :param xn: order of x-nth cumulant
    :param yn:
    :param zn:
    :return: cumulant_xn_yn_zn

    Order cumulant's subterms: xn + yn + zn
    ex 5th order = m012*m020
    """

    x, y, z = symbols('x y z')
    F = Function('F')(x, y, z)

    mgf = ln(F)
    deriv = Derivative(mgf, (x, xn), (y, yn), (z, zn))

    all_terms = deriv.doit()
    all_terms = all_terms * F  # Geier: C = c * m000

    all_terms = simplify(all_terms)

    # result = collect(result, F)  # Thank you sympy:  NotImplementedError: Improve MV Derivative support in collect
    # so lets start from highest (2,2,2) ...

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 2), (y, 2), (z, 2)): Symbol('m_{222}'),
    })

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 1), (y, 2), (z, 2)): Symbol('m_{122}'),
        sym.Derivative(F, (x, 2), (y, 1), (z, 2)): Symbol('m_{212}'),
        sym.Derivative(F, (x, 2), (y, 2), (z, 1)): Symbol('m_{221}'),
    })

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 0), (y, 2), (z, 2)): Symbol('m_{022}'),
        sym.Derivative(F, (x, 2), (y, 0), (z, 2)): Symbol('m_{202}'),
        sym.Derivative(F, (x, 2), (y, 2), (z, 0)): Symbol('m_{220}'),
        sym.Derivative(F, (x, 2), (y, 1), (z, 1)): Symbol('m_{211}'),
        sym.Derivative(F, (x, 1), (y, 2), (z, 1)): Symbol('m_{121}'),
        sym.Derivative(F, (x, 1), (y, 1), (z, 2)): Symbol('m_{112}'),
    })

    pretty_dict = {
        sym.Derivative(F, (x, 2), (y, 1), (z, 0)): Symbol('m_{210}'),
        sym.Derivative(F, (x, 1), (y, 2), (z, 0)): Symbol('m_{120}'),

        sym.Derivative(F, (x, 1), (y, 1), (z, 1)): Symbol('m_{111}'),

        sym.Derivative(F, (x, 0), (y, 1), (z, 2)): Symbol('m_{012}'),
        sym.Derivative(F, (x, 0), (y, 2), (z, 1)): Symbol('m_{021}'),

        sym.Derivative(F, (x, 1), (y, 0), (z, 2)): Symbol('m_{102}'),
        sym.Derivative(F, (x, 2), (y, 0), (z, 1)): Symbol('m_{201}'),
    }
    all_terms = all_terms.subs(pretty_dict)

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 2)): Symbol('m_{200}'),
        sym.Derivative(F, (y, 2)): Symbol('m_{020}'),
        sym.Derivative(F, (z, 2)): Symbol('m_{002}'),
        sym.Derivative(F, (x, 1), (y, 1), (z, 0)): Symbol('m_{110}'),
        sym.Derivative(F, (x, 1), (y, 0), (z, 1)): Symbol('m_{101}'),
        sym.Derivative(F, (x, 0), (y, 1), (z, 1)): Symbol('m_{011}'),
    })

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 1)): Symbol('m_{100}'),
        sym.Derivative(F, (y, 1)): Symbol('m_{010}'),
        sym.Derivative(F, (z, 1)): Symbol('m_{001}'),
        F: Symbol('m_{000}'),
    })

    # all_terms = collect(all_terms, Symbol('m_{100}'))  # does nothing
    all_terms = Poly(all_terms, F).all_terms()
    all_terms = sum(F ** n * term for (n,), term in all_terms)

    # order = 4
    # given_order_terms = sum(F ** n * term for (n,), term in all_terms if n <= order)
    # given_order_terms_inv = sum(F ** (-n) * term for (n,), term in all_terms if n <= order)

    all_terms = simplify(all_terms)  # does nothing agan

    lower_m000_terms = []
    # # PYDEVD_USE_FRAME_EVAL = NO
    for term in all_terms.args:
        # may crash in debug session... sympy - thank you again
        ht = Symbol('m_{000}')
        higher_terms = [ht**(-2), ht**(-3), ht**(-4)]
        is_lower_order = not any(elem in higher_terms for elem in term.args)
        if is_lower_order:
            lower_m000_terms.append(term)
            # pprint(term)
        # print("------------------------")

    # Wolfram Alpha  - Derivatives of Abstract Functions
    # d^2/(dy*dx)(log(f(x,y)))
    return all_terms, lower_m000_terms
from sympy.abc import t, g, k
from sympy import sqrt, Function, Derivative, dsolve

if __name__ == '__main__':
    x, y = map(Function, 'xy')
    dx = Derivative(x(t), t)
    dy = Derivative(y(t), t)
    eq1 = dx+k*x(t)/sqrt(x(t)+y(t))
    eq2 = dy+k*y(t)/sqrt(x(t)+y(t))
    s = dsolve((eq1, eq2))
    print(s)
Пример #10
0
"kod za resavanje sistema ODE sa razdvajanjem promenljivih"
import numpy as np
import sympy
from sympy import *
from sympy.abc import *
from sympy.plotting import plot
#from scipy import integrate
#import matplotlib.pyplot as plt
from sympy import init_printing
init_printing()
from sympy import Function, Indexed, Tuple, sqrt, dsolve, solve, Eq, Derivative, sin, cos, symbols
from sympy.abc import h, t, o, d, i
from sympy import solve, Poly, Eq, Function, exp
"zbog biblioteke sympy.abc rho00=x rho01=y rho10=z i rho11=w"
from sympy.abc import x, y, z, w
#f = Function('f')
from sympy import Indexed, IndexedBase, Tuple, sqrt
from IPython.display import display
init_printing()

h, t, o, d, i = symbols("h t o d i")
x, y, z, w = symbols("x y z w", cls=Function, Function=True)
eq1 = Eq(Derivative(x(t), t), x(t) - i * (o * y(t) / 2 - o * z(t) / 2))
eq2 = Eq(Derivative(y(t), t),
         -y(t) - i * (-d * y(t) + o * x(t) / 2 - o * w(t) / 2))
eq3 = Eq(Derivative(z(t), t),
         -z(t) - i * (d * z(t) - o * x(t) / 2 + o * w(t) / 2))
eq4 = Eq(Derivative(w(t), t), -w(t) - i * (-o * y(t) / 2 + o * z(t) / 2))
#constants = solve((soln[0].subs(t,0).subs(y(0),0), soln[0].subs(t,0).subs(z(0),0), soln[0].subs(t,0).subs(w(0),0)),{C1,C2,C3})
soln = dsolve((eq1, eq2, eq3, eq4), ics={x(0): 1, y(0): 0, z(0): 0, w(0): 0})
display(soln)
Пример #11
0
from sympy import pprint, Symbol, Derivative, Integral

x = Symbol('x')

f_of_x = x**2
print("f_of_x:")
pprint(f_of_x)

print("--------------------")

derivative_f_of_x = Derivative(f_of_x, x)
print("derivative_f_of_x:")
pprint(derivative_f_of_x)

print("--------------------")

integral_f_of_x = Integral(f_of_x, x)
print("integral_f_of_x:")
pprint(integral_f_of_x)
"""
f_of_x:
 2
x 
--------------------
derivative_f_of_x:
d ⎛ 2⎞
──⎝x ⎠
dx    
--------------------
integral_f_of_x:
⌠      
Пример #12
0
def test_derivative_subs3():
    x = Symbol('x')
    dex = Derivative(exp(x), x)
    assert Derivative(dex, x).subs(dex, exp(x)) == dex
    assert dex.subs(exp(x), dex) == Derivative(exp(x), x, x)
Пример #13
0
def test_derivative_subs2():
    x, y, z = symbols('x y z')
    f_func, g_func = symbols('f g', cls=Function)
    f, g = f_func(x, y, z), g_func(x, y, z)
    assert Derivative(f, x, y).subs(Derivative(f, x, y), g) == g
    assert Derivative(f, y, x).subs(Derivative(f, x, y), g) == g
    assert Derivative(f, x, y).subs(Derivative(f, x), g) == Derivative(g, y)
    assert Derivative(f, x, y).subs(Derivative(f, y), g) == Derivative(g, x)
    assert (Derivative(f, x, y, z).subs(Derivative(f, x, z),
                                        g) == Derivative(g, y))
    assert (Derivative(f, x, y, z).subs(Derivative(f, z, y),
                                        g) == Derivative(g, x))
    assert (Derivative(f, x, y, z).subs(Derivative(f, z, y, x), g) == g)

    # Issue 9135
    assert (Derivative(f, x, x, y).subs(Derivative(f, y, y),
                                        g) == Derivative(f, x, x, y))
    assert (Derivative(f, x, y, y, z).subs(Derivative(f, x, y, y, y),
                                           g) == Derivative(f, x, y, y, z))

    assert Derivative(f, x, y).subs(Derivative(f_func(x), x, y),
                                    g) == Derivative(f, x, y)
Пример #14
0
def test_deriv_sub_bug3():
    y = Symbol('y')
    f = Function('f')
    pat = Derivative(f(x), x, x)
    assert pat.subs(y, y**2) == Derivative(f(x), x, x)
    assert pat.subs(y, y**2) != Derivative(f(x), x)
Пример #15
0
def test_issue_15226():
    assert Subs(Derivative(f(y), x, y), y, g(x)).doit() != 0
Пример #16
0
def _as_finite_diff(derivative, points=1, x0=None, wrt=None):
    """
    Returns an approximation of a derivative of a function in
    the form of a finite difference formula. The expression is a
    weighted sum of the function at a number of discrete values of
    (one of) the independent variable(s).

    Parameters
    ==========

    derivative: a Derivative instance

    points: sequence or coefficient, optional
        If sequence: discrete values (length >= order+1) of the
        independent variable used for generating the finite
        difference weights.
        If it is a coefficient, it will be used as the step-size
        for generating an equidistant sequence of length order+1
        centered around ``x0``. default: 1 (step-size 1)

    x0: number or Symbol, optional
        the value of the independent variable (``wrt``) at which the
        derivative is to be approximated. Default: same as ``wrt``.

    wrt: Symbol, optional
        "with respect to" the variable for which the (partial)
        derivative is to be approximated for. If not provided it
        is required that the Derivative is ordinary. Default: ``None``.


    Examples
    ========

    >>> from sympy import symbols, Function, exp, sqrt, Symbol, as_finite_diff
    >>> from sympy.utilities.exceptions import SymPyDeprecationWarning
    >>> import warnings
    >>> warnings.simplefilter("ignore", SymPyDeprecationWarning)
    >>> x, h = symbols('x h')
    >>> f = Function('f')
    >>> as_finite_diff(f(x).diff(x))
    -f(x - 1/2) + f(x + 1/2)

    The default step size and number of points are 1 and ``order + 1``
    respectively. We can change the step size by passing a symbol
    as a parameter:

    >>> as_finite_diff(f(x).diff(x), h)
    -f(-h/2 + x)/h + f(h/2 + x)/h

    We can also specify the discretized values to be used in a sequence:

    >>> as_finite_diff(f(x).diff(x), [x, x+h, x+2*h])
    -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)

    The algorithm is not restricted to use equidistant spacing, nor
    do we need to make the approximation around ``x0``, but we can get
    an expression estimating the derivative at an offset:

    >>> e, sq2 = exp(1), sqrt(2)
    >>> xl = [x-h, x+h, x+e*h]
    >>> as_finite_diff(f(x).diff(x, 1), xl, x+h*sq2)
    2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/\
((-h + E*h)*(h + E*h)) + (-(-sqrt(2)*h + h)/(2*h) - \
(-sqrt(2)*h + E*h)/(2*h))*f(-h + x)/(h + E*h) + \
(-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h + E*h)/(2*h))*f(h + x)/(-h + E*h)

    Partial derivatives are also supported:

    >>> y = Symbol('y')
    >>> d2fdxdy=f(x,y).diff(x,y)
    >>> as_finite_diff(d2fdxdy, wrt=x)
    -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)

    See also
    ========

    sympy.calculus.finite_diff.apply_finite_diff
    sympy.calculus.finite_diff.finite_diff_weights

    """
    if derivative.is_Derivative:
        pass
    elif derivative.is_Atom:
        return derivative
    else:
        return derivative.fromiter(
            [_as_finite_diff(ar, points, x0, wrt) for ar in derivative.args],
            **derivative.assumptions0)

    if wrt is None:
        old = None
        for v in derivative.variables:
            if old is v:
                continue
            derivative = _as_finite_diff(derivative, points, x0, v)
            old = v
        return derivative

    order = derivative.variables.count(wrt)

    if x0 is None:
        x0 = wrt

    if not iterable(points):
        # points is simply the step-size, let's make it a
        # equidistant sequence centered around x0
        if order % 2 == 0:
            # even order => odd number of points, grid point included
            points = [
                x0 + points * i for i in range(-order // 2, order // 2 + 1)
            ]
        else:
            # odd order => even number of points, half-way wrt grid point
            points = [
                x0 + points * S(i) / 2 for i in range(-order, order + 1, 2)
            ]
    others = [wrt, 0]
    for v in set(derivative.variables):
        if v == wrt:
            continue
        others += [v, derivative.variables.count(v)]
    if len(points) < order + 1:
        raise ValueError("Too few points for order %d" % order)
    return apply_finite_diff(
        order, points,
        [Derivative(derivative.expr.subs({wrt: x}), *others)
         for x in points], x0)
Пример #17
0
def test_issue_7027():
    for wrt in (cos(x), re(x), Derivative(cos(x), x)):
        raises(ValueError, lambda: diff(f(x), wrt))
Пример #18
0
'''
    Finding the Derivative of Functions
'''

from sympy import Symbol, Derivative

t = Symbol('t')
St = 5 * t**2 + 2 * t + 8

# Find the value of the Derivative
d = Derivative(St, t)
print(Derivative(St, t), '=', d.doit())

# Substitute a value
print(d.doit().subs({t: 1}))
Пример #19
0
def test_Subs():
    assert Subs(1, (), ()) is S.One
    # check null subs influence on hashing
    assert Subs(x, y, z) != Subs(x, y, 1)
    # neutral subs works
    assert Subs(x, x, 1).subs(x, y).has(y)
    # self mapping var/point
    assert Subs(Derivative(f(x), (x, 2)), x, x).doit() == f(x).diff(x, x)
    assert Subs(x, x, 0).has(x)  # it's a structural answer
    assert not Subs(x, x, 0).free_symbols
    assert Subs(Subs(x + y, x, 2), y, 1) == Subs(x + y, (x, y), (2, 1))
    assert Subs(x, (x, ), (0, )) == Subs(x, x, 0)
    assert Subs(x, x, 0) == Subs(y, y, 0)
    assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0)
    assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0)
    assert Subs(f(x), x, 0).doit() == f(0)
    assert Subs(f(x**2), x**2, 0).doit() == f(0)
    assert Subs(f(x, y, z), (x, y, z), (0, 1, 1)) != \
        Subs(f(x, y, z), (x, y, z), (0, 0, 1))
    assert Subs(x, y, 2).subs(x, y).doit() == 2
    assert Subs(f(x, y), (x, y, z), (0, 1, 1)) != \
        Subs(f(x, y) + z, (x, y, z), (0, 1, 0))
    assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1)
    assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1)
    raises(ValueError, lambda: Subs(f(x, y), (x, y), (0, 0, 1)))
    raises(ValueError, lambda: Subs(f(x, y), (x, x, y), (0, 0, 1)))

    assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2
    assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1)

    assert Subs(f(x), x, 0) == Subs(f(y), y, 0)
    assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0))
    assert Subs(f(x) * y, (x, y), (0, 1)) == Subs(f(y) * x, (y, x), (0, 1))
    assert Subs(f(x) * y, (x, y), (1, 1)) == Subs(f(y) * x, (x, y), (1, 1))

    assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0)
    assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0)
    assert Subs(y * f(x), x, y).subs(y, 2) == Subs(2 * f(x), x, 2)
    assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2 * y

    assert Subs(f(x), x, 0).free_symbols == set([])
    assert Subs(f(x, y), x, z).free_symbols == {y, z}

    assert Subs(f(x).diff(x), x, 0).doit(), Subs(f(x).diff(x), x, 0)
    assert Subs(1 + f(x).diff(x), x, 0).doit(), 1 + Subs(f(x).diff(x), x, 0)
    assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \
        2*Subs(Derivative(f(x, 2), x), x, 0)
    assert Subs(y**2 * f(x), x, 0).diff(y) == 2 * y * f(0)

    e = Subs(y**2 * f(x), x, y)
    assert e.diff(y) == e.doit().diff(
        y) == y**2 * Derivative(f(y), y) + 2 * y * f(y)

    assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2 * Subs(f(x), x, 0)
    e1 = Subs(z * f(x), x, 1)
    e2 = Subs(z * f(y), y, 1)
    assert e1 + e2 == 2 * e1
    assert e1.__hash__() == e2.__hash__()
    assert Subs(z * f(x + 1), x, 1) not in [e1, e2]
    assert Derivative(f(x), x).subs(x, g(x)) == Derivative(f(g(x)), g(x))
    assert Derivative(f(x), x).subs(x, x + y) == Subs(Derivative(f(x), x), x,
                                                      x + y)
    assert Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).n(2) == \
        Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \
        z + Rational('1/2').n(2)*f(0)

    assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0)
    assert (x * f(x).diff(x).subs(x, 0)).subs(
        x, y) == y * f(x).diff(x).subs(x, 0)
    assert Subs(Derivative(g(x)**2, g(x), x), g(x),
                exp(x)).doit() == 2 * exp(x)
    assert Subs(Derivative(g(x)**2, g(x), x), g(x),
                exp(x)).doit(deep=False) == 2 * Derivative(exp(x), x)
    assert Derivative(
        f(x, g(x)),
        x).doit() == Derivative(f(x, g(x)), g(x)) * Derivative(g(x), x) + Subs(
            Derivative(f(y, g(x)), y), y, x)
Пример #20
0
mb_edf = get_Maxwellian_DF_v2(rho, u2D, sigma2, dzeta2D)
my_l_edf = my_laplace_transform_of_edf(mb_edf, dzeta2D, u2D, s2D)
print(f"my_l_edf = {my_l_edf}")
c = calc_cumulant(my_l_edf, order=0, direction=s_x)
print(f"derivative is \n {c}")  # the the cumulant is at s = 0
result = c.subs(s_x, 0)
print(f"substituting s = 0 to get cumulant:\n {result}"
      )  # the the cumulant is at s = 0

cgf = ln(my_l_edf)
md = moments_dict['D2Q9']

for mno in md:
    d = cgf
    for s_i, mno_i in zip(s3D, mno):
        d = Derivative(d, (s_i, mno_i), evaluate=True)
    d_at_0 = simplify(d)

    for s_i in s3D:
        d_at_0 = d_at_0.subs(s_i, 0)

    s_mno = re.sub(r',', '', str(mno))
    s_mno = re.sub(r' ', '', s_mno)
    s_mno = re.sub(r'\(', '', s_mno)
    s_mno = re.sub(r'\)', '', s_mno)

    print(f"c{s_mno} =  {d_at_0}")  # the the cumulant is at s = 0

print("try another script")

from SymbolicCollisions.core.ContinuousCMTransforms import ContinuousCMTransforms, get_mom_vector_from_continuous_def
Пример #21
0
def test_doit():
    n = Symbol('n', integer=True)
    f = Sum(2 * n * x, (n, 1, 3))
    d = Derivative(f, x)
    assert d.doit() == 12
    assert d.doit(deep=False) == Sum(2 * n, (n, 1, 3))
Пример #22
0
def calc_cumulant(_fun, direction, order):
    cgf = ln(_fun)
    deriv = Derivative(cgf, (direction, order))
    all_terms = deriv.doit()
    all_terms = simplify(all_terms)
    return all_terms
Пример #23
0
def test_diff_wrt_value():
    assert Expr()._diff_wrt is False
    assert x._diff_wrt is True
    assert f(x)._diff_wrt is True
    assert Derivative(f(x), x)._diff_wrt is True
    assert Derivative(x**2, x)._diff_wrt is False
Пример #24
0
def test_Derivative():
    assert str(Derivative(x, y)) == "Derivative(x, y)"
    assert str(Derivative(x**2, x, evaluate=False)) == "Derivative(x**2, x)"
    assert str(Derivative(x**2 / y, x, y,
                          evaluate=False)) == "Derivative(x**2/y, x, y)"
Пример #25
0
def test_multiple_derivative():
    # Issue #15007
    assert f(x, y).diff(y, y, x, y, x) == Derivative(f(x, y), (x, 2), (y, 3))
Пример #26
0
from sympy import Symbol, solve, Derivative

x = Symbol('x')
f = x**5 - 30 * x**3 + 50 * x
d1 = Derivative(f, x).doit()

critical_points = solve(d1)
print(critical_points)

A = critical_points[2]
B = critical_points[1]
C = critical_points[1]
D = critical_points[3]
'''
    Because all the critical points for this function lie within the considered
    interval, they are all relevant for our search for the global maximum and
    minimum of f(x). We may now apply the so-called second derivative test to
    narrow down which critical points could be global maxima or minima.
    First, we calculate the second-order derivative for the function f(x).
    Note that to do so, we enter 2 as the third argument:

    Excerpt from the book Doing Math with Python
'''

d2 = Derivative(f, x, 2).doit()

# The minimum of the following values will be the minima of the function
print(d2.subs({x: B}).evalf())
print(d2.subs({x: C}).evalf())
print(d2.subs({x: A}).evalf())
print(d2.subs({x: D}).evalf())
Пример #27
0
def test_Derivative_as_finite_difference():
    # Central 1st derivative at gridpoint
    x, h = symbols('x h', real=True)
    dfdx = f(x).diff(x)
    assert (dfdx.as_finite_difference([x - 2, x - 1, x, x + 1, x + 2]) -
            (S(1) / 12 * (f(x - 2) - f(x + 2)) + S(2) / 3 *
             (f(x + 1) - f(x - 1)))).simplify() == 0

    # Central 1st derivative "half-way"
    assert (dfdx.as_finite_difference() -
            (f(x + S(1) / 2) - f(x - S(1) / 2))).simplify() == 0
    assert (dfdx.as_finite_difference(h) -
            (f(x + h / S(2)) - f(x - h / S(2))) / h).simplify() == 0
    assert (dfdx.as_finite_difference([x - 3 * h, x - h, x + h, x + 3 * h]) -
            (S(9) / (8 * 2 * h) * (f(x + h) - f(x - h)) + S(1) / (24 * 2 * h) *
             (f(x - 3 * h) - f(x + 3 * h)))).simplify() == 0

    # One sided 1st derivative at gridpoint
    assert (dfdx.as_finite_difference([0, 1, 2], 0) -
            (-S(3) / 2 * f(0) + 2 * f(1) - f(2) / 2)).simplify() == 0
    assert (dfdx.as_finite_difference([x, x + h], x) -
            (f(x + h) - f(x)) / h).simplify() == 0
    assert (dfdx.as_finite_difference([x - h, x, x + h], x - h) -
            (-S(3) / (2 * h) * f(x - h) + 2 / h * f(x) - S(1) /
             (2 * h) * f(x + h))).simplify() == 0

    # One sided 1st derivative "half-way"
    assert (
        dfdx.as_finite_difference(
            [x - h, x + h, x + 3 * h, x + 5 * h, x + 7 * h]) - 1 / (2 * h) *
        (-S(11) / (12) * f(x - h) + S(17) /
         (24) * f(x + h) + S(3) / 8 * f(x + 3 * h) - S(5) / 24 * f(x + 5 * h) +
         S(1) / 24 * f(x + 7 * h))).simplify() == 0

    d2fdx2 = f(x).diff(x, 2)
    # Central 2nd derivative at gridpoint
    assert (d2fdx2.as_finite_difference([x - h, x, x + h]) - h**-2 *
            (f(x - h) + f(x + h) - 2 * f(x))).simplify() == 0

    assert (
        d2fdx2.as_finite_difference([x - 2 * h, x - h, x, x + h, x + 2 * h]) -
        h**-2 * (-S(1) / 12 * (f(x - 2 * h) + f(x + 2 * h)) + S(4) / 3 *
                 (f(x + h) + f(x - h)) - S(5) / 2 * f(x))).simplify() == 0

    # Central 2nd derivative "half-way"
    assert (d2fdx2.as_finite_difference([x - 3 * h, x - h, x + h, x + 3 * h]) -
            (2 * h)**-2 * (S(1) / 2 *
                           (f(x - 3 * h) + f(x + 3 * h)) - S(1) / 2 *
                           (f(x + h) + f(x - h)))).simplify() == 0

    # One sided 2nd derivative at gridpoint
    assert (d2fdx2.as_finite_difference([x, x + h, x + 2 * h, x + 3 * h]) -
            h**-2 * (2 * f(x) - 5 * f(x + h) + 4 * f(x + 2 * h) - f(x + 3 * h))
            ).simplify() == 0

    # One sided 2nd derivative at "half-way"
    assert (
        d2fdx2.as_finite_difference([x - h, x + h, x + 3 * h, x + 5 * h]) -
        (2 * h)**-2 *
        (S(3) / 2 * f(x - h) - S(7) / 2 * f(x + h) + S(5) / 2 * f(x + 3 * h) -
         S(1) / 2 * f(x + 5 * h))).simplify() == 0

    d3fdx3 = f(x).diff(x, 3)
    # Central 3rd derivative at gridpoint
    assert (d3fdx3.as_finite_difference() -
            (-f(x - 3 / S(2)) + 3 * f(x - 1 / S(2)) - 3 * f(x + 1 / S(2)) +
             f(x + 3 / S(2)))).simplify() == 0

    assert (d3fdx3.as_finite_difference(
        [x - 3 * h, x - 2 * h, x - h, x, x + h, x + 2 * h, x + 3 * h]) -
            h**-3 * (S(1) / 8 * (f(x - 3 * h) - f(x + 3 * h)) - f(x - 2 * h) +
                     f(x + 2 * h) + S(13) / 8 *
                     (f(x - h) - f(x + h)))).simplify() == 0

    # Central 3rd derivative at "half-way"
    assert (d3fdx3.as_finite_difference([x - 3 * h, x - h, x + h, x + 3 * h]) -
            (2 * h)**-3 * (f(x + 3 * h) - f(x - 3 * h) + 3 *
                           (f(x - h) - f(x + h)))).simplify() == 0

    # One sided 3rd derivative at gridpoint
    assert (d3fdx3.as_finite_difference([x, x + h, x + 2 * h, x + 3 * h]) -
            h**-3 * (f(x + 3 * h) - f(x) + 3 *
                     (f(x + h) - f(x + 2 * h)))).simplify() == 0

    # One sided 3rd derivative at "half-way"
    assert (d3fdx3.as_finite_difference([x - h, x + h, x + 3 * h, x + 5 * h]) -
            (2 * h)**-3 * (f(x + 5 * h) - f(x - h) + 3 *
                           (f(x + h) - f(x + 3 * h)))).simplify() == 0

    # issue 11007
    y = Symbol('y', real=True)
    d2fdxdy = f(x, y).diff(x, y)

    ref0 = Derivative(f(x + S(1) / 2, y), y) - Derivative(
        f(x - S(1) / 2, y), y)
    assert (d2fdxdy.as_finite_difference(wrt=x) - ref0).simplify() == 0

    half = S(1) / 2
    xm, xp, ym, yp = x - half, x + half, y - half, y + half
    ref2 = f(xm, ym) + f(xp, yp) - f(xp, ym) - f(xm, yp)
    assert (d2fdxdy.as_finite_difference() - ref2).simplify() == 0
Пример #28
0
def test_diff_symbols():
    assert diff(f(x, y, z), x, y, z) == Derivative(f(x, y, z), x, y, z)
    assert diff(f(x, y, z), x, x, x) == Derivative(f(
        x, y, z), x, x, x) == Derivative(f(x, y, z), (x, 3))
    assert diff(f(x, y, z), x, 3) == Derivative(f(x, y, z), x, 3)

    # issue 5028
    assert [diff(-z + x / y, sym)
            for sym in (z, x, y)] == [-1, 1 / y, -x / y**2]
    assert diff(f(x, y, z), x, y, z, 2) == Derivative(f(x, y, z), x, y, z, z)
    assert diff(f(x, y, z), x, y, z, 2, evaluate=False) == \
        Derivative(f(x, y, z), x, y, z, z)
    assert Derivative(f(x, y, z), x, y, z)._eval_derivative(z) == \
        Derivative(f(x, y, z), x, y, z, z)
    assert Derivative(Derivative(f(x, y, z), x), y)._eval_derivative(z) == \
        Derivative(f(x, y, z), x, y, z)

    raises(TypeError, lambda: cos(x).diff((x, y)).variables)
    assert cos(x).diff((x, y))._wrt_variables == [x]
Пример #29
0
 def _visit_eval_derivative_array(self, x):
     if x.has(self):
         return _matrix_derivative(x, self)
     else:
         from sympy import Derivative
         return Derivative(x, self)
Пример #30
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 unchanged(jacobi, n, a, b, oo)

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

    _k = Dummy('k')
    assert diff(jacobi(n, a, b, x), n) == Derivative(jacobi(n, a, b, x), n)
    assert diff(jacobi(n, a, b, x), a).dummy_eq(
        Sum((jacobi(n, a, b, x) + (2 * _k + a + b + 1) *
             RisingFactorial(_k + b + 1, -_k + n) * jacobi(_k, a, b, x) /
             ((-_k + n) * RisingFactorial(_k + a + b + 1, -_k + n))) /
            (_k + a + b + n + 1), (_k, 0, n - 1)))
    assert diff(jacobi(n, a, b, x), b).dummy_eq(
        Sum(((-1)**(-_k + n) * (2 * _k + a + b + 1) *
             RisingFactorial(_k + a + 1, -_k + n) * jacobi(_k, a, b, x) /
             ((-_k + n) * RisingFactorial(_k + a + b + 1, -_k + n)) +
             jacobi(n, a, b, x)) / (_k + a + b + n + 1), (_k, 0, n - 1)))
    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)

    assert jacobi_normalized(n, a, b, x) == \
           (jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)
                                    /((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1))))

    raises(ValueError, lambda: jacobi(-2.1, a, b, x))
    raises(ValueError,
           lambda: jacobi(Dummy(positive=True, integer=True), 1, 2, oo))

    assert jacobi(n, a, b, x).rewrite("polynomial").dummy_eq(
        Sum((S(1) / 2 - x / 2)**_k * RisingFactorial(-n, _k) *
            RisingFactorial(_k + a + 1, -_k + n) *
            RisingFactorial(a + b + n + 1, _k) / factorial(_k),
            (_k, 0, n)) / factorial(n))
    raises(ArgumentIndexError, lambda: jacobi(n, a, b, x).fdiff(5))