I gave an introduction to sage tutorial at the University of Warwick Computational Group seminar today, 2 November 2017. Below is a conversion of the sage/jupyter notebook I based the rest of the tutorial on. I said many things which are not included in the notebook, and during the seminar we added a few additional examples and took extra consideration to a few different calls. But for reference, the notebook is here.

The notebook itself (as a jupyter notebook) can be found and viewed on my github (link to jupyter notebook). When written, this notebook used a Sage 8.0.0.rc1 backend kernel and ran fine on the standard Sage 8.0 release , though I expect it to work fine with any recent official version of sage. The last cell requires an active notebook to be seen (or some way to export jupyter widgets to standalone javascript or something; this either doesn’t yet exist, or I am not aware of it).

I will also note that I converted the notebook for display on this website using jupyter’s nbconvert package. I have some CSS and syntax coloring set up that affects the display.

Good luck learning sage, and happy hacking.

# Sage¶

Sage (also known as SageMath) is a general purpose computer algebra system written on top of the python language. In Mathematica, Magma, and Maple, one writes code in the mathematica-language, the magma-language, or the maple-language. Sage is python.

But no python background is necessary for the rest of today’s guided tutorial. The purpose of today’s tutorial is to give an indication about how one really *uses* sage, and what might be available to you if you want to try it out.

I will spoil the surprise by telling you upfront the two main points I hope you’ll take away from this tutorial.

- With tab-completion and documentation, you can do many things in sage without ever having done them before.
- The ecosystem of libraries and functionality available in sage is tremendous, and (usually) pretty easy to use.

## Lightning Preview¶

Let’s first get a small feel for sage by seeing some standard operations and what typical use looks like through a series of trivial, mostly unconnected examples.

```
# Fundamental manipulations work as you hope
2+3
```

You can also subtract, multiply, divide, exponentiate…

```
>>> 3-2
1
>>> 2*3
6
>>> 2^3
8
>>> 2**3 # (also exponentiation)
8
```

There is an order of operations, but these things work pretty much as you want them to work. You might try out several different operations.

Sage includes a lot of functionality, too. For instance,

```
factor(-1008)
```

```
list(factor(1008))
```

In the background, Sage is actually calling on pari/GP to do this factorization. Sage bundles lots of free and open source math software within it (which is why it’s so large), and provides a common access point. The great thing here is that you can often use sage without needing to know much pari/GP (or other software).

Sage knows many functions and constants, and these are accessible.

```
sin(pi)
```

```
exp(2)
```

Sage tries to internally keep expressions in exact form. To present approximations, use `N()`

.

```
N(exp(2))
```

```
pi
```

```
N(pi)
```

You can ask for a number of digits in the approximation by giving a `digits`

keyword to `N()`

.

```
N(pi, digits=60)
```

There are some benefits to having smart representations. In many computer algebra systems, computing (sqrt(2))^2 doesn’t give you back 2, due to finite floating point arithmetic. But in sage, this problem is sometimes avoided.

```
sqrt(2)
```

```
sqrt(2)**2
```

Of course, there are examples where floating point arithmetic gets in the way.

In sage/python, integers have unlimited digit length. Real precision arithmetic is a bit more complicated, which is why sage tries to keep exact representations internally. We don’t go into tracking digits of precision in sage, but it is usually possible to prescribe levels of precision.

Sage is written in python. You can use python functions in sage. [You can also import python libraries in sage, which extends sage’s reach significantly]. The `range`

function in python counts up to a given number, starting at 0.

```
range(16)
```

```
A = matrix(4,4, range(16))
A
```

```
B = matrix(4,4, range(-5, 11))
B
```

Sage can be smart about using the same operators in different contexts. (i.e. sage is very polymorphic). Multiplying, adding, subtracting, and dividing matrices works as expected.

```
A*B
```

There are two sorts of ways that functions are called in sage. For some functions, you create the object (in this case, the matrix A), type a dot `.`

, and then call the function.

```
A.charpoly()
```

There are some top-level functions as well.

```
factor(A.charpoly())
```

Sometimes you start with an object, such as a matrix, and you wonder what you can do with it. Sage has very good tab-completion and introspection in its notebook interface.

