Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 4641

Sage Beginner's Workshop

This is an introduction to the basic functionality of Sage, with an emphasis on seeing how to handle a worksheet and how to get more detailed help. We will point out a little bit of the power that Sage has hiding in it, but this is not a full-fledged tutorial. Down at the bottom of the page you will find links to some more resources.


Note that this worksheet is based upon an earlier one by Theron Hitchman. That worksheet, available here, was designed for the Sage Notebook interface. This one is written with the SageMathCloud worksheet style in mind. Other contributors include: Harald Schilly, Gustav Delius.

Worksheet Basics

The first thing to note is that a worksheet is made up of "cells." These are where you will do your programming. To evaluate a cell, you press [Shift]+[Enter]. Try it now in the cell below. Add 5 and 4.
5+4

Note that the output is marked by a grey parenthesis on the left near the line numbers, and the inputs are separated by thin, grey horizontal rulings. Also, the active cell has a light grey background cell.

Another way to evaluate a cell is to use the "run" button at the top of the worksheet. Depending on the width of your display, this button may or may not have the word "run" on it. If not, just look for the triangle pointing to the right.

Try that version now with the simple computation below.

67-5

To keep things rolling, you will often need to create new cells. At the end of a worksheet this is done automatically: there is always a set of blank lines at the bottom of a .sagews file. If you somehow manage to evaluate the last line, the page should refresh with a new blank line below the output.

The other way to make a new cell also works in the middle of a worksheet. Use your mouse or trackpad to hover over one of the thin grey horizontal rulings which separate cells. The ruling should get highlighted in blue. At this point, clicking the highlighted ruling will create a new cell directly below that ruling.

Try it now. Make a new cell between the ones below.

print('Do not touch this cell. Make a new one just below it!')
Do not touch this cell. Make a new one just below it!

It is possible to delete input cells, too. To do so, simply empty the cell and press [Backspace] or [Delete] in the active, empty cell. Try deleting a one or two of the cells just below.

Note that pressing [Backspace] at the beginning of a cell will also remove the horizontal bar between cells. This joins the two input cells into a single one. That trick might be useful to you at some point.

"not empty, empty me first to delete me"

It is useful to annotate your work by typing text right into the page. To do this, you can use two methods.

  • HTML: If you open a cell with the “decorator” as the first line, the worksheet will evaluate the rest of the cell by parsing it as html.

  • Markdown: If you open a cell with the “decorator” as the first line, the worksheet will evaluate that cell by interpreting the input following the Markdown specification, converting it to html, and displaying the html as output.

If you don’t know either, basic Markdown is easy to learn. Even if you don’t learn it, paragraphs typed in markdown will display roughly how you want them on this page.

After evaluation, the input for a Markdown or html cell will automatically hide. To reopen the input for editing, simply double click the displayed output. The text in this page has been generated with a mix of these two approaches, so you can double click them to see some examples of how this works.

Sage as a Calculator

Arithmetic works just as you would expect. The basic operations are + for addition, - for subtraction, * for multiplication, / for division, and ^ for exponentiation. Try that out now. Make some cells and evaluate some basic arithmetic operations.

Note that sage tries to remember what kind of object you are working with, so 4/5 is kept as a rational number in that form: 4/5. But if you give it a decimal expression, Sage will use finite precision arithmetic.

If you want to get a numerical (decimal) approximation to a number that is expressed differently, you can use the .n() method. This method has an option to change how many digits you want displayed. Here are some examples, all in a line. [This demonstrates how to get one compute cell to display several computations—separate them by semicolons.]

4/5; .75; (4/5).n(); pi.n(digits=300)
4/5 0.750000000000000 0.800000000000000 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127

Sage can also be used as a symbolic calculator. (It is a computer algebra system, after all.) For this to work, you have to tell Sage the names of things it should consider as symbolic variables. After that, you can create an manipulate expressions in a variety of ways.

x = var('x') expr = 1 / (1-x^2) show(expr)
1x21-\frac{1}{x^{2} - 1}

In this case, the method tells Sage to display the output nicely using LaTeX\LaTeX{}.

expr2 = - expr + expr^3 show(expr2)
1x211(x21)3\frac{1}{x^{2} - 1} - \frac{1}{{\left(x^{2} - 1\right)}^{3}}

An important part of Sage’s capabilities for symbolic expressions is the ability to simplify.

show(expr2.simplify_rational())
x42x2x63x4+3x21\frac{x^{4} - 2 \, x^{2}}{x^{6} - 3 \, x^{4} + 3 \, x^{2} - 1}

