- •Credits
- •About the Author
- •About the Reviewers
- •www.PacktPub.com
- •Preface
- •Getting started
- •More advanced graphics
- •Summary
- •Installing Sage
- •Starting Sage
- •Start Sage
- •Prerequisites
- •Installation
- •Summary
- •Command history
- •Working with code
- •Arithmetic operators
- •Strings
- •Functions
- •Functions with keyword arguments
- •Objects
- •Summary
- •Python 2 and Python 3
- •Running scripts
- •Strings
- •List comprehensions
- •Storing data in a dictionary
- •Summary
- •Vectors and vector spaces
- •Creating a vector space
- •Vector operators and methods
- •Decomposing matrices
- •Summary
- •Using graphics primitives
- •Summary
- •Substitutions
- •Finding roots
- •Derivatives
- •Integrals
- •Series and summations
- •Summary
- •Computing gradients
- •Constrained optimization
- •Probability
- •Summary
- •Making our tanks move
- •Unit testing
- •Summary
- •Introducing Python decorators
- •Making interactive graphics
- •Summary
- •Index
Chapter 7
What just happened?
The function integrate (or integral) is used to compute integrals, and the methods called integrate and integral do exactly the same thing. We started out by showing that Sage knows about lots of the elementary integrals. We then showed that Sage easily handles functions that need to be integrated by parts, which can be very tedious to do by hand. If integrate is called as a function, the first argument is the function to be integrated, and the second argument is the variable of integration. If there are no additional arguments, the integral is assumed to be indefinite. If two additional arguments are present, they
are used as the limits of integration. We showed that Sage can compute definite integrals and improper integrals (one or more limits at infinity.) In the final case, we showed what happens when an integral diverges: Sage simply prints an appropriate error message and exits. integrate also accepts the optional keyword argument algorithm to choose the integration algorithm, which can be set to 'maxima' (the default), 'sympy', or
'mathematica_free' (which uses http://integrals.wolfram.com/).
Series and summations
An infinite series is a summation of a sequence with an infinite number of terms. Truncated series are useful for approximating functions. In this section, we'll look at the capabilities that Sage has for computing infinite sequences and computing their sums.
Timeforaction–computingsumsofseries
Enter the following code into an input cell in a worksheet, and evaluate the cell:
var('x, n, k')
f(x) = sin(x) / x^2 f.show()
print("Power series expansion around x=1:") s(x) = f.series(x==1, 3)
s.show()
print("Sum of alternating harmonic series:") h(k) = (-1)^(k + 1) * 1 / k
print h.sum(k, 1, infinity)
print("Sum of binomial series:") h(k) = binomial(n, k)
print h.sum(k, 1, infinity)
print("Sum of harmonic series:") h(k) = 1 / k
print h.sum(k, 1, infinity) |
# Diverges |
|
|
|
|
|
[ 199 ] |
|
|
|
|
Making Symbolic Mathematics Easy
The results are shown in the following screenshot:
What just happened?
We started by defining a function and using the series method to compute a power series around the point x=1. The first argument to series is the point at which to create the series, and the second argument is the order of the computed series. Notice that Sages uses "big O" notation to denote the order of the series.
We then created several infinite series and computed their sums. Sage can compute the sum of any convergent series using the sum method. The first argument to sum is the summation variable, the second argument is the lower endpoint, and the third argument is the upper endpoint of the series. We used this method to compute the sum of the alternating harmonic series and the binomial series. However, we ran into trouble when we tried to compute the sum of the harmonic series, which is divergent. Fortunately, Sage handled this problem gracefully.
Taylorseries
A Taylor series is a series expansion of a function around a point. If the point is zero, the series is known as a Maclaurin series. Taylor series are often used to approximate functions.
Timeforaction–findingTaylorseries
Run the following code to see how to compute a one-dimensional Taylor series with Sage.
var('x,k')
colors=['red', 'black', 'green', 'magenta']
x1 = pi/2
[ 200 ]
Chapter 7
xmin = x1 - pi; xmax = x1 + pi
f(x) = sin(x)
p1 = plot(f, (xmin, xmax), color='blue')
Taylor_series_3(x) = f.taylor(x, x1, 3)
p1 += plot(Taylor_series_3, (xmin, xmax), legend_label='3', color='red')
Taylor_series_5(x) = f.taylor(x, x1, 5)
p1 += plot(Taylor_series_5, (xmin, xmax), legend_label='5', color='green')
Taylor_series_7(x) = f.taylor(x, x1, 7)
p1 += plot(Taylor_series_7, (xmin, xmax), legend_label='7', color='black')
Taylor_series_7.show() show(p1)
The results are shown in the following screenshot:
[ 201 ]
Making Symbolic Mathematics Easy
What just happened?
The Taylor series expansion approximates the behaviour of a function in the vicinity of a point. With an infinite number of terms, the series should match the function exactly in a small region near the point. However, the Taylor series provides a good approximation with only a finite number of terms. We used Sage to create a plot that illustrates how the Taylor series approaches the function sin(x) near the point pi/2 as the number of terms in the series increases.
We used the taylor method to create the Taylor series. The first argument is the independent variable, the second argument is the point, and the third argument is the order of the series. In this case, we constructed Taylor series of order 3, 5, and 7 and plotted them on the same axes with the sine function, in the vicinity of the point pi/2. We also displayed the seventh-order Taylor series.
Haveagohero–Taylorseries
Compute the Taylor series for the exp function about the point x=1. Use a plot to see how well the Taylor series approximates the function as you increase the order of the Taylor series.
Laplacetransforms
The Laplace transform is defined as the integral:
This is for functions that are defined for t ≥ 0. The Laplace transform is widely used for solving ordinary differential equations. It has applications in the theory of electrical circuits, control systems, and communication systems. If you need to learn or review the basics of Laplace transforms, you may want to consult Shaum's Outline of Laplace Transforms by Murray Spiegel (McGraw-Hill, 1965).
Timeforaction–computingLaplacetransforms
Evaluate the following code to see how to compute Laplace transforms with Sage:
var('t, a, k, s') print("Elementary transform:") f(t) = sin(k * t)
F(s) = f.laplace(t, s)
[ 202 ]
Chapter 7
F.show()
print("Inverse transform:")
G(s) = 1 / ((s - 1) * (s + 2) * (s + 4)) G.show()
g(t) = G.inverse_laplace(s, t) g.show()
The results are shown in the following screenshot:
What just happened?
We used Sage to compute the Laplace transform and the inverse Laplace transform. Normally, finding the Laplace transform would have required looking up the elementary forms in a table. Computing the inverse transform requires performing a partial fraction expansion and then finding the resulting terms in a table. The process is much faster with Sage, and Sage can compute transforms that cannot practically be computed by hand. We used the laplace method to compute the forward transform, and inverse_laplace to compute the reverse transform. Each of these methods computes the transform with respect to a variable (the first argument) using a transform parameter (the second argument.) It's easier to think of the first argument as the variable you are transforming from, and the second as the variable you are transforming to.
[ 203 ]
Making Symbolic Mathematics Easy
Solvingordinarydifferentialequations
Ordinary differential equations (ODEs) are widely used in applied mathematics, engineering, and the sciences. Sage enables you to find exact solutions to many ODEs.
Timeforaction–solvinganordinarydifferentialequation
The following code demonstrates how to solve ordinary differential equations with Sage:
var('x, x1, x2, t')
#Finding a general solution print("General solution:")
y = function('y', x)
ode = 4*diff(y, x, 2) + 36 * y == csc(3 * x) y(x) = desolve(ode, y)
y.show()
#Solving an initial-value problem print("Solving an initial-value problem:") y = function('y', x)
ode = diff(y, x, 2) - 4 * diff(y, x) + 13 * y == 0 y(x) = desolve(ode, y, [0, -1, 2], ivar=x) y.show()
#Solving a system of first-order equations print("Solving a system of first-order ODEs:") x1 = function('x1', t)
x2 = function('x2', t)
ode1 = 2 * diff(x1, t) + diff(x2, t) - x2 == t ode2 = diff(x1, t) + diff(x2, t) == t^2
y1, y2 = desolve_system([ode1, ode2], [x1, x2], ics=[0, 0, 0])
y1.show()
y2.show()
[ 204 ]
Chapter 7
The results are shown in the following screenshot:
What just happened?
The first step towards solving a differential equation with Sage is to create a symbolic function that represents the solution. In this example, we used function to create a symbolic function called y that is a function of x. We then created a relational symbolic expression called ode that implicitly defines y(x). Once the problem is set up, it is simple to call the desolve function to obtain the solution. desolve requires two arguments: the relational expression that defines the differential equation, and the dependent variable. It returns an expression for the general solution of the ODE. If the function has more than one independent variable, then the independent variable must be specified using the ivar keyword.
In the next part of the example, we used desolve to solve an initial-value problem with a second-order ODE. The initial values of the independent variable, the dependent variable, and the first derivative of the dependent variable are used to form a list (in this order), which was passed as an argument to desolve. Sage solves the initial-value problem and returns the solution as a symbolic expression. In the third part of the example, we used desolve_system to solve a system of two first-order ODEs. desolve_system can solve systems of many first-order differential equations. Since a higher-order ODE can be written as a system of first-order ODEs, this does not limit the usefulness of desolve_system. We defined two symbolic functions, x1 and x2, which are functions of t. The first argument of desolve_system is a list of differential equations, and the second argument is a list of dependent variables to solve for. We used the optional argument with keyword ics to set initial conditions for the independent variable (t), x1, and x2, respectively. The result is a pair of symbolic expressions for x1 and x2. In the next chapter, we'll see how Sage can help us solve differential equations numerically.
[ 205 ]
