Académique Documents
Professionnel Documents
Culture Documents
FIRST STEPS
Figure 1.1 – The first occurrence of the name Sage, on a handwritten note of
W. Stein.
At first, Sage was both an acronym and a reference to the “sage” medicinal
plant. When the system later expanded to cover much of mathematics, the
acronym part was dropped. As Sage came to be known in larger circles,
and to avoid confusion with, for example, the business management software
of the same name, the official name was changed to SageMath. When the
context is unambiguous, for example in this book, it is traditional to just
use Sage.
sage: ( 1 + 2 * (3 + 5) ) * 2
34
The * character above stands for multiplication, which should not be omitted,
even in expressions like 2x. The power operation is written ˆ or **:
sage: 2^3
8
sage: 2**3
8
Please note the exact computation: the result of the above division, after sim-
plification, is the rational number 10/3 and not an approximation like 3.33333.
There is no limit1 to the size of integers or rational numbers:
sage: 2^10
1024
sage: 2^100
1267650600228229401496703205376
sage: 2^1000
1071508607186267320948425049060001810561404811705533607443750\
3883703510511249361224931983788156958581275946729175531468251\
8714528569231404359845775746985748039345677748242309854210746\
0506237114187795418215304647498358194126739876755916554394607\
7062914571196477686542167660429831652624386837205668069376
Integer operations
integer division a // b
remainder a % b
quotient and remainder divmod(a,b)
factorial n! factorial(n)
binomial coefficient n
k
binomial(n,k)
sage: arccos(sin(pi/3))
arccos(1/2*sqrt(3))
sage: sqrt(2)
sqrt(2)
sage: exp(I*pi/7)
e^(1/7*I*pi)
One does not always get the expected results. Indeed, only few simplifications
are done automatically. If needed, it is possible to explicitly call a simplification
function:
sage: simplify(arccos(sin(pi/3)))
1/6*pi
We will see in §2.1 how to tune the simplification of expressions. Of course, it
is also possible to compute numerical approximations of the results, with an
accuracy as large as desired:
sage: numerical_approx(6*arccos(sin(pi/3)), digits=60)
3.14159265358979323846264338327950288419716939937510582097494
sage: numerical_approx(sqrt(2), digits=60)
1.41421356237309504880168872420969807856967187537694807317668
sage: arc<tab>
Possible completions are:
arc arccos arccosh arccot arccoth arccsc arccsch
arcsec arcsech arcsin arcsinh arctan arctan2 arctanh
e
To restore the original value, one can type for example:
sage: from sage.all import pi
or alternatively
sage: restore()
which restores to their default value all predefined variables and functions. The
reset() function performs an even more complete reset, in particular it clears all
user-defined variables.
2*z + 3
How can we give a value to a symbolic variable appearing in an expression? One
uses the substitution operation, as in:
sage: x = SR.var('x')
sage: expr = sin(x); expr
sin(x)
sage: expr(x=1)
sin(1)
The substitution in symbolic expressions is discussed in detail in the next chapter.
Exercise 1. Explain step by step what happens during the following instructions:
sage: u = SR.var('u')
sage: u = u+1
sage: u = u+1
sage: u
u + 2
3 In this book, we will often write x = var(’x’) instead of the better but cumbersome form
arctan(sqrt(2)) and pi/2-arctan(1/sqrt(2)) are considered equal. In fact, when one compares
two expressions with bool(x==y), Sage tries to prove that their difference is zero, and returns
True if that succeeds.
18 CHAP. 2. ANALYSIS AND ALGEBRA
+ *
^ * 2 + +
x 2 3 x x 1 x 2
Figure 2.1 – Two symbolic expressions representing the same mathematical object.
Symbolic Functions
sage: p = (x+y)*(x+1)^2
sage: p2 = p.expand(); p2
x^3 + x^2*y + 2*x^2 + 2*x*y + x + y
whereas the collect method groups terms together according to the powers of a
given variable:
sage: p2.collect(x)
x^3 + x^2*(y + 2) + x*(2*y + 1) + y
Those methods do not only apply to polynomials in symbolic variables, but also
to polynomials in more complex sub-expressions like sin x:
sage: ((x+y+sin(x))^2).expand().collect(sin(x))
x^2 + 2*x*y + y^2 + 2*(x + y)*sin(x) + sin(x)^2
For rational functions, the combine method enables us to group together terms
with common denominator; the partial_fraction method performs the partial
fraction decomposition over Q. (To specify a different decomposition field, we
refer the reader to §7.4.)
The more useful representations are the expanded form for a polynomial, and
the reduced form P/Q with P and Q expanded in the case of a fraction. When
20 CHAP. 2. ANALYSIS AND ALGEBRA
(x−1)x y2 b c 1
Fraction r= x2 −7
+ x2 −7
+ a
+ a
+ x+1
(x−1)x+y 2 b+c 1
r.combine() x2 −7
+ a
+ x+1
1
Fraction r=
(x3 +1)y2
−(x−2) 1
r.partial_fraction(x) + 3 (x+1)y 2
3 (x2 −x+1)y 2
two polynomials or fractions are written in this form, it suffices to compare their
coefficients to decide if they are equal: we say they are in normal form.
2.1.4 Assumptions
During a computation, the symbolic variables appearing in expressions are in
general considered as taking potentially any value in the complex plane. This
22 CHAP. 2. ANALYSIS AND ALGEBRA
2.2 Equations
We now deal with equations and how to solve them; the main functions are
summarised in Table 2.3.
Scalar equations
Symbolic solution solve
Roots (with multiplicities) roots
Numerical solving find_root
sage: eq.rhs()
0
then solve it for z with solve:
sage: solve(eq,
√
z)
√
2 cos(ϕ)2 −1−1 2 cos(ϕ)2 −1+1
z=− cos(ϕ) , z = cos(ϕ)
"
√ 1 √ √ ( 13 ) √
1 1 − I 3−1
− I 3+1 3 59 − + √ √ 1 ,1 ,
2 18 2 1 1 (3)
3 18 3 59 − 2
√ 1 √ √ (3)
1 √
− −I 3 − 1
− 1 1
−I 3 + 1 3 59 − + √ √ 1 ,1 ,
2 18 2 1 1 (3)
3 18 3 59 − 2
( 31 )
√ √
1 1 −2
3 59 − + √ √ 1 ,1
18 2 1 1 (3)
3 18 3 59 − 2
sage: solve(x^(1/x)==(1/x)^x, x)
[(1/x)^x == x^(1/x)]
sage: y = function('y')(x)
sage: desolve(diff(y,x,x) + x*diff(y,x) + y == 0, y, [0,0,1])
-1/2*I*sqrt(2)*sqrt(pi)*erf(1/2*I*sqrt(2)*x)*e^(-1/2*x^2)
2.3 Analysis
This section is a quick introduction of useful functions in real analysis. For more
advanced usage or more details, we refer to the following chapters, in particular
about numerical integration (Chapter 14), non-linear equations (Chapter 12), and
differential equations (Chapter 10).
2.3.1 Sums
The sum function computes symbolic sums. Let us obtain for example the sum of
the n first positive integers:
sage: k, n = var('k, n')
sage: sum(k, k, 1, n).factor()
1
2 (n + 1)n
To compute the corresponding power series, we should tell Sage that the
modulus2 of q is less than 1:
sage: assume(abs(q) < 1)
sage: sum(a*q^k, k, 0, infinity)
a
− q−1
This recurrence is easily obtained when computing by two different methods the telescopic
(k + 1)p+1 − kp+1 .
P
sum
0≤k≤n
2.3.2 Limits
To determine a limit, we use the limit command or its alias lim. Let us compute
the following limits:
√3
x−2
a) lim √ ;
x→8 3
x + 19 − 3
cos π4 − x − tan x
b) limπ .
x→ 4 1 − sin π4 + x
2.3.3 Sequences
The above functions enable us to study sequences of numbers. We illustrate this
by comparing the growth of an exponential sequence and a geometric sequence.
100
n
Example. (A sequence study) Let us consider the sequence un = 100 n.
Compute the first 10 terms. How does the sequence vary? What is the sequence
limit? From which value of n does un ∈ 0, 10−8 hold?
2.3. ANALYSIS 29
1.6e90
1.4e90
1.2e90
1e90
8e89
6e89
4e89
2e89
0
5 10 15 20 25 30 35 40
The sequence is thus increasing up to index 21, then decreasing after index
22.
30 CHAP. 2. ANALYSIS AND ALGEBRA
sage: ((1+arctan(x))^(1/x)).series(x==0, 3)
(e) + (− 12 e)x + ( 18 e)x2 + O x3
sage: (ln(2*sin(x))).series(x==pi/6, 3)
√ 2
3
( 3)(− 61 π + x) + (−2)(− 61 π + x) + O − 216
1
(π − 6 x)
sage: k = var('k')
sage: sum(1/k^2, k, 1, infinity),\
....: sum(1/k^4, k, 1, infinity),\
....: sum(1/k^5, k, 1, infinity)
1 2 1 4
6 π , 90 π , ζ(5)
We notice that the partial sum of the first 12 terms already yields 95 significant
digits of π!
Example. (Convergence of a series) Let us study the convergence of the
series p
X
sin π 4 n2 + 1 .
n≥0
We can then apply the taylor function to this new expression of the general
term:
2.3.6 Derivatives
The derivative function (with alias diff) computes the derivative of a symbolic
expression or function.
sage: diff(sin(x^2), x)
2*x*cos(x^2)
sage: function('f')(x); function('g')(x); diff(f(g(x)), x)
f(x)
g(x)
D[0](f)(g(x))*diff(g(x), x)
sage: diff(ln(f(x)), x)
diff(f(x), x)/f(x)
2.3.8 Integrals
To compute an indefinite or definite integral, we use integrate as a function or
method (or its alias integral):
sage: sin(x).integral(x, 0, pi/2)
1
sage: integrate(1/(1+x^2), x)
arctan(x)
3A function f is said harmonic when its Laplacian ∆f = ∂12 f + ∂22 f is zero.
34 CHAP. 2. ANALYSIS AND ALGEBRA
√
Z 1/ 2
f (t)
2. For N ∈ N, let us define J = dt. Prove lim SN = J.
0
1 − t8 N →+∞
This fabulous formula was found on September 19, 1995 by Simon Plouffe, in
collaboration with David Bailey and Peter Borwein. Thanks to computation
derived from the BBP formula, the 4 000 000 000 000 000-th digit of π in radix 2
was computed in 2001.
−ı ∧ →
1. Show that →
− →
−
D = − 1e S and deduce the ellipse eccentricity.
−ı is colinear with the vector →
2. Show that →
− → −
S ∧ D.
−ı ∧ →
3. Show that →
− →
−
N = − pe S and deduce the ellipse parameter p.
4. Compute the half major axis a of the ellipse in term of the parameter p and the
eccentricity e.
5. Numerical application: in the plane with a Cartesian coordinate system, we
consider the following points:
A1 ( 01 ) , A2 ( 22 ) , A3 ( 3.5
0 ), O ( 00 ) .
Matrix reduction
Eigenvalues of a matrix eigenvalues
Eigenvectors of a matrix eigenvectors_right
Jordan normal form reduction jordan_form
Minimal polynomial minimal_polynomial
Characteristic polynomial characteristic_polynomial
Exercise 11 (A matrix equation). Let us recall the factorisation lemma for linear
maps. Let E, F, G be K-vector spaces of finite dimension. Let u ∈ L(E, F ) and
v ∈ L(E, G). Then the following assertions are equivalent:
i) there exists w ∈ L(F, G) such that v = w ◦ u,
ii) Ker(u) ⊂ Ker(v).
We search all solutions to this problem in a concrete case. Let
−2 1 1
1 2 −1
A= 8 1 −5 and C= 2 −1 −1 .
4 3 −3 −5 0 3
The minimal polynomial of A admits a simple root and a double root; thus A
is not diagonalisable. However, its minimal polynomial being split into linear
factors, A is triangularisable.
sage: A.eigenvectors_right()
[(1, [(1, −1, 1)] , 1) , (−2, [(1, −1, 0)] , 2)]
sage: A.jordan_form(transformation=True)
1 0 0 1 1 1
0 −2 1 , −1 −1 0
0 0 −2 1 0 −1
1 −1/2
Example. Let us diagonalise the matrix A = −1/2 −1
. We first try the
jordan_form function:
sage: A = matrix(QQ, [[1,-1/2],[-1/2,-1]])
sage: A.jordan_form()
Traceback (most recent call last):
...
RuntimeError: Some eigenvalue does not exist in Rational Field.
A small difficulty appears here: the eigenvalues are not all rational.
sage: A = matrix(QQ, [[1,-1/2],[-1/2,-1]])
sage: A.minimal_polynomial()
x^2 - 5/4
We therefore have to change the base field.
sage: R = QQ[sqrt(5)]
sage: A = A.change_ring(R)
sage: A.jordan_form(transformation=True, subdivide=False)
1
sqrt 5 0
1
1
2 ,
1 −sqrt + 2 sqrt + 2
0 − sqrt 5 5 5
2
This is to be interpreted as:
1 √
2 5 √ 0 √ 1 √ 1
,
0 − 12 5 − 5+2 5+2
√ √
√2 6 √2
Example. Let us diagonalise the matrix A = √6 √3 3 .
2 3 1
Here, we have to work in an extension of degree 4 of the field Q, for example
as follows.
sage: K.<sqrt2> = NumberField(x^2 - 2)
sage: L.<sqrt3> = K.extension(x^2 - 3)
sage: A = matrix(L, [[2, sqrt2*sqrt3, sqrt2], \
....: [sqrt2*sqrt3, 3, sqrt3], \
....: [sqrt2, sqrt3, 1]])
2.4. BASIC LINEAR ALGEBRA 39
sage: A.jordan_form(transformation=True)
6 0 0 √ √ 1 1 0
0 0 0 , 1 2 3
√ √0 √1
2
0 0 0 1
2 2 − 2 − 3
40 CHAP. 2. ANALYSIS AND ALGEBRA
Programming and Data Structures
3
The two preceding chapters introduced mathematical computations using one-line
commands, but Sage also allows programs with sequences of instructions.
The Sage computer algebra system is in fact an extension of the Python1 com-
puter language, and allows, with a few exceptions, to use the Python programming
constructs.
The commands described in the previous chapters show that it is not necessary
to know the Python language to use Sage; this chapter explains how to use
the Python programming structures within Sage. Since we only present basic
programming, this chapter can be skipped by the reader fluent in Python; the
examples are chosen among the most classical ones encountered in mathematics,
so that the reader can quickly grasp the Python programming constructs, by
analogy with known programming languages.
This chapter presents in particular the paradigm of structured programming
with loops and tests, then describes functions dealing with lists and other data
structures.
3.1 Syntax
3.1.1 General Syntax
The instructions are generally processed line by line. Python considers the
sharp symbol “#” as the beginning of a comment, until the end of the line.
The semi-colon “;” separates several instructions written on the same line:
1 The Sage version considered here uses Python 2.7, which slightly differs from Python 3.
42 CHAP. 3. PROGRAMMING AND DATA STRUCTURES
In addition to these keywords, we have the constants None (empty value, named
NULL in other languages), True and False, and several functions predefined by
Python or Sage like len, cos and integrate. It is better not to use these as
variable names, otherwise some functionalities might no longer be available. The
interpreter knows some additional commands, like quit to exit the Sage session.
We will discover other commands like time or timeit later in this book.
Some symbols have a special meaning in Sage. They are explained in Table 3.2.
3.1. SYNTAX 43
sage: a, b = b, a
sage: a, b
(20, 10)
The assignment a, b = b, a is equivalent to swapping the values of a and b
using an auxiliary variable:
sage: temp = a; a = b; b = temp # equivalent to: a, b = b, a
The following trick swaps the values of a and b without any auxiliary variable,
using additions and subtractions:
sage: x, y = var('x, y'); a = x ; b = y
sage: a, b
(x, y)
sage: a = a + b ; b = a - b ; a = a - b
sage: a, b
(y, x)
The instruction a = b = c = 0 assigns the same value, here 0, to several
variables; the instructions x += 5 and n *= 2 are respectively equivalent to x =
x+5 and n = n*2.
The comparison between two objects is performed by the double equal sign
“==”:
sage: 2 + 2 == 2^2, 3 * 3 == 3^3
(True, False)
3.2 Algorithmics
The paradigm of structured programming consists in designing a computer program
as a finite sequence of instructions, which are executed in order. Those instructions
can be atomic or composed:
3.2.1 Loops
Enumeration Loops. An enumeration loop performs the same computation
for all integer values of an index k ∈ {a, . . . , b}: the following example3 outputs
the beginning of the multiplication table by 7:
3 When using Sage in a terminal, such a block of instructions must be ended by an additional
empty line, which will be implicit in the whole book. This is not necessary when using Sage
through a web browser.
3.2. ALGORITHMICS 45
sage: S = 0 sage: S = 0
sage: for k in [1..3]: sage: for k in [1..3]:
... S = S+k ... S = S+k
sage: S = 2*S ... S = 2*S
sage: S sage: S
On the left the instruction S = 2*S is executed only once at the end of the loop,
while on the right it is executed at every iteration, which explains the different
results:
S = (0 + 1 + 2 + 3) · 2 = 12 S = ((((0 + 1) · 2) + 2) · 2 + 3) · 2 = 22.
This kind of loop will be useful to compute a given term of a recurrence, cf. the
examples at the end of this section.
The syntax for k in [a..b] for an enumeration loop is the simplest one
and can be used without any problem for 104 or 105 iterations; its drawback
is that it explicitly constructs the list of all possible values of the loop variable
before executing the iteration block, however it manipulates Sage integers of type
Integer (see §5.3.1). Several ..range functions allow iterations with two possible
choices. The first choice is: either construct the list of possible values before
starting the loop, or determine those values along with the loop iterations. The
second choice is between Sage integers4 (Integer) and Python integers (int),
those two integer types having slightly different properties. In case of doubt, the
[a..b] form should be preferred.
While Loops. The other kind of loops are the while loops. Like the enumeration
loops, they execute a certain number of times the same sequence of instructions;
4 The commands srange, sxrange and [...] also work on rational and floating-point numbers:
however, here the number of repetitions is not known a priori, but depends on a
condition.
The while loop, as its name says, executes instructions while a given condition
is fulfilled. The following example computes the sum of the squares of non-negative
integers whose exponential is less or equal to 106 , i.e., 12 + 22 + · · · + 132 :
sage: S = 0 ; k = 0 # The sum S starts to 0
sage: while e^k <= 10^6: # e^13 <= 10^6 < e^14
....: S = S + k^2 # accumulates the squares k^2
....: k = k + 1
sage: S
819
The last instruction returns the value of the variable S and outputs the result:
X 13
X
S= k2 = k 2 = 819, e13 ≈ 442413 ≤ 106 < e14 ≈ 1202604.
k∈N k=0
ek ≤106
The above instruction block contains two assignments: the first one accumulates
the new term, and the second one moves to the next index. Those two instructions
are indented in the same way inside the while loop structure.
The following example is another typical example of while loop. For a given
number x ≥ 1, it seeks the unique integer n ∈ N satisfying 2n−1 ≤ x < 2n , i.e.,
the smallest integer with x < 2n . The program below compares x to 2n , whose
value is successively 1, 2, 4, 8, etc.; it performs this computation for x = 104 :
sage: x = 10^4; u = 1; n = 0 # invariant: u = 2^n
sage: while u <= x: n = n+1; u = 2*u # or n += 1; u *= 2
sage: n
14
As long as the condition 2n ≤ x is satisfied, this program computes the new values
n + 1 and 2n+1 = 2 · 2n of the two variables n and u, and stores them in place
of n and 2n . The loop ends when the condition is no longer fulfilled, i.e., when