Of course, you can evaluate an expression by making a substitution of particular values for a variable, too.

expr2.subs(x = pi); expr2.subs(x = pi).n()
1/(pi^2 - 1) - 1/(pi^2 - 1)^3 0.111311464472836

How do I get help?

There are several methods for getting help while using a Sage worksheet. The most obvious one is to click the Help icon in the top left corner of the page. This takes you to the Sage documentation. Almost everything you want to know can be found there in one way or another. I say almost because Sage is an open-source project maintained by a community of mathematicians across teh world. Some people are better than others at writing documentation. Also, it is a bit intimidating that "Almost everything you ever need to know" is there! Sage is a large project with a lot of power and functionality. It can be difficult to find the thing you need unless you know how to look for it.

Thankfully, the Sage Developers have incorporated other ways to get help. The first option is called "Tab Completion." You can type part of a command and then hit the [Tab] key to get a menu of possible commands that start that way. Let's try it. In the next cell, type

then hit the [Tab] key. After you are done looking, press [Escape] to leave the pop-up menu.

Notice that there are quite a few commands that start with “ma”. We want the one for a matrix. Can you find it?

Define a matrix called A by typing the following in the next cell, and then evaluating it.

Nothing seems to happen. Sage made the matrix and put it in memory, but did not print it out. To see it, simply type A in a cell and evaluate.

There is a fundamental number attached to each matrix called its “rank.” Sage has a way to compute the rank built in. Like most built-in methods, you can access this function in two ways. First type

and evaluate. Then make a new cell and type

and evaluate. Both times you should get the number 2 as output.

What else can you do with a matrix? Sage thinks like a mathematician! In particular, it attaches “methods” to “objects” depending on their “type.”

To see all of the methods attached to an object, you can use the “dot-[Tab]” approach. Type (notice the period!) then press [Tab] to get a list of all the methods attached to the matrix A. Sage knows a lot of linear algebra, so the menu will be very big.

The other ways to get help involve using the question mark key. First, a command name followed by a question mark will evaluate to the documentation for that command.

I left the matrix command a little mysterious above. To see why I had you type it like that, evaluate this in the next cell.

To get more information, you can use the double question mark. When you evaluate the command “matrix??” you will get the Sage source code for how the matrix command works! I don’t use this very often, but if you think you find a bug in Sage, this is the place to start looking. Try it tnow to see what it looks like. Evaluate

What else should you know?

We have barely scratched the surface on Sage’s capabilities. It is important to see that Sage can be made to deal with functions, it can solve equations, and it can make nice plots. I’ll just put some examples of using Sage to do those things here.

Making a (mathematical) function and evaluating it.

f(x) = x^3 + x - 4 f
x |--> x^3 + x - 4
f(7)
346
g(x) = f.derivative()
g(4)
49

A basic 2d plot of our functions

plot([f,g],[x,-5,5])

Plots can be made in a variety of colors, this example uses some standard color names.

where = [x,-5,5] plot(f,where, color='red') + plot(g, where, color='green')

Solving an equation

solve([g(x)==0],x)
[x == -1/3*I*sqrt(3), x == 1/3*I*sqrt(3)]

I denotes the imaginary unit. Sage can handle complex numbers.

Wait. Complex roots! Really? Let’s zoom in…

P = plot(f, [x,-.2,.2], legend_label='$f$') # the default color is blue. And comments can be added after a '#' character. P+= plot(g, [x,-.2,.2], legend_label='$g$', color='red') P.show()

Yes. We see that ff is strictly increasing. Therefore, g(x)g'(x) is never zero. This is also apparent from the graph, too. Since gg is a quadratic polynomial, its two roots must come as a complex conjugate pair.

Of course, Sage has many ways of handling finding roots. Here is another one.

g; g.roots()
x |--> 3*x^2 + 1 [(-1/3*I*sqrt(3), 1), (1/3*I*sqrt(3), 1)]

What else might you like to know?

  • Sage knows LaTeX\LaTeX{}, so you can use that in Markdown or html cells. I did it with the mathematics above.
  • Sage is built on Python, a wonderful programming language. You can use any Python code you want to do your mathematics. For example, I used some Python list comprehensions (which look a lot like set-builder notation) to make the following list.
[3*n for n in range(17)]
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]

Here is another small bit of Python programming. This time it defines a simple function, and then calls that function to do a computation.

def square_and_add(x,y): z = x^2 + y^2 return z square_and_add(3,4)
25

Where do I get more instruction?

There are some good tutorials available.

You can also look through relevant documentation.

And there a useful Q & A site: