Sage Quick Reference

William Stein (based on work of P. Jipsen) (mod. by nu) GNU Free Document License, extend for your own use

Notebook

Evaluate cell: ⟨shift-enter⟩ Evaluate cell creating new cell: ⟨alt-enter⟩ Split cell: ⟨control-;⟩ Join cells: ⟨control-backspace⟩ Insert math cell: click blue line between cells Insert text/HTML cell: shift-click blue line between cells Delete cell: delete content then backspace

Command line com⟨tab⟩ complete command *bar*? list command names containing “bar” command?⟨tab⟩ shows documentation command??⟨tab⟩ shows source code a.⟨tab⟩ shows methods for object a (more: dir(a)) a. ⟨tab⟩ shows hidden methods for object a search doc("string or regexp") fulltext search of docs search src("string or regexp") search source code is previous output

Numbers Integers: ℤ = ZZ e.g. -2 -1 0 1 10^100

Rationals: ℚ = QQ e.g. 1/2 1/1000 314/100 -2/1
Reals: ℝ ≈ RR e.g. .5 0.001 3.14 1.23e10000
Complex: ℂ ≈ CC e.g. CC(1,1) CC(2.5,-3)

Double precision: RDF and CDF e.g. CDF(2.1,3)

Mod n: ℤ/nℤ = Zmod e.g. Mod(2,3) Zmod(3)(2)
Finite fields: 𝔽_{q} = GF e.g. GF(3)(2) GF(9,"a").0

Polynomials: R[x, y] e.g. S.<x,y>=QQ[] x+2*y^3

Series: R[[t]] e.g. S.<t>=QQ[[]] 1/2+2*t+O(t^2)

p-adic numbers: ℤ_{p} ≈Zp, Q_{p} ≈Qp e.g. 2+3*5+O(5^2) Algebraic closure: \overline{ℚ} = QQbar e.g. QQbar(2^(1/5)) Interval arithmetic: RIF e.g. RIF((1,1.00001))

Number field: R.<x>=QQ[]; K.<a>=NumberField(x^3+x+1)

Arithmetic

                                                     ab = a*b   \frac{a}{b} = a/b a^{b} = a^b   \sqrt{x} = sqrt(x)
                                                     \sqrt[n]{x} = x^(1/n) |x| = abs(x) log_{b}(x) = log(x,b)
                                                     Sums: ∑_{i=k}^{n} f(i) = sum(f(i) for i in (k..n))
                                                     Products: ∏_{i=k}^{n} f(i) = prod(f(i) for i in (k..n))

Constants and functions

Constants: π = pi e = e i = i ∞ = oo

                                                     ϕ = golden ratio γ = euler gamma

Approximate: pi.n(digits=18) = 3.14159265358979324

                                                     Functions:  sin cos tan sec csc cot sinh cosh tanh
                                                     sech csch coth log ln exp . . .
                                                     Python function: def f(x): return x^2

Interactive functions

Put @interact before function (vars determine controls)

                                                       @interact
                                                       def f(n=[0..4], s=(1..5), c=Color("red")):
                                                           var("x")
                                                           show(plot(sin(n+x^s),-pi,pi,color=c))

Symbolic expressions

Define new symbolic variables: var("t u v y z")

Symbolic function: e.g. f(x) = x^{2} f(x)=x^2

                                                     Relations: f==g f<=g f>=g f<g f>g
                                                     Solve f = g: solve(f(x)==g(x), x)
                                                                solve([f(x,y)==0, g(x,y)==0], x,y)
                                                     factor(...)    expand(...)    (...).simplify ...

find root(f(x), a, b) find x ∈ [a, b] s.t. f(x) ≈ 0

