Differentiation and Integration

Sympy is capable of carrying out differentiation and integration of many functions.
>>> from sympy import Symbol, exp, sin, sqrt, diff
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> diff(sin(x),x)
cos(x)
>>> diff(sin(x),y)
0
>>> diff(10 + 2*x + 4*y + 10*x**2 + x**9, x)
9*x**8 + 20*x + 2
>>> diff(10 + 2*x + 4*y + 10*x**2 + x**9, y)
4
>>> diff(10 + 2*x + 4*y + 10*x**2 + x**9, x).subs(x,1)
31
>>> diff(10 + 2*x + 4*y + 10*x**2 + x**9, x).subs(x,1.5)
262.660156250000
>>> diff(exp(x),x)
exp(x)
>>> diff(exp(-x**2/2),x)
-x*exp(-x**2/2)
The Sympy diff() function takes a minimum of two arguments: the function to be differentiated and the variable with respect ot which the differentiation is performed. Higher derivatives may be calculated by specifying additional variables, or by adding and optional integer argument.
>>> diff(3*x**4,x)
12*x**3
>>> diff(3*x**4, x, x, x)
72*x
>>> diff(3*x**4, x, 3)
72*x
>>> diff(3*x**4*y**7, x , 2, y, 2)
1512*x**2*y**5
>>> diff(diff(3*x**4*y**7, x , x), y, y)
1512*x**2*y**5
Integration uses a similar syntax. For the indefinite case, specify the function and a variable with respect to which the integration is performed:
>>> from sympy import integrate
>>> integrate(x**2,x)
x**3/3
>>> integrate(x**2,y)
x**2*y
>>> integrate(sin(x),y)
y*sin(x)
>>> integrate(sin(x),x)
-cos(x)
>>> integrate(-x*exp(-x**2/2),x)
exp(-x**2/2)
We can calculate definite integrals by providing integrate() method with a tuple containing the variable of interest, the lower and the upper bounds. If several variables are specified, multiple integration is performed. When Sympy returns a result in the Rational class, it is possible to evaluate it to a floating-point representation at any desired precision.
>>> integrate(x*2, (x, 0, 1))
1
>>> integrate(x**2, x)
x**3/3
>>> integrate(x**2, x, x)
x**4/12
>>> integrate(x**2, x, x, y)
x**4*y/12
>>> integrate(x**2, (x, 0, 2))
8/3
>>> integrate(x**2, (x, 0, 2), (x, 0, 2), (y, 0, 1))
16/3
>>> float(integrate(x**2, (x, 0, 2)))
2.6666666666666665
>>> type(integrate(x**2, (x, 0, 2)))

>>> res_rational = integrate(x**2, (x, 0, 2))
>>> res_rational.evalf()
2.66666666666667
>>> res_rational.evalf(100)
2.6666666666666666666666666666666666666666666666666666666666666666666666666666666
66666666666666666667

Nema komentara:

Objavi komentar