Tutorial: Using the Sage notebook, navigating the help system, first exercises

This worksheet is based on William Stein's JPL09__intro_to_sage.sws worksheet and the Sage days 20.5_demo worksheet and aims to be an interactive introduction to Sage through exercises. You will learn how to use the notebook and call the help.

Making this help page into a worksheet

If you are browsing this on a static web page, use the Upload worksheet button of the notebook, and copy-paste the URL of this page.

Go into the File menu at the top left of this window and click on Copy worksheet. Then, you can clear all output in the menu Action by clicking on Delete All Output.

Entering, Editing and Evaluating Input

To evaluate code in the Sage Notebook, type the code into an input cell and press shift-enter or click the evaluate link. Try it now with a simple expression (e.g., $2 + 3$). The first time you evaluate a cell takes longer than subsequent times since a new Sage process is started:

{{{id=0| 2 + 3 /// 5 }}} {{{id=1| # edit here /// }}} {{{id=2| # edit here /// }}}

Create new input cells by clicking blue line that appears between cells when you move your mouse around. Try it now:

{{{id=3| 1 + 1 /// }}} {{{id=4| # edit here /// }}}

You can go back and edit any cell by clicking in it (or using the keyboard to move up or down). Go back and change your 2+2 above to 3 + 3 and re-evaluate it.

You can also edit this text right here by double clicking on it, which will bring up the TinyMCE Javascript text editor. You can even put embedded mathematics like this $\sin(x) - y^3$ just like with LaTeX.

Help systems

There are various ways of getting help in Sage.

We detail in what follows the two last methods through examples.

Completion and contextual documentation

Start typing something and press the tab key. The interface tries to complete it with a command name. If there is more than one completion, then they are all presented to you. Remember that Sage is case sensitive, e.g. it differentiates lower case from lower case. Hence the tab completion of klein won't show you the KleinFourGroup command that build the group $\ZZ/2 \times \ZZ/2$ as a permutation group. Try it on the next cells

{{{id=5| klein /// }}} {{{id=6| Klein /// }}}

To see documentation and examples for a command, type a question mark ? at the end of the command name and press the tab key as

{{{id=7| KleinFourGroup?<tab> /// }}} {{{id=8| # edit here /// }}}

Exercise A: What is the largest prime factor of $600851475143$?

{{{id=9| factor?<tab> /// }}} {{{id=10| # edit here /// }}}

In the above exercise we do not store any mathematical data for later use. This can be done in Sage with the = symbol as in:

{{{id=11| a = 3 b = 2 print a+b /// 5 }}}

This can be understood as Sage evaluating the expression to the right of the = sign and creating the appropriate object, and then associating that object with a label, given by the right hand side. Multiple assignments can be done simultaneously:

{{{id=12| a,b = 2,3 print a,b /// 2 3 }}}

This allows us to swap variables directly:

{{{id=13| a,b = 2,3 a,b = b,a print a,b /// 3 2 }}}

Note that when we use the word variable in the computer-science sense we mean "a label associated to some data stored by Sage". Once an object is created, some methods apply to it. This means functions but instead of writing f(my_object) you write my_object.f().:

{{{id=14| p = 17 p.is_prime() /// True }}}

To know all methods of an object you can still use tab-completion. Write the name of the object followed by a dot and then press tab.:

a.<tab>

{{{id=15| # edit here /// }}} {{{id=16| # edit here /// }}}

Exercise B: Create the Permutation 51324 and assign it to the variable p.

{{{id=17| Permutation?<tab> /// }}} {{{id=18| # edit here /// }}}

What is the inverse of p ?

{{{id=19| p.inv<tab> /// }}} {{{id=20| # edit here /// }}}

Does p have the pattern 123 ? What about 1234 ? And 312 ? (even if you don't know what a pattern is, you should be able to find a command that does this).

{{{id=21| p.pat<tab> /// }}} {{{id=22| # edit here /// }}}

Some linear algebra

Exercise C: Use the matrix command to create the following matrix.

\[
    M = \left(\begin{array}{rrrr} 
    10 & 4 & 1 & 1 \\
    4 & 6 & 5 & 1 \\
    1 & 5 & 6 & 4 \\
    1 & 1 & 4 & 10
    \end{array} \right)
\]


{{{id=23| matrix?<tab> /// }}} {{{id=24| # edit here /// }}}

Then using methods of the matrix:

  1. Find the determinant of the matrix.
  2. Find the echelon form of the matrix.
  3. Find the eigenvalues of the matrix.
  4. Find the kernel of the matrix.
  5. Find the LLL decomposition of the matrix.
{{{id=25| # edit here /// }}} {{{id=26| # edit here /// }}}

Now you know how to access the different methods of matrices:

  1. Create the vector $v = (1,-1,-1,1)$.
  2. Compute the products: $M*v$ and $v*M$.
{{{id=27| vector?<tab> /// }}} {{{id=28| # edit here /// }}}

Note

Vectors in Sage are row vectors. A method such as eigenspaces might not return what you expect, so it is best to specify eigenspaces_left or eigenspaces_right instead. Same thing for kernel (left_kernel or right_kernel), and so on.

Some Plotting

The plot command allows you to draw plots of functions. Recall that you can access the documentation by pressing the tab key after writing plot? in a cell.:

{{{id=29| plot?<tab> /// }}} {{{id=30| # edit here /// }}}

Here is a simple example:

{{{id=31| var('x') # make sure x is a symbolic variable plot(sin(x^2), (x,0,10)) /// }}}

Here is a more complicated plot. Try to change every single input to the plot command in some way, evaluating to see what happens:

{{{id=32| P = plot(sin(x^2), (x,-2,2), rgbcolor=(0.8,0,0.2), thickness=3, linestyle='--', fill='axis') show(P, gridlines=True) /// }}}

Above we used the show command to show a plot after it was created. You can also use P.show instead:

{{{id=33| P.show(gridlines=True) /// }}}

Try putting the cursor right after P.show( and pressing tab to get a list of the options for how you can change the values of the given inputs.:

{{{id=34| P.show( /// }}}

Plotting multiple functions at once is as easy as adding them together:

{{{id=35| P1 = plot(sin(x), (x,0,2*pi)) P2 = plot(cos(x), (x,0,2*pi), rgbcolor='red') P1 + P2 /// }}}

Symbolic Expressions

Here is an example of a symbolic function:

{{{id=36| f(x) = x^4 - 8*x^2 - 3*x + 2 f(x) /// x^4 - 8*x^2 - 3*x + 2 }}} {{{id=37| f(-3) /// 20 }}}

This is an example of a function in the mathematical variable $x$. When Sage starts, it defines the symbol $x$ to be a mathematical variable. If you want to use other symbols for variables, you must define them first.:

{{{id=38| x^2 /// x^2 }}} {{{id=39| u + v /// Traceback (click to the left of this block for traceback) NameError: name 'u' is not defined }}} {{{id=40| var('u v') u + v /// u + v }}}

It is possible, though, to define symbolic functions without first defining the variables.:

{{{id=41| f(w) = w^2 f(3) /// 9 }}}

Exercise D: Define the symbolic function $f(x) = x \sin(x^2)$. Plot $f$ on the domain $[-3,3]$ and colour it red. Use the find_root method to numerically approximate the root of $f$ on the interval $[1,2]$:

{{{id=42| # edit here /// }}}

Compute the tangent line to $f$ at $x=1$:

{{{id=43| # edit here /// }}}

Plot $f$ and the tangent line to $f$ at $x=1$ in one image:

{{{id=44| # edit here /// }}}

Exercise E (Advanced): Solve the following equation for $y$

\[ y = 1 + x y^2 \]

There are two solutions, take the one for which $\lim_{x\to0}y(x) = 1$. (Don't forget to create the variables $x$ and $y$!).:

{{{id=45| # edit here /// }}}

Expand $y$ as a truncated Taylor series around $0$ and containing $n=10$ terms.

{{{id=46| # edit here /// }}}

Do you recognize the coefficients of the Taylor series expansion? You might want to use the On-Line Encyclopedia of Integer Sequences, or better yet, Sage's command sloane_find which queries the encyclopedia:

sloane_find?<tab>

{{{id=47| # edit here /// }}}