Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – manipulating elements of vectors


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]))
u[len(u) - 1] = 3/2
print("The last element is now {0}".format(u[-1]))

print "Assigning a real value to an element:"
u[2] = numerical_approx(pi, digits=5)
print(u)

The output from this code will look like this if you are using the notebook interface:

What just happened?

We created a vector called u, defined over the field of rational numbers (remember that QQ is a short form of RationalField) and manipulated the elements of the vector just like elements in a list. We demonstrated...