Calculus

                                                     lim_{x→a} f(x) = limit(f(x), x=a)
                                                     \frac{d}{dx}(f(x)) = diff(f(x),x)
                                                     \frac{∂}{∂x}(f(x, y)) = diff(f(x,y),x)
                                                       diff = differentiate = derivative
                                                     ∫ f(x)dx = integral(f(x),x)
                                                     ∫_{a}^{b} f(x)dx = integral(f(x),x,a,b)
                                                     ∫_{a}^{b} f(x)dx ≈ numerical integral(f(x),a,b)

Taylor polynomial, deg n about a: taylor(f(x),x,a,n)

2D graphics

line([(x_{1},y_{1}),…,(x_{n},y_{n})],options)

                                                                                                          polygon([(x_{1},y_{1}),. . .,(x_{n},y_{n})],options)
                                                                                                          circle((x,y),r,options)
                                                                                                          text("txt",(x,y),options)
                                                                                                          options as in plot.options,
                                                                                                            e.g. thickness=pixel, rgbcolor=(r,g,b), hue=h

where 0 ≤ r, b, g, h ≤ 1 show(graphic, options)

use figsize=[w,h] to adjust size

use aspect ratio=number to adjust aspect ratio plot(f(x),(x, x_{min}, x_{max}),options)

                                                                                                          parametric plot((f(t),g(t)),(t, t_{min}, t_{max}),options)

polar plot(f(t),(t, t_{min}, t_{max}),options)

                                                                                                          combine: circle((1,1),1)+line([(0,0),(2,2)])
                                                                                                          animate(list of graphics, options).show(delay=20)

3D graphics

line3d([(x_{1},y_{1},z_{1}),…,(x_{n},y_{n},z_{n})],options)

                                                                                                          sphere((x,y,z),r,options)
                                                                                                          text3d("txt", (x,y,z), options)
                                                                                                          tetrahedron((x,y,z),size,options)

cube((x,y,z),size,options)

                                                                                                          octahedron((x,y,z),size,options)
                                                                                                          dodecahedron((x,y,z),size,options)
                                                                                                          icosahedron((x,y,z),size,options)

plot3d(f(x, y),(x, x_{b}, x_{e}), (y, y_{b}, y_{e}),options)

                                                                                                          parametric plot3d((f,g,h),(t, t_{b}, t_{e}),options)
                                                                                                          parametric plot3d((f(u, v),g(u, v),h(u, v)),

(u, u_{b}, u_{e}),(v, v_{b}, v_{e}),options)

                                                                                                          options: aspect ratio=[1,1,1], color="red",
                                                                                                            opacity=0.5, figsize=6, viewer="tachyon"

Discrete math

⌊x⌋ = floor(x) ⌈x⌉ = ceil(x)

Remainder of n divided by k = n%k k|n iff n%k==0

n! = factorial(n)    \binom{x}{m} = binomial(x,m)
ϕ(n) = euler phi(n)
Strings: e.g. s = "Hello" = "He"+'llo'
s[0]="H"   s[-1]="o"   s[1:3]="el"   s[3:]="lo"
Lists: e.g. [1,"Hello",x] = []+[1,"Hello"]+[x]

Tuples: e.g. (1,"Hello",x) (immutable) Sets: e.g. {1, 2, 1, a} = Set([1,2,1,"a"]) (= {1, 2, a}) List comprehension ≈ set builder notation, e.g.

{f(x)|x ∈ X, x > 0} =Set([f(x) for x in X if x>0])

Graph theory

Graph: G = Graph({0:[1,2,3], 2:[4]})

Directed Graph: DiGraph(dictionary) Graph families: graphs.⟨tab⟩

Invariants: G.chromatic polynomial(), G.is planar()
Paths: G.shortest path()
Visualize: G.plot(), G.plot3d()
Automorphisms: G.automorphism group(),
G1.is isomorphic(G2), G1.is subgraph(G2)

Combinatorics

Integer sequences: sloane find(list), sloane.⟨tab⟩