Try typing

```
A.
```

and hit `<Tab>`

. Sage should display a list of things it thinks it can do to the matrix A.

### Warning¶

Note that on CoCalc or external servers, tab completion sometimes has a small delay.

```
A.
```

Some of these are more meaningful than others, but you have a list of options. If you want to find out what an option does, like `A.eigenvalues()`

, then type

```
A.eigenvalues?
```

and hit enter.

```
A.eigenvalues?
```

```
A.eigenvalues()
```

If you’re really curious about what’s going on, you can type

```
A.eigenvalues??
```

which will also show you the implementation of that functionality. (You usually don’t need this).

```
A.eigenvalues??
```

There is a lot of domain-specific functionality within sage as well. We won’t dwell too much on any particular functionality in this tutorial, but for example sage knows about elliptic curves.

```
E = EllipticCurve([1,2,3,4,5])
E
```

```
# Tab complete me to see what's available
E.
```

```
E.conductor()
```

```
E.rank()
```

Sage knows about complex numbers as well. Use `i`

or `I`

to mean a $\sqrt{-1}$.

```
(1+2*I) * (pi - sqrt(5)*I)
```

```
c = 1/(sqrt(3)*I + 3/4 + sqrt(29)*2/3)
```

Sage tries to keep computations in exact form. So `c`

is stored with perfect representations of square roots.

```
c
```

But we can have sage give numerical estimates of objects by calling `N()`

on them.

```
N(c)
```

```
N(c, 20) # Keep 20 "bits" of information
```

As one more general topic before we jump into a few deeper examples, sage is also very good at representing objects in latex. Use `latex(<object>)`

to give a latex representation.

```
latex(c)
```

```
latex(E)
```

```
latex(A)
```

You can have sage print the LaTeX version in the notebook by using `pretty_print`

```
pretty_print(A)
```

## Basic Algebra¶

```
H = DihedralGroup(6)
H.list()
```

```
a = H[1]
a
```

```
a.order()
```

```
b = H[2]
b
```

```
a*b
```

```
for elem in H:
if elem.order() == 2:
print elem
```

```
# Or, in the "pythonic" way
elements_of_order_2 = [elem for elem in H if elem.order() == 2]
elements_of_order_2
```

```
rand_elem = H.random_element()
rand_elem
```

```
G_sub = H.subgroup([rand_elem])
G_sub
```

```
# Explicitly using elements of a group
H("(1,2,3,4,5,6)") * H("(1,5)(2,4)")
```

### Exercises¶

The real purpose of these exercises are to show you that it’s often possible to use tab-completion to quickly find out what is and isn’t possible to do within sage.

- What things does sage know about this subgroup? Can you find the cardinality of the subgroup? (Note that the subgroup is generated by a random element, and your subgroup might be different than your neighbor’s). Can you list all subgroups of the dihedral group in sage?
- Sage knows other groups as well. Create a symmetric group on 5 elements. What does sage know about that? Can you verify that S5 isn’t simple? Create some cyclic groups?

## Changing the Field¶

It’s pretty easy to work over different fields in sage as well. I show a few examples of this

```
# It may be necessary to use `reset('x')` if x has otherwise been defined
K.<alpha> = NumberField(x**3 - 5)
```

```
K
```

```
alpha
```

```
alpha**3
```

```
(alpha+1)**3
```

```
GF?
```

```
F7 = GF(7)
```

```
a = 2/5
a
```

```
F7(a)
```

```
var('x')
```

```
eqn = x**3 + sqrt(2)*x + 5 == 0
a = solve(eqn, x)[0].rhs()
```

```
a
```

```
latex(a)
```

```
pretty_print(a)
```

```
# Also RR, CC
QQ
```

```
K.<b> = QQ[a]
```

```
K
```

```
a.minpoly()
```

```
K.class_number()
```

### Exercise¶

Sage tries to keep the same syntax even across different applications. Above, we factored a few integers. But we may also try to factor over a number field. You can factor 2 over the Gaussian integers by:

- Create the Gaussian integers. The constructor CC[I] works.
- Get the Gaussian integer 2 (which is programmatically different than the typical integer 2), by something like
`CC[I](2)`

