- •Credits
- •About the Author
- •About the Reviewers
- •www.PacktPub.com
- •Preface
- •Getting started
- •More advanced graphics
- •Summary
- •Start Sage
- •Installing Sage
- •Starting 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
5
Vectors,Matrices,andLinearAlgebra
Linear algebra is a fundamental task for mathematical software. Linear algebra is easily automated because it involves tedious computations that must be performed according to well-defined formulas and algorithms. Sage has extensive support for various types of
calculations with vectors and matrices. Sage's vector and matrix objects build upon the basic mathematical types that we learned about in Chapter 3. We will also learn about a Python library called NumPy that is very useful for numerical calculations.
In this chapter we will:
Learn how to create and manipulate vector and matrix objects See how Sage can take the tedious work out of linear algebra
Learn about matrix methods for computing eigenvalues, inverses, and decompositions
Get started with NumPy arrays and matrices for numerical calculations
There are many ways to do linear algebra in Sage. Sage is a collection of tools, each of which has its own way of representing vectors and matrices. Therefore, you will find that there are multiple ways to accomplish the same thing. We will focus on the high level constructs that are unique to Sage. Then, we will introduce the NumPy package, which provides a powerful set of tools for numerical computation. Let's get started!
Vectors and vector spaces
Vectors and matrices are so important that they are represented by special types of objects in Sage. We'll start with vectors.
Vectors, Matrices, and Linear Algebra
Timeforaction–workingwithvectors
Vectors have important applications in physics and engineering. Vectors are used to represent position, velocity, angular momentum, electromagnetic fields, and so on. Let's see how to perform some basic operations with vectors in Sage. You can enter the following code in an input cell in a worksheet, or enter it line by line in the interactive shell. You can also enter the code into a plain text file, save it with a .sage extension, and run it from the Sage command line as described in the previous chapter:
R3 = VectorSpace(QQ, 3) (b1, b2, b3) = R3.basis() print("Basis for space:") print b1
print b2 print b3
vector1 = R3([-1, 2, 7]) |
# define some vectors |
|
vector2 = R3([4, -9, 2]) |
|
|
print("Linear combinations:") |
|
|
var('a b') |
|
|
print(a * vector1 + b * vector2) |
|
|
print("Norm of vector 1:") |
|
|
print(sqrt(vector1 * vector1)) |
# definition |
|
print(vector1.norm()) |
# using norm method |
|
print("Scalar multiplication:") |
|
|
print(2 * vector1) |
|
|
print("Scalar (dot) products:") |
|
|
print(vector1 * vector2) |
|
# using operators |
print(vector1.inner_product(vector2)) # using methods print(b1 * b2)
print("Pairwise product:") print(vector1.pairwise_product(vector2))
print("Vector (cross) product:") print(vector1.cross_product(vector2))
[ 114 ]
Chapter 5
Execute the code (remember that you can press Shift-Enter in an input cell to run the code from the Notebook interface). If you are using the notebook interface, the result should look like this:
What just happened?
This example demonstrated some of the most useful operations that Sage can perform on vectors. We started by defining a vector space that consists of three-element vectors with rational numbers as elements. While it's not strictly necessary to define the vector space, it does provide some helpful tools, such as access to the basis vectors of the space. We then defined a pair of vectors and demonstrated various operations, such as the cross product and dot product.
Creating a vector space
The VectorSpace class is used to create an object that represents a vector space.
my_vector_space = VectorSpace(base_field, dimension)
The first argument is the base field, such as the field of rational, real, or complex numbers, over which the vector space is defined. You can also define a vector space over the symbolic ring to perform symbolic calculations. The second argument is the dimension of the space, which is effectively the number of elements in each vector.
[ 115 ]
Vectors, Matrices, and Linear Algebra
At this point, it is important to explain more about rings and fields. Rings were introduced in Chapter 3. Fields are a superset of rings; every field is a ring, but not every ring is a field. The following table summarizes the rings and fields that we have used so far:
Full name |
Shortcut |
Ring? |
Field? |
Description |
IntegerRing |
ZZ |
Yes |
No |
Integers |
RationalField |
Yes |
Yes |
Rational numbers |
|
RealField |
RR |
Yes |
Yes |
Real numbers |
ComplexField |
CC |
Yes |
Yes |
Complex numbers |
All of the rings we have used so far are also fields, with the exception of integers. Therefore, you cannot use integers as the base field for a vector. However, you can use the symbolic ring SR as a base field for a vector or vector space. The reason is that the symbolic ring is not a ring in the strict mathematical sense. The symbolic ring is simply a way of stating that a particular construct will contain symbols instead of numerical values.
Creatingandmanipulatingvectors
There are two ways to create a vector object. In the example, we first defined a vector space, and used the vector space to create the vector. A list of elements (of the appropriate length) is used to define the elements of the new vector:
new_vector = my_vector_space([element_1, element_2, element_n])
The other way is to use the vector function, which automatically constructs a vector space over the specified field and returns a vector object:
new_vector = vector(base_field,[element_1, element_2, element_n])
The first argument is the base field, and the second is a list of elements. Both ways return equivalent vectors.
Timeforaction–manipulatingelementsofvectors
The elements of a vector can be manipulated like the elements of any other Python sequence type, such as lists and strings. That means individual elements are accessed using square brackets, as shown in the following example:
u = vector(QQ, [1, 2/7, 10/3]) |
# QQ is the field of rational |
numbers |
|
print("u=" + str(u))
print("Elements: {0}, {1}, {2}".format(u[0], u[1], u[2])) print("The slice [0:2] is {0}".format(u[0:2])) print("The last element is {0}".format(u[-1]))
[ 116 ]
