Elementary Functions

Examples for elementary functions in SymPy are trigonometric functions and their inverses. The following example shows how simplify acts on expression which include elementary function:

x = symbols('x')
simplify(cos(x)**2 + sin(x)**2)  # returns 1

Here is another example for the use of elementary functions:

atan(x).diff(x) - 1./(x**2+1)  # returns 0

If you use SciPy and SymPy together, we strongly recommend that you use them in different namespaces:

import scipy as sp
import sympy as sym
# working with numbers
x=3
y=sp.sin(x)
# working with symbols
x=sym.symbols('x')
y=sym.sin(x)   

Lambda - functions

In section Anonymous functions of Chapter 7, Functions, we saw how to define so-called anonymous functions in Python. The counterpart in SymPy is done by the Lambda command. Note the difference; lambda is a keyword while Lambda is a constructor.

The command Lambda takes two arguments, the symbol of the function's independent variable, and a SymPy expression to evaluate the function.

Here is an example that defines air resistance (also called drag) as a function of speed:

C,rho,A,v=symbols('C rho A v')
# C drag coefficient, A coss-sectional area, rho density
# v speed
f_drag = Lambda(v,-Rational(1,2)*C*rho*A*v**2)

f_drag is displayed as an expression:

Lambda - functions.

This function can be evaluated in the usual way by providing it with an argument:

x = symbols('x')
f_drag(2)
f_drag(x/3)

which will results in given expression:

Lambda - functions

It is also possible to create functions in several variables by just providing it with several arguments as for example:

t=Lambda((x,y),sin(x) + cos(2*y))

A call to this function can be done in two ways, either by directly providing several arguments:

t(pi,pi/2)  # returns -1

or by unpacking a tuple or list:

p=(pi,pi/2)
t(*p)   # returns -1

Matrix objects in SymPy make it even possible to define vector-valued functions:

F=Lambda((x,y),Matrix([sin(x) + cos(2*y), sin(x)*cos(y)]))

This enables us to compute Jacobians:

F(x,y).jacobian((x,y))

Which gives the following expression as output:

Lambda - functions

In the case of more variables, it is convenient to use a more compact form to define the function:

x=symbols('x:2')
F=Lambda(x,Matrix([sin(x[0]) + cos(2*x[1]),sin(x[0])*cos(x[1])]))  
F(*x).jacobian(x)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.61.218