Sage PDF
Sage PDF
Release 6.3
The Sage Development Team
August 11, 2014
CONTENTS
1 Introduction 3
1.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Ways to Use Sage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Longterm Goals for Sage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 A Guided Tour 7
2.1 Assignment, Equality, and Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.3 Functions, Indentation, and Counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4 Basic Algebra and Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.5 Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.6 Some Common Issues with Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.7 Basic Rings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.8 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.9 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.10 Parents, Conversion and Coercion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.11 Finite Groups, Abelian Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.12 Number Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
2.13 Some More Advanced Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3 The Interactive Shell 51
3.1 Your Sage Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.2 Logging Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.3 Paste Ignores Prompts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.4 Timing Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.5 Other IPython tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.6 Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.7 Reverse Search and Tab Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.8 Integrated Help System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.9 Saving and Loading Individual Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
3.10 Saving and Loading Complete Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.11 The Notebook Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4 Interfaces 65
4.1 GP/PARI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.2 GAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.3 Singular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.4 Maxima . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
i
5 Sage, LaTeX and Friends 71
5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
5.2 Basic Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.3 Customizing LaTeX Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.4 Customizing LaTeX Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.5 An Example: Combinatorial Graphs with tkz-graph . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.6 A Fully Capable TeX Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
5.7 External Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6 Programming 79
6.1 Loading and Attaching Sage les . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.2 Creating Compiled Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.3 Standalone Python/Sage Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.4 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.5 Lists, Tuples, and Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
6.6 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
6.7 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.8 Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.9 Loops, Functions, Control Statements, and Comparisons . . . . . . . . . . . . . . . . . . . . . . . . 86
6.10 Proling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7 Using SageTeX 91
8 Afterword 93
8.1 Why Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.2 I would like to contribute somehow. How can I? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.3 How do I reference Sage? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
9 Appendix 97
9.1 Arithmetical binary operator precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10 Bibliography 99
11 Indices and tables 101
Bibliography 103
ii
Sage Tutorial, Release 6.3
Sage is free, open-source math software that supports research and teaching in algebra, geometry, number theory,
cryptography, numerical computation, and related areas. Both the Sage development model and the technology in Sage
itself are distinguished by an extremely strong emphasis on openness, community, cooperation, and collaboration: we
are building the car, not reinventing the wheel. The overall goal of Sage is to create a viable, free, open-source
alternative to Maple, Mathematica, Magma, and MATLAB.
This tutorial is the best way to become familiar with Sage in only a few hours. You can read it in HTML or PDF
versions, or from the Sage notebook (click Help, then click Tutorial to interactively work through the tutorial
from within Sage).
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License.
CONTENTS 1
Sage Tutorial, Release 6.3
2 CONTENTS
CHAPTER
ONE
INTRODUCTION
This tutorial should take at most 3-4 hours to fully work through. You can read it in HTML or PDF versions, or from
the Sage notebook click Help, then click Tutorial to interactively work through the tutorial from within Sage.
Though much of Sage is implemented using Python, no Python background is needed to read this tutorial. You will
want to learn Python (a very fun language!) at some point, and there are many excellent free resources for doing so
including [PyT] and [Dive]. If you just want to quickly try out Sage, this tutorial is the place to start. For example:
sage: 2 + 2
4
sage: factor(-2007)
-1
*
3^2
*
223
sage: A = matrix(4,4, range(16)); A
[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
sage: factor(A.charpoly())
x^2
*
(x^2 - 30
*
x - 80)
sage: m = matrix(ZZ,2, range(4))
sage: m[0,0] = m[0,0] - 3
sage: m
[-3 1]
[ 2 3]
sage: E = EllipticCurve([1,2,3,4,5]);
sage: E
Elliptic Curve defined by y^2 + x
*
y + 3
*
y = x^3 + 2
*
x^2 + 4
*
x + 5
over Rational Field
sage: E.anlist(10)
[0, 1, 1, 0, -1, -3, 0, -1, -3, -3, -3]
sage: E.rank()
1
sage: k = 1/(sqrt(3)
*
I + 3/4 + sqrt(73)
*
5/9); k
36/(20
*
sqrt(73) + 36
*
I
*
sqrt(3) + 27)
sage: N(k)
0.165495678130644 - 0.0521492082074256
*
I
sage: N(k,30) # 30 "bits"
0.16549568 - 0.052149208
*
I
sage: latex(k)
\frac{36}{20 \, \sqrt{73} + 36 i \, \sqrt{3} + 27}
3
Sage Tutorial, Release 6.3
1.1 Installation
If you do not have Sage installed on a computer and just want to try some commands, use online at
http://www.sagenb.org.
See the Sage Installation Guide in the documentation section of the main Sage webpage [SA] for instructions on
installing Sage on your computer. Here we merely make a few comments.
1. The Sage download le comes with batteries included. In other words, although Sage uses Python, IPython,
PARI, GAP, Singular, Maxima, NTL, GMP, and so on, you do not need to install them separately as they are
included with the Sage distribution. However, to use certain Sage features, e.g., Macaulay or KASH, you must
install the relevant optional package or at least have the relevant programs installed on your computer already.
Macaulay and KASH are Sage packages (for a list of available optional packages, type sage -optional, or
browse the Download page on the Sage website).
2. The pre-compiled binary version of Sage (found on the Sage web site) may be easier and quicker to install than
the source code version. Just unpack the le and run sage.
3. If youd like to use the SageTeX package (which allows you to embed the results of Sage computations into
a LaTeX le), you will need to make SageTeX known to your TeX distribution. To do this, see the section
Make SageTeX known to TeX in the Sage installation guide (this link should take you to a local copy of the
installation guide). Its quite easy; you just need to set an environment variable or copy a single le to a directory
that TeX will search.
The documentation for using SageTeXis located in $SAGE_ROOT/local/share/texmf/tex/generic/sagetex/,
where $SAGE_ROOT refers to the directory where you installed Sage for example, /opt/sage-4.2.1.
1.2 Ways to Use Sage
You can use Sage in several ways.
Notebook graphical interface: see the section on the Notebook in the reference manual and The Notebook
Interface below,
Interactive command line: see The Interactive Shell,
Programs: By writing interpreted and compiled programs in Sage (see Loading and Attaching Sage les and
Creating Compiled Code), and
Scripts: by writing stand-alone Python scripts that use the Sage library (see Standalone Python/Sage Scripts).
1.3 Longterm Goals for Sage
Useful: Sages intended audience is mathematics students (from high school to graduate school), teachers, and
research mathematicians. The aim is to provide software that can be used to explore and experiment with
mathematical constructions in algebra, geometry, number theory, calculus, numerical computation, etc. Sage
helps make it easier to interactively experiment with mathematical objects.
Efcient: Be fast. Sage uses highly-optimized mature software like GMP, PARI, GAP, and NTL, and so is very
fast at certain operations.
Free and open source: The source code must be freely available and readable, so users can understand what
the system is really doing and more easily extend it. Just as mathematicians gain a deeper understanding of
a theorem by carefully reading or at least skimming the proof, people who do computations should be able to
understand how the calculations work by reading documented source code. If you use Sage to do computations
4 Chapter 1. Introduction
Sage Tutorial, Release 6.3
in a paper you publish, you can rest assured that your readers will always have free access to Sage and all its
source code, and you are even allowed to archive and re-distribute the version of Sage you used.
Easy to compile: Sage should be easy to compile from source for Linux, OS X and Windows users. This
provides more exibility for users to modify the system.
Cooperation: Provide robust interfaces to most other computer algebra systems, including PARI, GAP, Sin-
gular, Maxima, KASH, Magma, Maple, and Mathematica. Sage is meant to unify and extend existing math
software.
Well documented: Tutorial, programming guide, reference manual, and how-to, with numerous examples and
discussion of background mathematics.
Extensible: Be able to dene new data types or derive from built-in types, and use code written in a range of
languages.
User friendly: It should be easy to understand what functionality is provided for a given object and to view
documentation and source code. Also attain a high level of user support.
1.3. Longterm Goals for Sage 5
Sage Tutorial, Release 6.3
6 Chapter 1. Introduction
CHAPTER
TWO
A GUIDED TOUR
This section is a guided tour of some of what is available in Sage. For many more examples, see Sage Constructions,
which is intended to answer the general question How do I construct ...?. See also the Sage Reference Manual,
which has thousands more examples. Also note that you can interactively work through this tour in the Sage notebook
by clicking the Help link.
(If you are viewing the tutorial in the Sage notebook, press shift-enter to evaluate any input cell. You can
even edit the input before pressing shift-enter. On some Macs you might have to press shift-return rather than
shift-enter.)
2.1 Assignment, Equality, and Arithmetic
With some minor exceptions, Sage uses the Python programming language, so most introductory books on Python
will help you to learn Sage.
Sage uses = for assignment. It uses ==, <=, >=, < and > for comparison:
sage: a = 5
sage: a
5
sage: 2 == 2
True
sage: 2 == 3
False
sage: 2 < 3
True
sage: a == 5
True
Sage provides all of the basic mathematical operations:
sage: 2
**
3 #
**
means exponent
8
sage: 2^3 # ^ is a synonym for
**
(unlike in Python)
8
sage: 10 % 3 # for integer arguments, % means mod, i.e., remainder
1
sage: 10/4
5/2
sage: 10//4 # for integer arguments, // returns the integer quotient
2
sage: 4
*
(10 // 4) + 10 % 4 == 10
True
7
Sage Tutorial, Release 6.3
sage: 3^2
*
4 + 2%5
38
The computation of an expression like 3^2
*
4 + 2%5 depends on the order in which the operations are applied; this
is specied in the operator precedence table in Arithmetical binary operator precedence.
Sage also provides many familiar mathematical functions; here are just a few examples:
sage: sqrt(3.4)
1.84390889145858
sage: sin(5.135)
-0.912021158525540
sage: sin(pi/3)
1/2
*
sqrt(3)
As the last example shows, some mathematical expressions return exact values, rather than numerical approxima-
tions. To get a numerical approximation, use either the function n or the method n (and both of these have a longer
name, numerical_approx, and the function N is the same as n)). These take optional arguments prec, which is
the requested number of bits of precision, and digits, which is the requested number of decimal digits of precision;
the default is 53 bits of precision.
sage: exp(2)
e^2
sage: n(exp(2))
7.38905609893065
sage: sqrt(pi).numerical_approx()
1.77245385090552
sage: sin(10).n(digits=5)
-0.54402
sage: N(sin(10),digits=10)
-0.5440211109
sage: numerical_approx(pi, prec=200)
3.1415926535897932384626433832795028841971693993751058209749
Python is dynamically typed, so the value referred to by each variable has a type associated with it, but a given variable
may hold values of any Python type within a given scope:
sage: a = 5 # a is an integer
sage: type(a)
<type sage.rings.integer.Integer>
sage: a = 5/3 # now a is a rational number
sage: type(a)
<type sage.rings.rational.Rational>
sage: a = hello # now a is a string
sage: type(a)
<type str>
The C programming language, which is statically typed, is much different; a variable declared to hold an int can only
hold an int in its scope.
A potential source of confusion in Python is that an integer literal that begins with a zero is treated as an octal number,
i.e., a number in base 8.
sage: 011
9
sage: 8 + 1
9
sage: n = 011
8 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
sage: n.str(8) # string representation of n in base 8
11
This is consistent with the C programming language.
2.2 Getting Help
Sage has extensive built-in documentation, accessible by typing the name of a function or a constant (for example),
followed by a question mark:
sage: tan?
Type: <class sage.calculus.calculus.Function_tan>
Definition: tan( [noargspec] )
Docstring:
The tangent function
EXAMPLES:
sage: tan(pi)
0
sage: tan(3.1415)
-0.0000926535900581913
sage: tan(3.1415/4)
0.999953674278156
sage: tan(pi/4)
1
sage: tan(1/2)
tan(1/2)
sage: RR(tan(1/2))
0.546302489843790
sage: log2?
Type: <class sage.functions.constants.Log2>
Definition: log2( [noargspec] )
Docstring:
The natural logarithm of the real number 2.
EXAMPLES:
sage: log2
log2
sage: float(log2)
0.69314718055994529
sage: RR(log2)
0.693147180559945
sage: R = RealField(200); R
Real Field with 200 bits of precision
sage: R(log2)
0.69314718055994530941723212145817656807550013436025525412068
sage: l = (1-log2)/(1+log2); l
(1 - log(2))/(log(2) + 1)
sage: R(l)
0.18123221829928249948761381864650311423330609774776013488056
sage: maxima(log2)
log(2)
sage: maxima(log2).float()
.6931471805599453
2.2. Getting Help 9
Sage Tutorial, Release 6.3
sage: gp(log2)
0.6931471805599453094172321215 # 32-bit
0.69314718055994530941723212145817656807 # 64-bit
sage: sudoku?
File: sage/local/lib/python2.5/site-packages/sage/games/sudoku.py
Type: <type function>
Definition: sudoku(A)
Docstring:
Solve the 9x9 Sudoku puzzle defined by the matrix A.
EXAMPLE:
sage: A = matrix(ZZ,9,[5,0,0, 0,8,0, 0,4,9, 0,0,0, 5,0,0,
0,3,0, 0,6,7, 3,0,0, 0,0,1, 1,5,0, 0,0,0, 0,0,0, 0,0,0, 2,0,8, 0,0,0,
0,0,0, 0,0,0, 0,1,8, 7,0,0, 0,0,4, 1,5,0, 0,3,0, 0,0,2,
0,0,0, 4,9,0, 0,5,0, 0,0,3])
sage: A
[5 0 0 0 8 0 0 4 9]
[0 0 0 5 0 0 0 3 0]
[0 6 7 3 0 0 0 0 1]
[1 5 0 0 0 0 0 0 0]
[0 0 0 2 0 8 0 0 0]
[0 0 0 0 0 0 0 1 8]
[7 0 0 0 0 4 1 5 0]
[0 3 0 0 0 2 0 0 0]
[4 9 0 0 5 0 0 0 3]
sage: sudoku(A)
[5 1 3 6 8 7 2 4 9]
[8 4 9 5 2 1 6 3 7]
[2 6 7 3 4 9 5 8 1]
[1 5 8 4 6 3 9 7 2]
[9 7 4 2 1 8 3 6 5]
[3 2 6 7 9 5 4 1 8]
[7 8 2 9 3 4 1 5 6]
[6 3 5 1 7 2 8 9 4]
[4 9 1 8 5 6 7 2 3]
Sage also provides Tab completion: type the rst few letters of a function and then hit the tab key. For example, if
you type ta followed by TAB, Sage will print tachyon, tan, tanh, taylor. This provides a good way to
nd the names of functions and other structures in Sage.
2.3 Functions, Indentation, and Counting
To dene a new function in Sage, use the def command and a colon after the list of variable names. For example:
sage: def is_even(n):
... return n%2 == 0
...
sage: is_even(2)
True
sage: is_even(3)
False
Note: Depending on which version of the tutorial you are viewing, you may see three dots ... on the second line of
this example. Do not type them; they are just to emphasize that the code is indented. Whenever this is the case, press
[Return/Enter] once at the end of the block to insert a blank line and conclude the function denition.
10 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
You do not specify the types of any of the input arguments. You can specify multiple inputs, each of which may have
an optional default value. For example, the function below defaults to divisor=2 if divisor is not specied.
sage: def is_divisible_by(number, divisor=2):
... return number%divisor == 0
sage: is_divisible_by(6,2)
True
sage: is_divisible_by(6)
True
sage: is_divisible_by(6, 5)
False
You can also explicitly specify one or either of the inputs when calling the function; if you specify the inputs explicitly,
you can give them in any order:
sage: is_divisible_by(6, divisor=5)
False
sage: is_divisible_by(divisor=2, number=6)
True
In Python, blocks of code are not indicated by curly braces or begin and end blocks as in many other languages.
Instead, blocks of code are indicated by indentation, which must match up exactly. For example, the following is a
syntax error because the return statement is not indented the same amount as the other lines above it.
sage: def even(n):
... v = []
... for i in range(3,n):
... if i % 2 == 0:
... v.append(i)
... return v
Syntax Error:
return v
If you x the indentation, the function works:
sage: def even(n):
... v = []
... for i in range(3,n):
... if i % 2 == 0:
... v.append(i)
... return v
sage: even(10)
[4, 6, 8]
Semicolons are not needed at the ends of lines; a line is in most cases ended by a newline. However, you can put
multiple statements on one line, separated by semicolons:
sage: a = 5; b = a + 3; c = b^2; c
64
If you would like a single line of code to span multiple lines, use a terminating backslash:
sage: 2 + \
... 3
5
In Sage, you count by iterating over a range of integers. For example, the rst line below is exactly like for(i=0;
i<3; i++) in C++ or Java:
2.3. Functions, Indentation, and Counting 11
Sage Tutorial, Release 6.3
sage: for i in range(3):
... print i
0
1
2
The rst line below is like for(i=2;i<5;i++).
sage: for i in range(2,5):
... print i
2
3
4
The third argument controls the step, so the following is like for(i=1;i<6;i+=2).
sage: for i in range(1,6,2):
... print i
1
3
5
Often you will want to create a nice table to display numbers you have computed using Sage. One easy way to do this
is to use string formatting. Below, we create three columns each of width exactly 6 and make a table of squares and
cubes.
sage: for i in range(5):
... print %6s %6s %6s%(i, i^2, i^3)
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
The most basic data structure in Sage is the list, which is as the name suggests just a list of arbitrary objects. For
example, the range command that we used creates a list:
sage: range(2,10)
[2, 3, 4, 5, 6, 7, 8, 9]
Here is a more complicated list:
sage: v = [1, "hello", 2/3, sin(x^3)]
sage: v
[1, hello, 2/3, sin(x^3)]
List indexing is 0-based, as in many programming languages.
sage: v[0]
1
sage: v[3]
sin(x^3)
Use len(v) to get the length of v, use v.append(obj) to append a new object to the end of v, and use del
v[i] to delete the i
th
entry of v:
sage: len(v)
4
12 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
sage: v.append(1.5)
sage: v
[1, hello, 2/3, sin(x^3), 1.50000000000000]
sage: del v[1]
sage: v
[1, 2/3, sin(x^3), 1.50000000000000]
Another important data structure is the dictionary (or associative array). This works like a list, except that it can be
indexed with almost any object (the indices must be immutable):
sage: d = {hi:-2, 3/8:pi, e:pi}
sage: d[hi]
-2
sage: d[e]
pi
You can also dene new data types using classes. Encapsulating mathematical objects with classes is a powerful
technique that can help to simplify and organize your Sage programs. Below, we dene a class that represents the list
of even positive integers up to n; it derives from the builtin type list.
sage: class Evens(list):
... def __init__(self, n):
... self.n = n
... list.__init__(self, range(2, n+1, 2))
... def __repr__(self):
... return "Even positive numbers up to n."
The __init__ method is called to initialize the object when it is created; the __repr__ method prints the object
out. We call the list constructor method in the second line of the __init__ method. We create an object of class
Evens as follows:
sage: e = Evens(10)
sage: e
Even positive numbers up to n.
Note that e prints using the __repr__ method that we dened. To see the underlying list of numbers, use the list
function:
sage: list(e)
[2, 4, 6, 8, 10]
We can also access the n attribute or treat e like a list.
sage: e.n
10
sage: e[2]
6
2.4 Basic Algebra and Calculus
Sage can perform various computations related to basic algebra and calculus: for example, nding solutions to equa-
tions, differentiation, integration, and Laplace transforms. See the Sage Constructions documentation for more exam-
ples.
2.4. Basic Algebra and Calculus 13
Sage Tutorial, Release 6.3
2.4.1 Solving Equations
Solving Equations Exactly
The solve function solves equations. To use it, rst specify some variables; then the arguments to solve are an
equation (or a system of equations), together with the variables for which to solve:
sage: x = var(x)
sage: solve(x^2 + 3
*
x + 2, x)
[x == -2, x == -1]
You can solve equations for one variable in terms of others:
sage: x, b, c = var(x b c)
sage: solve([x^2 + b
*
x + c == 0],x)
[x == -1/2
*
b - 1/2
*
sqrt(b^2 - 4
*
c), x == -1/2
*
b + 1/2
*
sqrt(b^2 - 4
*
c)]
You can also solve for several variables:
sage: x, y = var(x, y)
sage: solve([x+y==6, x-y==4], x, y)
[[x == 5, y == 1]]
The following example of using Sage to solve a system of non-linear equations was provided by Jason Grout: rst, we
solve the system symbolically:
sage: var(x y p q)
(x, y, p, q)
sage: eq1 = p+q==9
sage: eq2 = q
*
y+p
*
x==-6
sage: eq3 = q
*
y^2+p
*
x^2==24
sage: solve([eq1,eq2,eq3,p==1],p,q,x,y)
[[p == 1, q == 8, x == -4/3
*
sqrt(10) - 2/3, y == 1/6
*
sqrt(5)
*
sqrt(2) - 2/3],
[p == 1, q == 8, x == 4/3
*
sqrt(10) - 2/3, y == -1/6
*
sqrt(5)
*
sqrt(2) - 2/3]]
For numerical approximations of the solutions, you can instead use:
sage: solns = solve([eq1,eq2,eq3,p==1],p,q,x,y, solution_dict=True)
sage: [[s[p].n(30), s[q].n(30), s[x].n(30), s[y].n(30)] for s in solns]
[[1.0000000, 8.0000000, -4.8830369, -0.13962039],
[1.0000000, 8.0000000, 3.5497035, -1.1937129]]
(The function n prints a numerical approximation, and the argument is the number of bits of precision.)
Solving Equations Numerically
Often times, solve will not be able to nd an exact solution to the equation or equations specied. When it fails,
you can use find_root to nd a numerical solution. For example, solve does not return anything interesting for the
following equation:
sage: theta = var(theta)
sage: solve(cos(theta)==sin(theta), theta)
[sin(theta) == cos(theta)]
On the other hand, we can use find_root to nd a solution to the above equation in the range 0 < < /2:
14 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
sage: phi = var(phi)
sage: find_root(cos(phi)==sin(phi),0,pi/2)
0.785398163397448...
2.4.2 Differentiation, Integration, etc.
Sage knows how to differentiate and integrate many functions. For example, to differentiate sin(u) with respect to u,
do the following:
sage: u = var(u)
sage: diff(sin(u), u)
cos(u)
To compute the fourth derivative of sin(x
2
):
sage: diff(sin(x^2), x, 4)
16
*
x^4
*
sin(x^2) - 48
*
x^2
*
cos(x^2) - 12
*
sin(x^2)
To compute the partial derivatives of x
2
+ 17y
2
with respect to x and y, respectively:
sage: x, y = var(x,y)
sage: f = x^2 + 17
*
y^2
sage: f.diff(x)
2
*
x
sage: f.diff(y)
34
*
y
We move on to integrals, both indenite and denite. To compute
xsin(x
2
) dx and
1
0
x
x
2
+1
dx
sage: integral(x
*
sin(x^2), x)
-1/2
*
cos(x^2)
sage: integral(x/(x^2+1), x, 0, 1)
1/2
*
log(2)
To compute the partial fraction decomposition of
1
x
2
1
:
sage: f = 1/((1+x)
*
(x-1))
sage: f.partial_fraction(x)
-1/2/(x + 1) + 1/2/(x - 1)
2.4.3 Solving Differential Equations
You can use Sage to investigate ordinary differential equations. To solve the equation x
+x 1 = 0:
sage: t = var(t) # define a variable t
sage: x = function(x,t) # define x to be a function of that variable
sage: DE = diff(x, t) + x - 1
sage: desolve(DE, [x,t])
(_C + e^t)
*
e^(-t)
This uses Sages interface to Maxima [Max], and so its output may be a bit different from other Sage output. In this
case, this says that the general solution to the differential equation is x(t) = e
t
(e
t
+c).
You can compute Laplace transforms also; the Laplace transform of t
2
e
t
sin(t) is computed as follows:
2.4. Basic Algebra and Calculus 15
Sage Tutorial, Release 6.3
sage: s = var("s")
sage: t = var("t")
sage: f = t^2
*
exp(t) - sin(t)
sage: f.laplace(t,s)
-1/(s^2 + 1) + 2/(s - 1)^3
Here is a more involved example. The displacement from equilibrium (respectively) for a coupled spring attached to a
wall on the left
|------\/\/\/\/\---|mass1|----\/\/\/\/\/----|mass2|
spring1 spring2
is modeled by the system of 2nd order differential equations
m
1
x
1
+ (k
1
+k
2
)x
1
k
2
x
2
= 0
m
2
x
2
+k
2
(x
2
x
1
) = 0,
where m
i
is the mass of object i, x
i
is the displacement from equilibrium of mass i, and k
i
is the spring constant for
spring i.
Example: Use Sage to solve the above problem with m
1
= 2, m
2
= 1, k
1
= 4, k
2
= 2, x
1
(0) = 3, x
1
(0) = 0,
x
2
(0) = 3, x
2
(0) = 0.
Solution: Take the Laplace transform of the rst equation (with the notation x = x
1
, y = x
2
):
sage: de1 = maxima("2
*
diff(x(t),t, 2) + 6
*
x(t) - 2
*
y(t)")
sage: lde1 = de1.laplace("t","s"); lde1
2
*
(-?%at(diff(x(t),t,1),t=0)+s^2
*
laplace(x(t),t,s)-x(0)
*
s)-2
*
laplace(y(t),t,s)+6
*
laplace(x(t),t,s)
This is hard to read, but it says that
2x
(0) + 2s
2
X(s) 2sx(0) 2Y (s) + 6X(s) = 0
(where the Laplace transform of a lower case function like x(t) is the upper case function X(s)). Take the Laplace
transform of the second equation:
sage: de2 = maxima("diff(y(t),t, 2) + 2
*
y(t) - 2
*
x(t)")
sage: lde2 = de2.laplace("t","s"); lde2
-?%at(diff(y(t),t,1),t=0)+s^2
*
laplace(y(t),t,s)+2
*
laplace(y(t),t,s)-2
*
laplace(x(t),t,s)-y(0)
*
s
This says
Y
(0) +s
2
Y (s) + 2Y (s) 2X(s) sy(0) = 0.
Plug in the initial conditions for x(0), x
(x)
y(x +h) y(x)
h
,
where h > 0 is given and small. This and the DE together give f(x, y(x))
y(x+h)y(x)
h
. Now solve for y(x +h):
y(x +h) y(x) +h f(x, y(x)).
If we call h f(x, y(x)) the correction term (for lack of anything better), call y(x) the old value of y, and call
y(x +h) the new value of y, then this approximation can be re-expressed as
y
new
y
old
+h f(x, y
old
).
If we break the interval from a to b into n steps, so that h =
ba
n
, then we can record the information for this method
in a table.
2.4. Basic Algebra and Calculus 17
Sage Tutorial, Release 6.3
x y h f(x, y)
a c h f(a, c)
a +h c +h f(a, c) ...
a + 2h ...
...
b = a +nh ??? ...
The goal is to ll out all the blanks of the table, one row at a time, until we reach the ??? entry, which is the Eulers
method approximation for y(b).
The idea for systems of ODEs is similar.
Example: Numerically approximate z(t) at t = 1 using 4 steps of Eulers method, where z
+tz
+z = 0, z(0) = 1,
z
(0) = 0.
We must reduce the 2nd order ODE down to a system of two rst order DEs (using x = z, y = z
2. Those roots
are not rational, so if you are working with polynomials with rational coefcients, the polynomial wont factor. With
real coefcients, it will. Therefore you may want to specify the ring to insure that you are getting the information you
expect. The following two commands denes the sets of polynomials with rational coefcents and real coefcients,
respectively. The sets are named ratpoly and realpoly, but these arent important here; however, note that the
strings .<t> and .<z> name the variables used in the two cases.
sage: ratpoly.<t> = PolynomialRing(QQ)
sage: realpoly.<z> = PolynomialRing(RR)
Now we illustrate the point about factoring x
2
2:
sage: factor(t^2-2)
t^2 - 2
sage: factor(z^2-2)
(z - 1.41421356237310)
*
(z + 1.41421356237310)
Similar comments apply to matrices: the row-reduced form of a matrix can depend on the ring over which it is dened,
as can its eigenvalues and eigenvectors. For more about constructing polynomials, see Polynomials, and for more about
matrices, see Linear Algebra.
The symbol I represents the square root of 1; i is a synonym for I. Of course, this is not a rational number:
sage: i # square root of -1
I
sage: i in QQ
False
Note: The above code may not work as expected if the variable i has been assigned a different value, for example, if
it was used as a loop variable. If this is the case, type
sage: reset(i)
to get the original complex value of i.
There is one subtlety in dening complex numbers: as mentioned above, the symbol i represents a square root of
1, but it is a formal or symbolic square root of 1. Calling CC(i) or CC.0 returns the complex square root of
1. Arithmetic involving different kinds of numbers is possible by so-called coercion, see Parents, Conversion and
Coercion.
sage: i = CC(i) # floating point complex number
sage: i == CC.0
True
2.7. Basic Rings 25
Sage Tutorial, Release 6.3
sage: a, b = 4/3, 2/3
sage: z = a + b
*
i
sage: z
1.33333333333333 + 0.666666666666667
*
I
sage: z.imag() # imaginary part
0.666666666666667
sage: z.real() == a # automatic coercion before comparison
True
sage: a + b
2
sage: 2
*
b == a
True
sage: parent(2/3)
Rational Field
sage: parent(4/2)
Rational Field
sage: 2/3 + 0.1 # automatic coercion before addition
0.766666666666667
sage: 0.1 + 2/3 # coercion rules are symmetric in SAGE
0.766666666666667
Here are more examples of basic rings in Sage. As noted above, the ring of rational numbers may be referred to using
QQ, or also RationalField() (a eld is a ring in which the multiplication is commutative and in which every
nonzero element has a reciprocal in that ring, so the rationals form a eld, but the integers dont):
sage: RationalField()
Rational Field
sage: QQ
Rational Field
sage: 1/2 in QQ
True
The decimal number 1.2 is considered to be in QQ: decimal numbers which happen to also be rational can be co-
erced into the rational numbers (see Parents, Conversion and Coercion). The numbers and
2 are not rational,
though:
sage: 1.2 in QQ
True
sage: pi in QQ
False
sage: pi in RR
True
sage: sqrt(2) in QQ
False
sage: sqrt(2) in CC
True
For use in higher mathematics, Sage also knows about other rings, such as nite elds, p-adic integers, the ring of
algebraic numbers, polynomial rings, and matrix rings. Here are constructions of some of these:
sage: GF(3)
Finite Field of size 3
sage: GF(27, a) # need to name the generator if not a prime field
Finite Field in a of size 3^3
sage: Zp(5)
5-adic Ring with capped relative precision 20
sage: sqrt(3) in QQbar # algebraic closure of QQ
True
26 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
2.8 Linear Algebra
Sage provides standard constructions from linear algebra, e.g., the characteristic polynomial, echelon form, trace,
decomposition, etc., of a matrix.
Creation of matrices and matrix multiplication is easy and natural:
sage: A = Matrix([[1,2,3],[3,2,1],[1,1,1]])
sage: w = vector([1,1,-4])
sage: w
*
A
(0, 0, 0)
sage: A
*
w
(-9, 1, -2)
sage: kernel(A)
Free module of degree 3 and rank 1 over Integer Ring
Echelon basis matrix:
[ 1 1 -4]
Note that in Sage, the kernel of a matrix A is the left kernel, i.e. the space of vectors w such that wA = 0.
Solving matrix equations is easy, using the method solve_right. Evaluating A.solve_right(Y) returns a
matrix (or vector) X so that AX = Y :
sage: Y = vector([0, -4, -1])
sage: X = A.solve_right(Y)
sage: X
(-2, 1, 0)
sage: A
*
X # checking our answer...
(0, -4, -1)
A backslash \ can be used in the place of solve_right; use A \ Y instead of A.solve_right(Y).
sage: A \ Y
(-2, 1, 0)
If there is no solution, Sage returns an error:
sage: A.solve_right(w)
Traceback (most recent call last):
...
ValueError: matrix equation has no solutions
Similarly, use A.solve_left(Y) to solve for X in XA = Y .
Sage can also compute eigenvalues and eigenvectors:
sage: A = matrix([[0, 4], [-1, 0]])
sage: A.eigenvalues ()
[-2
*
I, 2
*
I]
sage: B = matrix([[1, 3], [3, 1]])
sage: B.eigenvectors_left()
[(4, [
(1, 1)
], 1), (-2, [
(1, -1)
], 1)]
(The syntax for the output of eigenvectors_left is a list of triples: (eigenvalue, eigenvector, multiplicity).)
Eigenvalues and eigenvectors over QQ or RR can also be computed using Maxima (see Maxima below).
2.8. Linear Algebra 27
Sage Tutorial, Release 6.3
As noted in Basic Rings, the ring over which a matrix is dened affects some of its properties. In the following, the
rst argument to the matrix command tells Sage to view the matrix as a matrix of integers (the ZZ case), a matrix
of rational numbers (QQ), or a matrix of reals (RR):
sage: AZ = matrix(ZZ, [[2,0], [0,1]])
sage: AQ = matrix(QQ, [[2,0], [0,1]])
sage: AR = matrix(RR, [[2,0], [0,1]])
sage: AZ.echelon_form()
[2 0]
[0 1]
sage: AQ.echelon_form()
[1 0]
[0 1]
sage: AR.echelon_form()
[ 1.00000000000000 0.000000000000000]
[0.000000000000000 1.00000000000000]
For computing eigenvalues and eigenvectors of matrices over oating point real or complex numbers, the matrix
should be dened over RDF (Real Double Field) or CDF (Complex Double Field), respectively. If no ring is specied
and oating point real or complex numbers are used then by default the matrix is dened over the RR or CC elds,
respectively, which do not support these computations for all the cases:
sage: ARDF = matrix(RDF, [[1.2, 2], [2, 3]])
sage: ARDF.eigenvalues()
[-0.0931712199461, 4.29317121995]
sage: ACDF = matrix(CDF, [[1.2, I], [2, 3]])
sage: ACDF.eigenvectors_right()
[(0.881845698329 - 0.820914065343
*
I, [(0.750560818381, -0.616145932705 + 0.238794153033
*
I)], 1),
(3.31815430167 + 0.820914065343
*
I, [(0.145594698293 + 0.37566908585
*
I, 0.915245825866)], 1)]
2.8.1 Matrix spaces
We create the space Mat
33
(Q) of 3 3 matrices with rational entries:
sage: M = MatrixSpace(QQ,3)
sage: M
Full MatrixSpace of 3 by 3 dense matrices over Rational Field
(To specify the space of 3 by 4 matrices, you would use MatrixSpace(QQ,3,4). If the number of columns is
omitted, it defaults to the number of rows, so MatrixSpace(QQ,3) is a synonym for MatrixSpace(QQ,3,3).)
The space of matrices has a basis which Sage stores as a list:
sage: B = M.basis()
sage: len(B)
9
sage: B[1]
[0 1 0]
[0 0 0]
[0 0 0]
We create a matrix as an element of M.
sage: A = M(range(9)); A
[0 1 2]
[3 4 5]
[6 7 8]
28 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
Next we compute its reduced row echelon form and kernel.
sage: A.echelon_form()
[ 1 0 -1]
[ 0 1 2]
[ 0 0 0]
sage: A.kernel()
Vector space of degree 3 and dimension 1 over Rational Field
Basis matrix:
[ 1 -2 1]
Next we illustrate computation of matrices dened over nite elds:
sage: M = MatrixSpace(GF(2),4,8)
sage: A = M([1,1,0,0, 1,1,1,1, 0,1,0,0, 1,0,1,1,
... 0,0,1,0, 1,1,0,1, 0,0,1,1, 1,1,1,0])
sage: A
[1 1 0 0 1 1 1 1]
[0 1 0 0 1 0 1 1]
[0 0 1 0 1 1 0 1]
[0 0 1 1 1 1 1 0]
sage: rows = A.rows()
sage: A.columns()
[(1, 0, 0, 0), (1, 1, 0, 0), (0, 0, 1, 1), (0, 0, 0, 1),
(1, 1, 1, 1), (1, 0, 1, 1), (1, 1, 0, 1), (1, 1, 1, 0)]
sage: rows
[(1, 1, 0, 0, 1, 1, 1, 1), (0, 1, 0, 0, 1, 0, 1, 1),
(0, 0, 1, 0, 1, 1, 0, 1), (0, 0, 1, 1, 1, 1, 1, 0)]
We make the subspace over F
2
spanned by the above rows.
sage: V = VectorSpace(GF(2),8)
sage: S = V.subspace(rows)
sage: S
Vector space of degree 8 and dimension 4 over Finite Field of size 2
Basis matrix:
[1 0 0 0 0 1 0 0]
[0 1 0 0 1 0 1 1]
[0 0 1 0 1 1 0 1]
[0 0 0 1 0 0 1 1]
sage: A.echelon_form()
[1 0 0 0 0 1 0 0]
[0 1 0 0 1 0 1 1]
[0 0 1 0 1 1 0 1]
[0 0 0 1 0 0 1 1]
The basis of S used by Sage is obtained from the non-zero rows of the reduced row echelon form of the matrix of
generators of S.
2.8.2 Sparse Linear Algebra
Sage has support for sparse linear algebra over PIDs.
sage: M = MatrixSpace(QQ, 100, sparse=True)
sage: A = M.random_element(density = 0.05)
sage: E = A.echelon_form()
2.8. Linear Algebra 29
Sage Tutorial, Release 6.3
The multi-modular algorithm in Sage is good for square matrices (but not so good for non-square matrices):
sage: M = MatrixSpace(QQ, 50, 100, sparse=True)
sage: A = M.random_element(density = 0.05)
sage: E = A.echelon_form()
sage: M = MatrixSpace(GF(2), 20, 40, sparse=True)
sage: A = M.random_element()
sage: E = A.echelon_form()
Note that Python is case sensitive:
sage: M = MatrixSpace(QQ, 10,10, Sparse=True)
Traceback (most recent call last):
...
TypeError: __classcall__() got an unexpected keyword argument Sparse
2.9 Polynomials
In this section we illustrate how to create and use polynomials in Sage.
2.9.1 Univariate Polynomials
There are three ways to create polynomial rings.
sage: R = PolynomialRing(QQ, t)
sage: R
Univariate Polynomial Ring in t over Rational Field
This creates a polynomial ring and tells Sage to use (the string) t as the indeterminate when printing to the screen.
However, this does not dene the symbol t for use in Sage, so you cannot use it to enter a polynomial (such as t
2
+1)
belonging to R.
An alternate way is
sage: S = QQ[t]
sage: S == R
True
This has the same issue regarding t.
A third very convenient way is
sage: R.<t> = PolynomialRing(QQ)
or
sage: R.<t> = QQ[t]
or even
sage: R.<t> = QQ[]
This has the additional side effect that it denes the variable t to be the indeterminate of the polynomial ring, so you
can easily construct elements of R, as follows. (Note that the third way is very similar to the constructor notation in
Magma, and just as in Magma it can be used for a wide range of objects.)
30 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
sage: poly = (t+1)
*
(t+2); poly
t^2 + 3
*
t + 2
sage: poly in R
True
Whatever method you use to dene a polynomial ring, you can recover the indeterminate as the 0
th
generator:
sage: R = PolynomialRing(QQ, t)
sage: t = R.0
sage: t in R
True
Note that a similar construction works with the complex numbers: the complex numbers can be viewed as being
generated over the real numbers by the symbol i; thus we have the following:
sage: CC
Complex Field with 53 bits of precision
sage: CC.0 # 0th generator of CC
1.00000000000000
*
I
For polynomial rings, you can obtain both the ring and its generator, or just the generator, during ring creation as
follows:
sage: R, t = QQ[t].objgen()
sage: t = QQ[t].gen()
sage: R, t = objgen(QQ[t])
sage: t = gen(QQ[t])
Finally we do some arithmetic in Q[t].
sage: R, t = QQ[t].objgen()
sage: f = 2
*
t^7 + 3
*
t^2 - 15/19
sage: f^2
4
*
t^14 + 12
*
t^9 - 60/19
*
t^7 + 9
*
t^4 - 90/19
*
t^2 + 225/361
sage: cyclo = R.cyclotomic_polynomial(7); cyclo
t^6 + t^5 + t^4 + t^3 + t^2 + t + 1
sage: g = 7
*
cyclo
*
t^5
*
(t^5 + 10
*
t + 2)
sage: g
7
*
t^16 + 7
*
t^15 + 7
*
t^14 + 7
*
t^13 + 77
*
t^12 + 91
*
t^11 + 91
*
t^10 + 84
*
t^9
+ 84
*
t^8 + 84
*
t^7 + 84
*
t^6 + 14
*
t^5
sage: F = factor(g); F
(7)
*
t^5
*
(t^5 + 10
*
t + 2)
*
(t^6 + t^5 + t^4 + t^3 + t^2 + t + 1)
sage: F.unit()
7
sage: list(F)
[(t, 5), (t^5 + 10
*
t + 2, 1), (t^6 + t^5 + t^4 + t^3 + t^2 + t + 1, 1)]
Notice that the factorization correctly takes into account and records the unit part.
If you were to use, e.g., the R.cyclotomic_polynomial function a lot for some research project, in addition
to citing Sage you should make an attempt to nd out what component of Sage is being used to actually compute
the cyclotomic polynomial and cite that as well. In this case, if you type R.cyclotomic_polynomial?? to
see the source code, youll quickly see a line f = pari.polcyclo(n) which means that PARI is being used for
computation of the cyclotomic polynomial. Cite PARI in your work as well.
Dividing two polynomials constructs an element of the fraction eld (which Sage creates automatically).
2.9. Polynomials 31
Sage Tutorial, Release 6.3
sage: x = QQ[x].0
sage: f = x^3 + 1; g = x^2 - 17
sage: h = f/g; h
(x^3 + 1)/(x^2 - 17)
sage: h.parent()
Fraction Field of Univariate Polynomial Ring in x over Rational Field
Using Laurent series, one can compute series expansions in the fraction eld of QQ[x]:
sage: R.<x> = LaurentSeriesRing(QQ); R
Laurent Series Ring in x over Rational Field
sage: 1/(1-x) + O(x^10)
1 + x + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + O(x^10)
If we name the variable differently, we obtain a different univariate polynomial ring.
sage: R.<x> = PolynomialRing(QQ)
sage: S.<y> = PolynomialRing(QQ)
sage: x == y
False
sage: R == S
False
sage: R(y)
x
sage: R(y^2 - 17)
x^2 - 17
The ring is determined by the variable. Note that making another ring with variable called x does not return a different
ring.
sage: R = PolynomialRing(QQ, "x")
sage: T = PolynomialRing(QQ, "x")
sage: R == T
True
sage: R is T
True
sage: R.0 == T.0
True
Sage also has support for power series and Laurent series rings over any base ring. In the following example, we create
an element of F
7
[[T]] and divide to create an element of F
7
((T)).
sage: R.<T> = PowerSeriesRing(GF(7)); R
Power Series Ring in T over Finite Field of size 7
sage: f = T + 3
*
T^2 + T^3 + O(T^4)
sage: f^3
T^3 + 2
*
T^4 + 2
*
T^5 + O(T^6)
sage: 1/f
T^-1 + 4 + T + O(T^2)
sage: parent(1/f)
Laurent Series Ring in T over Finite Field of size 7
You can also create power series rings using a double-brackets shorthand:
sage: GF(7)[[T]]
Power Series Ring in T over Finite Field of size 7
32 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
2.9.2 Multivariate Polynomials
To work with polynomials of several variables, we declare the polynomial ring and variables rst.
sage: R = PolynomialRing(GF(5),3,"z") # here, 3 = number of variables
sage: R
Multivariate Polynomial Ring in z0, z1, z2 over Finite Field of size 5
Just as for dening univariate polynomial rings, there are alternative ways:
sage: GF(5)[z0, z1, z2]
Multivariate Polynomial Ring in z0, z1, z2 over Finite Field of size 5
sage: R.<z0,z1,z2> = GF(5)[]; R
Multivariate Polynomial Ring in z0, z1, z2 over Finite Field of size 5
Also, if you want the variable names to be single letters then you can use the following shorthand:
sage: PolynomialRing(GF(5), 3, xyz)
Multivariate Polynomial Ring in x, y, z over Finite Field of size 5
Next lets do some arithmetic.
sage: z = GF(5)[z0, z1, z2].gens()
sage: z
(z0, z1, z2)
sage: (z[0]+z[1]+z[2])^2
z0^2 + 2
*
z0
*
z1 + z1^2 + 2
*
z0
*
z2 + 2
*
z1
*
z2 + z2^2
You can also use more mathematical notation to construct a polynomial ring.
sage: R = GF(5)[x,y,z]
sage: x,y,z = R.gens()
sage: QQ[x]
Univariate Polynomial Ring in x over Rational Field
sage: QQ[x,y].gens()
(x, y)
sage: QQ[x].objgens()
(Univariate Polynomial Ring in x over Rational Field, (x,))
Multivariate polynomials are implemented in Sage using Python dictionaries and the distributive representation of a
polynomial. Sage makes some use of Singular [Si], e.g., for computation of gcds and Grbner basis of ideals.
sage: R, (x, y) = PolynomialRing(RationalField(), 2, xy).objgens()
sage: f = (x^3 + 2
*
y^2
*
x)^2
sage: g = x^2
*
y^2
sage: f.gcd(g)
x^2
Next we create the ideal (f, g) generated by f and g, by simply multiplying (f,g) by R (we could also write
ideal([f,g]) or ideal(f,g)).
sage: I = (f, g)
*
R; I
Ideal (x^6 + 4
*
x^4
*
y^2 + 4
*
x^2
*
y^4, x^2
*
y^2) of Multivariate Polynomial
Ring in x, y over Rational Field
sage: B = I.groebner_basis(); B
[x^6, x^2
*
y^2]
sage: x^2 in I
False
2.9. Polynomials 33
Sage Tutorial, Release 6.3
Incidentally, the Grbner basis above is not a list but an immutable sequence. This means that it has a universe, parent,
and cannot be changed (which is good because changing the basis would break other routines that use the Grbner
basis).
sage: B.parent()
Category of sequences in Multivariate Polynomial Ring in x, y over Rational
Field
sage: B.universe()
Multivariate Polynomial Ring in x, y over Rational Field
sage: B[1] = x
Traceback (most recent call last):
...
ValueError: object is immutable; please change a copy instead.
Some (read: not as much as we would like) commutative algebra is available in Sage, implemented via Singular. For
example, we can compute the primary decomposition and associated primes of I:
sage: I.primary_decomposition()
[Ideal (x^2) of Multivariate Polynomial Ring in x, y over Rational Field,
Ideal (y^2, x^6) of Multivariate Polynomial Ring in x, y over Rational Field]
sage: I.associated_primes()
[Ideal (x) of Multivariate Polynomial Ring in x, y over Rational Field,
Ideal (y, x) of Multivariate Polynomial Ring in x, y over Rational Field]
2.10 Parents, Conversion and Coercion
This section may seem more technical than the previous, but we believe that it is important to understand the meaning
of parents and coercion in order to use rings and other algebraic structures in Sage effectively and efciently.
Note that we try to explain notions, but we do not show here how to implement them. An implementation-oriented
tutorial is available as a Sage thematic tutorial.
2.10.1 Elements
If one wants to implement a ring in Python, a rst approximation is to create a class for the elements X of that ring and
provide it with the required double underscore methods such as __add__, __sub__, __mul__, of course making
sure that the ring axioms hold.
As Python is a strongly typed (yet dynamically typed) language, one might, at least at rst, expect that one implements
one Python class for each ring. After all, Python contains one type <int> for the integers, one type <float> for
the reals, and so on. But that approach must soon fail: There are innitely many rings, and one can not implement
innitely many classes.
Instead, one may create a hierarchy of classes designed to implement elements of ubiquitous algebraic structures, such
as groups, rings, skew elds, commutative rings, elds, algebras, and so on.
But that means that elements of fairly different rings can have the same type.
sage: P.<x,y> = GF(3)[]
sage: Q.<a,b> = GF(4,z)[]
sage: type(x)==type(a)
True
On the other hand, one could also have different Python classes providing different implementations of the same
mathematical structure (e.g., dense matrices versus sparse matrices)
34 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
sage: P.<a> = PolynomialRing(ZZ)
sage: Q.<b> = PolynomialRing(ZZ, sparse=True)
sage: R.<c> = PolynomialRing(ZZ, implementation=NTL)
sage: type(a); type(b); type(c)
<type sage.rings.polynomial.polynomial_integer_dense_flint.Polynomial_integer_dense_flint>
<class sage.rings.polynomial.polynomial_element_generic.Polynomial_generic_sparse>
<type sage.rings.polynomial.polynomial_integer_dense_ntl.Polynomial_integer_dense_ntl>
That poses two problems: On the one hand, if one has elements that are two instances of the same class, then one may
expect that their __add__ method will allow to add them; but one does not want that, if the elements belong to very
different rings. On the other hand, if one has elements belonging to different implementations of the same ring, then
one wants to add them, but that is not straight forward if they belong to different Python classes.
The solution to these problems is called coercion and will be explained below.
However, it is essential that each element knows what it is element of. That is available by the method parent():
sage: a.parent(); b.parent(); c.parent()
Univariate Polynomial Ring in a over Integer Ring
Sparse Univariate Polynomial Ring in b over Integer Ring
Univariate Polynomial Ring in c over Integer Ring (using NTL)
2.10.2 Parents and categories
Similar to the hierarchy of Python classes addressed to elements of algebraic structures, Sage also provides classes for
the algebraic structures that contain these elements. Structures containing elements are called parent structures in
Sage, and there is a base class for them. Roughly parallel to the hierarchy of mathematical notions, one has a hierarchy
of classes, namely for sets, rings, elds, and so on:
sage: isinstance(QQ,Field)
True
sage: isinstance(QQ, Ring)
True
sage: isinstance(ZZ,Field)
False
sage: isinstance(ZZ, Ring)
True
In algebra, objects sharing the same kind of algebraic structures are collected in so-called categories. So, there is a
rough analogy between the class hierarchy in Sage and the hierarchy of categories. However, this analogy of Python
classes and categories shouldnt be stressed too much. After all, mathematical categories are implemented in Sage as
well:
sage: Rings()
Category of rings
sage: ZZ.category()
Category of euclidean domains
sage: ZZ.category().is_subcategory(Rings())
True
sage: ZZ in Rings()
True
sage: ZZ in Fields()
False
sage: QQ in Fields()
True
2.10. Parents, Conversion and Coercion 35
Sage Tutorial, Release 6.3
While Sages class hierarchy is centered at implementation details, Sages category framework is more centered on
mathematical structure. It is possible to implement generic methods and tests independent of a specic implementation
in the categories.
Parent structures in Sage are supposed to be unique Python objects. For example, once a polynomial ring over a certain
base ring and with a certain list of generators is created, the result is cached:
sage: RR[x,y] is RR[x,y]
True
2.10.3 Types versus parents
The type RingElement does not correspond perfectly to the mathematical notion of a ring element. For example,
although square matrices belong to a ring, they are not instances of RingElement:
sage: M = Matrix(ZZ,2,2); M
[0 0]
[0 0]
sage: isinstance(M, RingElement)
False
While parents are unique, equal elements of a parent in Sage are not necessarily identical. This is in contrast to the
behaviour of Python for some (albeit not all) integers:
sage: int(1) is int(1) # Python int
True
sage: int(-15) is int(-15)
False
sage: 1 is 1 # Sage Integer
False
It is important to observe that elements of different rings are in general not distinguished by their type, but by their
parent:
sage: a = GF(2)(1)
sage: b = GF(5)(1)
sage: type(a) is type(b)
True
sage: parent(a)
Finite Field of size 2
sage: parent(b)
Finite Field of size 5
Hence, from an algebraic point of view, the parent of an element is more important than its type.
2.10.4 Conversion versus Coercion
In some cases it is possible to convert an element of one parent structure into an element of a different parent structure.
Such conversion can either be explicit or implicit (this is called coercion).
The reader may know the notions type conversion and type coercion from, e.g., the C programming language. There
are notions of conversion and coercion in Sage as well. But the notions in Sage are centered on parents, not on types.
So, please dont confuse type conversion in C with conversion in Sage!
We give here a rather brief account. For a detailed description and for information on the implementation, we refer to
the section on coercion in the reference manual and to the thematic tutorial.
36 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
There are two extremal positions concerning the possibility of doing arithmetic with elements of different rings:
Different rings are different worlds, and it makes no sense whatsoever to add or multiply elements of different
rings; even 1 + 1/2 makes no sense, since the rst summand is an integer and the second a rational.
Or
If an element r1 of one ring R1 can somehow be interpreted in another ring R2, then all arithmetic operations
involving r1 and any element of R2 are allowed. The multiplicative unit exists in all elds and many rings, and
they should all be equal.
Sage favours a compromise. If P1 and P2 are parent structures and p1 is an element of P1, then the user may explicitly
ask for an interpretation of p1 in P2. This may not be meaningful in all cases or not be dened for all elements of P1,
and it is up to the user to ensure that it makes sense. We refer to this as conversion:
sage: a = GF(2)(1)
sage: b = GF(5)(1)
sage: GF(5)(a) == b
True
sage: GF(2)(b) == a
True
However, an implicit (or automatic) conversion will only happen if this can be done thoroughly and consistently.
Mathematical rigour is essential at that point.
Such an implicit conversion is called coercion. If coercion is dened, then it must coincide with conversion. Two
conditions must be satised for a coercion to be dened:
1. A coercion from P1 to P2 must be given by a structure preserving map (e.g., a ring homomorphism). It does
not sufce that some elements of P1 can be mapped to P2, and the map must respect the algebraic structure of
P1.
2. The choice of these coercion maps must be consistent: If P3 is a third parent structure, then the composition of
the chosen coercion from P1 to P2 with the coercion from P2 to P3 must coincide with the chosen coercion
from P1 to P3. In particular, if there is a coercion from P1 to P2 and P2 to P1, the composition must be the
identity map of P1.
So, although it is possible to convert each element of GF(2) into GF(5), there is no coercion, since there is no ring
homomorphism between GF(2) and GF(5).
The second aspect - consistency - is a bit more difcult to explain. We illustrate it with multivariate polynomial rings.
In applications, it certainly makes most sense to have name preserving coercions. So, we have:
sage: R1.<x,y> = ZZ[]
sage: R2 = ZZ[y,x]
sage: R2.has_coerce_map_from(R1)
True
sage: R2(x)
x
sage: R2(y)
y
If there is no name preserving ring homomorphism, coercion is not dened. However, conversion may still be possible,
namely by mapping ring generators according to their position in the list of generators:
sage: R3 = ZZ[z,x]
sage: R3.has_coerce_map_from(R1)
False
sage: R3(x)
z
2.10. Parents, Conversion and Coercion 37
Sage Tutorial, Release 6.3
sage: R3(y)
x
But such position preserving conversions do not qualify as coercion: By composing a name preserving map from
ZZ[x,y] to ZZ[y,x] with a position preserving map from ZZ[y,x] to ZZ[a,b], a map
would result that is neither name preserving nor position preserving, in violation to consistency.
If there is a coercion, it will be used to compare elements of different rings or to do arithmetic. This is often convenient,
but the user should be aware that extending the ==-relation across the borders of different parents may easily result in
overdoing it. For example, while == is supposed to be an equivalence relation on the elements of one ring, this is not
necessarily the case if different rings are involved. For example, 1 in ZZ and in a nite eld are considered equal, since
there is a canonical coercion from the integers to any nite eld. However, in general there is no coercion between
two different nite elds. Therefore we have
sage: GF(5)(1) == 1
True
sage: 1 == GF(2)(1)
True
sage: GF(5)(1) == GF(2)(1)
False
sage: GF(5)(1) != GF(2)(1)
True
Similarly, we have
sage: R3(R1.1) == R3.1
True
sage: R1.1 == R3.1
False
sage: R1.1 != R3.1
True
Another consequence of the consistency condition is that coercions can only go from exact rings (e.g., the rationals
QQ) to inexact rings (e.g., real numbers with a xed precision RR), but not the other way around. The reason is that
the composition of the coercion from QQ to RR with a conversion from RR to QQ is supposed to be the identity on QQ.
But this is impossible, since some distinct rational numbers may very well be treated equal in RR, as in the following
example:
sage: RR(1/10^200+1/10^100) == RR(1/10^100)
True
sage: 1/10^200+1/10^100 == 1/10^100
False
When comparing elements of two parents P1 and P2, it is possible that there is no coercion between the two rings,
but there is a canonical choice of a parent P3 so that both P1 and P2 coerce into P3. In this case, coercion will take
place as well. A typical use case is the sum of a rational number and a polynomial with integer coefcients, yielding
a polynomial with rational coefcients:
sage: P1.<x> = ZZ[]
sage: p = 2
*
x+3
sage: q = 1/2
sage: parent(p)
Univariate Polynomial Ring in x over Integer Ring
sage: parent(p+q)
Univariate Polynomial Ring in x over Rational Field
Note that in principle the result would also make sense in the fraction eld of ZZ[x]. However, Sage tries to
38 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
choose a canonical common parent that seems to be most natural (QQ[x] in our example). If several potential
common parents seem equally natural, Sage will not pick one of them at random, in order to have a reliable result.
The mechanisms which that choice is based upon is explained in the thematic tutorial.
No coercion into a common parent will take place in the following example:
sage: R.<x> = QQ[]
sage: S.<y> = QQ[]
sage: x+y
Traceback (most recent call last):
...
TypeError: unsupported operand parent(s) for +: Univariate Polynomial Ring in x over Rational Field and Univariate Polynomial Ring in y over Rational Field
The reason is that Sage would not choose one of the potential candidates QQ[x][y], QQ[y][x],
QQ[x,y] or QQ[y,x], because all of these four pairwise different structures seem natural common
parents, and there is no apparent canonical choice.
2.11 Finite Groups, Abelian Groups
Sage has some support for computing with permutation groups, nite classical groups (such as SU(n, q)), nite matrix
groups (with your own generators), and abelian groups (even innite ones). Much of this is implemented using the
interface to GAP.
For example, to create a permutation group, give a list of generators, as in the following example.
sage: G = PermutationGroup([(1,2,3)(4,5), (3,4)])
sage: G
Permutation Group with generators [(3,4), (1,2,3)(4,5)]
sage: G.order()
120
sage: G.is_abelian()
False
sage: G.derived_series() # random-ish output
[Permutation Group with generators [(1,2,3)(4,5), (3,4)],
Permutation Group with generators [(1,5)(3,4), (1,5)(2,4), (1,3,5)]]
sage: G.center()
Subgroup of (Permutation Group with generators [(3,4), (1,2,3)(4,5)]) generated by [()]
sage: G.random_element() # random output
(1,5,3)(2,4)
sage: print latex(G)
\langle (3,4), (1,2,3)(4,5) \rangle
You can also obtain the character table (in LaTeX format) in Sage:
sage: G = PermutationGroup([[(1,2),(3,4)], [(1,2,3)]])
sage: latex(G.character_table())
\left(\begin{array}{rrrr}
1 & 1 & 1 & 1 \\
1 & -\zeta_{3} - 1 & \zeta_{3} & 1 \\
1 & \zeta_{3} & -\zeta_{3} - 1 & 1 \\
3 & 0 & 0 & -1
\end{array}\right)
Sage also includes classical and matrix groups over nite elds:
2.11. Finite Groups, Abelian Groups 39
Sage Tutorial, Release 6.3
sage: MS = MatrixSpace(GF(7), 2)
sage: gens = [MS([[1,0],[-1,1]]),MS([[1,1],[0,1]])]
sage: G = MatrixGroup(gens)
sage: G.conjugacy_class_representatives()
(
[1 0] [0 6] [0 4] [6 0] [0 6] [0 4] [0 6] [0 6] [0 6] [4 0]
[0 1], [1 5], [5 5], [0 6], [1 2], [5 2], [1 0], [1 4], [1 3], [0 2],
[5 0]
[0 3]
)
sage: G = Sp(4,GF(7))
sage: G
Symplectic Group of degree 4 over Finite Field of size 7
sage: G.random_element() # random output
[5 5 5 1]
[0 2 6 3]
[5 0 1 0]
[4 6 3 4]
sage: G.order()
276595200
You can also compute using abelian groups (innite and nite):
sage: F = AbelianGroup(5, [5,5,7,8,9], names=abcde)
sage: (a, b, c, d, e) = F.gens()
sage: d
*
b
**
2
*
c
**
3
b^2
*
c^3
*
d
sage: F = AbelianGroup(3,[2]
*
3); F
Multiplicative Abelian group isomorphic to C2 x C2 x C2
sage: H = AbelianGroup([2,3], names="xy"); H
Multiplicative Abelian group isomorphic to C2 x C3
sage: AbelianGroup(5)
Multiplicative Abelian group isomorphic to Z x Z x Z x Z x Z
sage: AbelianGroup(5).order()
+Infinity
2.12 Number Theory
Sage has extensive functionality for number theory. For example, we can do arithmetic in Z/NZ as follows:
sage: R = IntegerModRing(97)
sage: a = R(2) / R(3)
sage: a
33
sage: a.rational_reconstruction()
2/3
sage: b = R(47)
sage: b^20052005
50
sage: b.modulus()
97
sage: b.is_square()
True
Sage contains standard number theoretic functions. For example,
40 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
sage: gcd(515,2005)
5
sage: factor(2005)
5
*
401
sage: c = factorial(25); c
15511210043330985984000000
sage: [valuation(c,p) for p in prime_range(2,23)]
[22, 10, 6, 3, 2, 1, 1, 1]
sage: next_prime(2005)
2011
sage: previous_prime(2005)
2003
sage: divisors(28); sum(divisors(28)); 2
*
28
[1, 2, 4, 7, 14, 28]
56
56
Perfect!
Sages sigma(n,k) function adds up the k
th
powers of the divisors of n:
sage: sigma(28,0); sigma(28,1); sigma(28,2)
6
56
1050
We next illustrate the extended Euclidean algorithm, Eulers -function, and the Chinese remainder theorem:
sage: d,u,v = xgcd(12,15)
sage: d == u
*
12 + v
*
15
True
sage: n = 2005
sage: inverse_mod(3,n)
1337
sage: 3
*
1337
4011
sage: prime_divisors(n)
[5, 401]
sage: phi = n
*
prod([1 - 1/p for p in prime_divisors(n)]); phi
1600
sage: euler_phi(n)
1600
sage: prime_to_m_part(n, 5)
401
We next verify something about the 3n + 1 problem.
sage: n = 2005
sage: for i in range(1000):
... n = 3
*
odd_part(n) + 1
... if odd_part(n)==1:
... print i
... break
38
Finally we illustrate the Chinese remainder theorem.
sage: x = crt(2, 1, 3, 5); x
11
2.12. Number Theory 41
Sage Tutorial, Release 6.3
sage: x % 3 # x mod 3 = 2
2
sage: x % 5 # x mod 5 = 1
1
sage: [binomial(13,m) for m in range(14)]
[1, 13, 78, 286, 715, 1287, 1716, 1716, 1287, 715, 286, 78, 13, 1]
sage: [binomial(13,m)%2 for m in range(14)]
[1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
sage: [kronecker(m,13) for m in range(1,13)]
[1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1]
sage: n = 10000; sum([moebius(m) for m in range(1,n)])
-23
sage: Partitions(4).list()
[[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]
2.12.1 p-adic Numbers
The eld of p-adic numbers is implemented in Sage. Note that once a p-adic eld is created, you cannot change its
precision.
sage: K = Qp(11); K
11-adic Field with capped relative precision 20
sage: a = K(211/17); a
4 + 4
*
11 + 11^2 + 7
*
11^3 + 9
*
11^5 + 5
*
11^6 + 4
*
11^7 + 8
*
11^8 + 7
*
11^9
+ 9
*
11^10 + 3
*
11^11 + 10
*
11^12 + 11^13 + 5
*
11^14 + 6
*
11^15 + 2
*
11^16
+ 3
*
11^17 + 11^18 + 7
*
11^19 + O(11^20)
sage: b = K(3211/11^2); b
10
*
11^-2 + 5
*
11^-1 + 4 + 2
*
11 + O(11^18)
Much work has been done implementing rings of integers in p-adic elds or number elds other than . The interested
reader is invited to ask the experts on the sage-support Google group for further details.
A number of related methods are already implemented in the NumberField class.
sage: R.<x> = PolynomialRing(QQ)
sage: K = NumberField(x^3 + x^2 - 2
*
x + 8, a)
sage: K.integral_basis()
[1, 1/2
*
a^2 + 1/2
*
a, a^2]
sage: K.galois_group(type="pari")
Galois group PARI group [6, -1, 2, "S3"] of degree 3 of the Number Field
in a with defining polynomial x^3 + x^2 - 2
*
x + 8
sage: K.polynomial_quotient_ring()
Univariate Quotient Polynomial Ring in a over Rational Field with modulus
x^3 + x^2 - 2
*
x + 8
sage: K.units()
(3
*
a^2 + 13
*
a + 13,)
sage: K.discriminant()
-503
sage: K.class_group()
Class group of order 1 of Number Field in a with
defining polynomial x^3 + x^2 - 2
*
x + 8
sage: K.class_number()
1
42 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
2.13 Some More Advanced Mathematics
2.13.1 Algebraic Geometry
You can dene arbitrary algebraic varieties in Sage, but sometimes nontrivial functionality is limited to rings over Qor
nite elds. For example, we compute the union of two afne plane curves, then recover the curves as the irreducible
components of the union.
sage: x, y = AffineSpace(2, QQ, xy).gens()
sage: C2 = Curve(x^2 + y^2 - 1)
sage: C3 = Curve(x^3 + y^3 - 1)
sage: D = C2 + C3
sage: D
Affine Curve over Rational Field defined by
x^5 + x^3
*
y^2 + x^2
*
y^3 + y^5 - x^3 - y^3 - x^2 - y^2 + 1
sage: D.irreducible_components()
[
Closed subscheme of Affine Space of dimension 2 over Rational Field defined by:
x^2 + y^2 - 1,
Closed subscheme of Affine Space of dimension 2 over Rational Field defined by:
x^3 + y^3 - 1
]
We can also nd all points of intersection of the two curves by intersecting them and computing the irreducible
components.
sage: V = C2.intersection(C3)
sage: V.irreducible_components()
[
Closed subscheme of Affine Space of dimension 2 over Rational Field defined by:
y - 1,
x,
Closed subscheme of Affine Space of dimension 2 over Rational Field defined by:
y,
x - 1,
Closed subscheme of Affine Space of dimension 2 over Rational Field defined by:
x + y + 2,
2
*
y^2 + 4
*
y + 3
]
Thus, e.g., (1, 0) and (0, 1) are on both curves (visibly clear), as are certain (quadratic) points whose y coordinates
satisfy 2y
2
+ 4y + 3 = 0.
Sage can compute the toric ideal of the twisted cubic in projective 3 space:
sage: R.<a,b,c,d> = PolynomialRing(QQ, 4)
sage: I = ideal(b^2-a
*
c, c^2-b
*
d, a
*
d-b
*
c)
sage: F = I.groebner_fan(); F
Groebner fan of the ideal:
Ideal (b^2 - a
*
c, c^2 - b
*
d, -b
*
c + a
*
d) of Multivariate Polynomial Ring
in a, b, c, d over Rational Field
sage: F.reduced_groebner_bases ()
[[-c^2 + b
*
d, -b
*
c + a
*
d, -b^2 + a
*
c],
[-c^2 + b
*
d, b^2 - a
*
c, -b
*
c + a
*
d],
[-c^2 + b
*
d, b
*
c - a
*
d, b^2 - a
*
c, -c^3 + a
*
d^2],
[c^3 - a
*
d^2, -c^2 + b
*
d, b
*
c - a
*
d, b^2 - a
*
c],
[c^2 - b
*
d, -b
*
c + a
*
d, -b^2 + a
*
c],
2.13. Some More Advanced Mathematics 43
Sage Tutorial, Release 6.3
[c^2 - b
*
d, b
*
c - a
*
d, -b^2 + a
*
c, -b^3 + a^2
*
d],
[c^2 - b
*
d, b
*
c - a
*
d, b^3 - a^2
*
d, -b^2 + a
*
c],
[c^2 - b
*
d, b
*
c - a
*
d, b^2 - a
*
c]]
sage: F.polyhedralfan()
Polyhedral fan in 4 dimensions of dimension 4
2.13.2 Elliptic Curves
Elliptic curve functionality includes most of the elliptic curve functionality of PARI, access to the data in Cremonas
online tables (this requires an optional database package), the functionality of mwrank, i.e., 2-descents with computa-
tion of the full Mordell-Weil group, the SEA algorithm, computation of all isogenies, much new code for curves over
Q, and some of Denis Simons algebraic descent software.
The command EllipticCurve for creating an elliptic curve has many forms:
EllipticCurve([a
1
, a
2
, a
3
, a
4
, a
6
]): Returns the elliptic curve
y
2
+a
1
xy +a
3
y = x
3
+a
2
x
2
+a
4
x +a
6
,
where the a
i
s are coerced into the parent of a
1
. If all the a
i
have parent Z, they are coerced into Q.
EllipticCurve([a
4
, a
6
]): Same as above, but a
1
= a
2
= a
3
= 0.
EllipticCurve(label): Returns the elliptic curve over from the Cremona database with the given (new!) Cremona
label. The label is a string, such as "11a" or "37b2". The letter must be lower case (to distinguish it from the
old labeling).
EllipticCurve(j): Returns an elliptic curve with j-invariant j.
EllipticCurve(R, [a
1
, a
2
, a
3
, a
4
, a
6
]): Create the elliptic curve over a ring R with given a
i
s as above.
We illustrate each of these constructors:
sage: EllipticCurve([0,0,1,-1,0])
Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field
sage: EllipticCurve([GF(5)(0),0,1,-1,0])
Elliptic Curve defined by y^2 + y = x^3 + 4
*
x over Finite Field of size 5
sage: EllipticCurve([1,2])
Elliptic Curve defined by y^2 = x^3 + x + 2 over Rational Field
sage: EllipticCurve(37a)
Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field
sage: EllipticCurve_from_j(1)
Elliptic Curve defined by y^2 + x
*
y = x^3 + 36
*
x + 3455 over Rational Field
sage: EllipticCurve(GF(5), [0,0,1,-1,0])
Elliptic Curve defined by y^2 + y = x^3 + 4
*
x over Finite Field of size 5
The pair (0, 0) is a point on the elliptic curve E dened by y
2
+ y = x
3
x. To create this point in Sage type
E([0,0]). Sage can add points on such an elliptic curve (recall elliptic curves support an additive group structure
where the point at innity is the zero element and three co-linear points on the curve add to zero):
44 Chapter 2. A Guided Tour
Sage Tutorial, Release 6.3
sage: E = EllipticCurve([0,0,1,-1,0])
sage: E
Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field
sage: P = E([0,0])
sage: P + P
(1 : 0 : 1)
sage: 10
*
P
(161/16 : -2065/64 : 1)
sage: 20
*
P
(683916417/264517696 : -18784454671297/4302115807744 : 1)
sage: E.conductor()
37
The elliptic curves over the complex numbers are parameterized by the j-invariant. Sage computes j-invariant as
follows:
sage: E = EllipticCurve([0,0,0,-4,2]); E
Elliptic Curve defined by y^2 = x^3 - 4
*
x + 2 over Rational Field
sage: E.conductor()
2368
sage: E.j_invariant()
110592/37
If we make a curve with the same j-invariant as that of E, it need not be isomorphic to E. In the following example,
the curves are not isomorphic because their conductors are different.
sage: F = EllipticCurve_from_j(110592/37)
sage: F.conductor()
37
However, the twist of F by 2 gives an isomorphic curve.
sage: G = F.quadratic_twist(2); G
Elliptic Curve defined by y^2 = x^3 - 4
*
x + 2 over Rational Field
sage: G.conductor()
2368
sage: G.j_invariant()
110592/37
We can compute the coefcients a
n
of the L-series or modular form
n=0
a
n
q
n
attached to the elliptic curve. This
computation uses the PARI C-library:
sage: E = EllipticCurve([0,0,1,-1,0])
sage: print E.anlist(30)
[0, 1, -2, -3, 2, -2, 6, -1, 0, 6, 4, -5, -6, -2, 2, 6, -4, 0, -12, 0, -4,
3, 10, 2, 0, -1, 4, -9, -2, 6, -12]
sage: v = E.anlist(10000)
It only takes a second to compute all a
n
for n 10
5
:
sage: %time v = E.anlist(100000)
CPU times: user 0.98 s, sys: 0.06 s, total: 1.04 s
Wall time: 1.06
Elliptic curves can be constructed using their Cremona labels. This pre-loads the elliptic curve with information about
its rank, Tamagawa numbers, regulator, etc.
2.13. Some More Advanced Mathematics 45
Sage Tutorial, Release 6.3
sage: E = EllipticCurve("37b2")
sage: E
Elliptic Curve defined by y^2 + y = x^3 + x^2 - 1873
*
x - 31833 over Rational
Field
sage: E = EllipticCurve("389a")
sage: E
Elliptic Curve defined by y^2 + y = x^3 + x^2 - 2
*
x over Rational Field
sage: E.rank()
2
sage: E = EllipticCurve("5077a")
sage: E.rank()
3
We can also access the Cremona database directly.
sage: db = sage.databases.cremona.CremonaDatabase()
sage: db.curves(37)
{a1: [[0, 0, 1, -1, 0], 1, 1], b1: [[0, 1, 1, -23, -50], 0, 3]}
sage: db.allcurves(37)
{a1: [[0, 0, 1, -1, 0], 1, 1],
b1: [[0, 1, 1, -23, -50], 0, 3],
b2: [[0, 1, 1, -1873, -31833], 0, 1],
b3: [[0, 1, 1, -3, 1], 0, 3]}
The objects returned from the database are not of type EllipticCurve. They are elements of a database and have
a couple of elds, and thats it. There is a small version of Cremonas database, which is distributed by default with
Sage, and contains limited information about elliptic curves of conductor 10000. There is also a large optional
version, which contains extensive data about all curves of conductor up to 120000 (as of October 2005). There is
also a huge (2GB) optional database package for Sage that contains the hundreds of millions of elliptic curves in the
Stein-Watkins database.
2.13.3 Dirichlet Characters
A Dirichlet character is the extension of a homomorphism (Z/NZ)