Partitions: P=Partitions(n)  P.count()
Combinations: C=Combinations(list)  C.list()
Cartesian product: CartesianProduct(P,C)
Tableau: Tableau([[1,2,3],[4,5]])
Words: W=Words("abc"); W("aabca")
Posets: Poset([[1,2],[4],[3],[4],[]])
Root systems: RootSystem(["A",3])
Crystals: CrystalOfTableaux(["A",3], shape=[3,2])

Lattice Polytopes: A=random matrix(ZZ,3,6,x=7)
L=LatticePolytope(A) L.npoints() L.plot3d()

Matrix algebra

(\begin{matrix}1 \\ 2 \end{matrix}) = vector([1,2])

(\begin{matrix}1 & 2 \\ 3 & 4 \end{matrix}) = matrix(QQ,[[1,2],[3,4]], sparse=False)
(\begin{matrix}1 & 2 & 3 \\ 4 & 5 & 6 \end{matrix}) = matrix(QQ,2,3,[1,2,3, 4,5,6])
|\begin{matrix}1 & 2 \\ 3 & 4 \end{matrix}| = det(matrix(QQ,[[1,2],[3,4]]))
Av = A*v A^{−1} = A^-1 A^{t} = A.transpose()
Solve Ax = v: A\v or A.solve right(v)
Solve xA = v: A.solve left(v)

Reduced row echelon form: A.echelon form()

Rank and nullity: A.rank() A.nullity()
Hessenberg form: A.hessenberg form()

Characteristic polynomial: A.charpoly()

Eigenvalues: A.eigenvalues()

Eigenvectors: A.eigenvectors right() (also left)

Gram-Schmidt: A.gram schmidt()

Visualize: A.plot()

LLL reduction: matrix(ZZ,...).LLL()
Hermite form: matrix(ZZ,...).hermite form()

Linear algebra

Vector space K^{n} = K^n e.g. QQ^3 RR^2 CC^4

Subspace: span(vectors, field)
E.g., span([[1,2,3], [2,3,5]], QQ)

Kernel: A.right kernel() (also left) Sum and intersection: V + W and V.intersection(W)

Basis: V.basis()
Basis matrix: V.basis matrix()

Restrict matrix to subspace: A.restrict(V) Vector in terms of basis: V.coordinates(vector)

Numerical mathematics

Packages: import numpy, scipy, cvxopt

Minimization: var("x y z")

  minimize(x^2+x*y^3+(1-z)^2-1, [1,1,1])

Number theory

Primes: prime range(n,m), is prime, next prime
Factor: factor(n), qsieve(n), ecm.factor(n)

Kronecker symbol: (\frac{a}{b}) = kronecker symbol(a,b)

Continued fractions: continued fraction(x)
Bernoulli numbers: bernoulli(n), bernoulli mod p(p)

Elliptic curves: EllipticCurve([a_{1}, a_{2}, a_{3}, a_{4}, a_{6}]) Dirichlet characters: DirichletGroup(N) Modular forms: ModularForms(level, weight) Modular symbols: ModularSymbols(level,weight,sign) Brandt modules: BrandtModule(level, weight) Modular abelian varieties: J0(N), J1(N)

Group theory

G = PermutationGroup([[(1,2,3),(4,5)],[(3,4)]])
SymmetricGroup(n), AlternatingGroup(n)
Abelian groups: AbelianGroup([3,15])

Matrix groups: GL, SL, Sp, SU, GU, SO, GO

Functions: G.sylow subgroup(p), G.character table(),
  G.normal subgroups(), G.cayley graph()

Noncommutative rings

Quaternions: Q.<i,j,k> = QuaternionAlgebra(a,b)
Free algebra: R.<a,b,c> = FreeAlgebra(QQ, 3)

Python modules import module name

module name.⟨tab⟩ and help(module name)

Profiling and debugging time command: show timing information timeit("command"): accurately time command

t = cputime(); cputime(t): elapsed CPU time
t = walltime(); walltime(t): elapsed wall time

%pdb: turn on interactive debugger (command line only) %prun command: profile command (command line only)