. `factor`

that 2.

## Some Calculus And Symbolic Manipulation¶

```
# Let's declare that we want x and y to mean symbolic variables
x = 1
y = 2
print(x+y)
reset('x')
reset('y')
var('x')
var('y')
print(x+y)
```

```
solve(x^2 + 3*x + 2, x)
```

```
solve(x^2 + y*x + 2 == 0, x)
```

```
# Nonlinear systems with complicated solutions can be solved as well
var('p,q')
eq1 = p+1==9
eq2 = q*y+p*x==-6
eq3 = q*y**2+p*x**2==24
s = solve([eq1, eq2, eq3, y==1], p,q,x,y)
s
```

```
s[0]
```

```
latex(s[0])
```

```
# We can also do some symbolic calculus
f = x**2 + 2*x + 1
f
```

```
diff(f, x)
```

```
integral(f, x)
```

```
F = integral(f, x)
F(x=1)
```

```
diff(sin(x**3), x)
```

```
# Compute the 4th derivative
diff(sin(x**3), x, 4)
```

```
# We can try to foil sage by giving it a hard integral
integral(sin(x)/x, x)
```

```
f = sin(x**2)
f
```

```
# And sage can give Taylor expansions
f.taylor(x, 0, 20)
```

```
f(x,y)=y^2+1-x^3-x
contour_plot(f, (x,-pi,pi), (y,-pi,pi))
```

```
contour_plot(f, (x,-pi,pi), (y,-pi,pi), colorbar=True, labels=True)
```

```
# Implicit plots
f(x,y) = -x**3 + y**2 - y + x + 1
implicit_plot(f(x,y)==0,(x,0,2*pi),(y,-pi,pi))
```

### Exercises¶

- Experiment with the above examples by trying out different functions and plots.
- Sage can do partial fractions for you as well. To do this, you first define your function you want to split up. Suppose you call it
`f`

. Then you use`f`

.partial_fraction(x). Try this out - Sage can also create 3d plots. Create one. Start by looking at the documentation for
`plot3d`

.

Of the various math software, sage+python provides my preferred plotting environment. I have used sage to create plots for notes, lectures, classes, experimentation, and publications. You can quickly create good-looking plots. For example, I used sage/python extensively in creating this note for my students on Taylor Series (which is a classic “hard topic” that students have lots of questions about, at least in the US universities I’m familiar with. To this day, about 1/6 of the traffic to my website is to see that page).

As a non-trivial example, I present the following interactive plot.

```
@interact
def g(f=sin(x), c=0, n=(1..30),
xinterval=range_slider(-10, 10, 1, default=(-8,8), label="x-interval"),
yinterval=range_slider(-50, 50, 1, default=(-3,3), label="y-interval")):
x0 = c
degree = n
xmin,xmax = xinterval
ymin,ymax = yinterval
p = plot(f, xmin, xmax, thickness=4)
dot = point((x0,f(x=x0)),pointsize=80,rgbcolor=(1,0,0))
ft = f.taylor(x,x0,degree)
pt = plot(ft, xmin, xmax, color='red', thickness=2, fill=f)
show(dot + p + pt, ymin=ymin, ymax=ymax, xmin=xmin, xmax=xmax)
html('$f(x)\;=\;%s$'%latex(f))
html('$P_{%s}(x)\;=\;%s+R_{%s}(x)$'%(degree,latex(ft),degree))
```

### Additional Resources and Comments¶

There are a variety of tutorials and resources for learning more about sage. I list several here.

- Sage provides some tutorials of its own. These include its Guided Tour and the Standard Sage Tutorial. The Standard Sage Tutorial is designed to take 2-4 hours to work through, and afterwards you should have a pretty good sense of the sage environment.
- PREP Tutorials are a set of tutorials created in a program sponsored by the Mathematics Association of America, aimed at working with university students with sage. These tutorials are designed for people both new to sage and to programming.

See also the main sage website.

For questions about specific things in sage, you can ask about these on StackOverflow or AskSage. You might also consider the sage-support or sage-edu mailing lists.

It isn’t necessary to know python to use sage, but a heavy sage user will benefit significantly from learning some python. Conversely, sage is very easy to use if you know python.