Introductory Sage Tutorial - Welcome!

This Sage worksheet is the first in a series of tutorials developed for the MAA PREP Workshop "Sage: Using Open-Source Mathematics Software with Undergraduates" (funding provided by NSF DUE 0817071).  It is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA).  

Click here to go straight to the main content of the tutorial.

Getting a Live Copy of a Worksheet

The first part of the tutorial is to load this worksheet, of course!   You'll need your own copy of the worksheet on the server.  It should look like this at the top:

Except, of course, your username will appear!  If you already have a live copy, please skip below.

If you don't see this, take another look at the top of the screen.  Does it look like this?    

If so, you need to log in!  Click the link at the upper left and follow usual website login creation/login procedures.  (You will know the magic word if there is one.)

Otherwise, it should look like this:

It should also look like this once you log in.   Now just click 'Edit this' so that it looks like this!  

Then you can continue with the tutorial.

 

The main part of the tutorial has the following sections:

This tutorial only introduces the most basic level of functionality.  Later tutorials address topics such as calculus, advanced plotting, and a wide variety of specific mathematical topics.

Evaluating Sage Commands

(i.e., How do I get Sage to do some math?)

Below, and throughout this worksheet, are little boxes called input cells or code cells.   They should be about the width of your browser.  

Evaluating the content of an input cell is very easy.

Try evaluating the following cell.

{{{id=2| 2+2 /// 4 }}}

Sage prints out its response just below the cell (that's the "4" above, so Sage confirms that $2+2=4$).   Note also that Sage has automatically made the next cell active after you evaluated your first cell.

You can also evaluate a cell using a keyboard shortcut.  

We call this "Shift-Enter".  Try doing Shift-Enter with this cell.
{{{id=4| factor(2010) /// 2 * 3 * 5 * 67 }}}

An input cell isn't much use if it can only do one thing, so you can edit a cell and evaluate it again.  Just click inside, and then make any changes you wish by typing as usual.  

Try changing the number "2010" above to "2011" and evaluate the cell to find its factorization (surprised?); then try your own favorite number.

To do more math, we'll need to be able to create new input cells.  This is also easy.

If for some reason you need to remove or delete an input cell, just delete all the text inside of it, and then press backspace in the now-empty cell.

Try creating a few new input cells below, doing some arithmetic in those cells, and then deleting one of the input cells.

{{{id=6| /// }}} {{{id=125| /// }}}

Functions in Sage

To start out, let's explore how to define and use functions in Sage.

For a typical mathematical function, it's pretty straightforward to define it.  Below, we define the function $$f(x)=x^2\; .$$

{{{id=8| f(x)=x^2 /// }}}

Since all we wanted was to create the function $f(x)$, Sage just does this and doesn't print anything out back to us.

We can check the definition by asking Sage what $f(x)$ is:

{{{id=111| f(x) /// x^2 }}}

If we just ask Sage what $f$ is (as opposed to $f(x)$), Sage prints out the standard mathematical notation for a function that maps a variable $x$ to the value $x^2$ (with the "maps to" arrow $\mapsto$ as "|-->").

{{{id=126| f /// x |--> x^2 }}}

We can evaluate $f$ at various values.

{{{id=103| f(3) /// 9 }}} {{{id=166| f(3.1) /// 9.61000000000000 }}}

Naturally, we are not restricted to $x$ as a variable.  In the next cell, we define the function $g(y)=2y-1$.

{{{id=167| g(y)=2*y-1 /// }}}

However, we need to make sure we do define a function if we use a new variable.  In the next cell, we see what happens if we try to use a random input by itself.

{{{id=169| z^2 /// Traceback (most recent call last): File "", line 1, in File "_sage_input_12.py", line 10, in exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("el4y"),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single') File "", line 1, in File "/tmp/tmpmnlwvp/___code___.py", line 3, in exec compile(u'z**_sage_const_2 ' + '\n', '', 'single') File "", line 1, in NameError: name 'z' is not defined }}}

This is explained in some detail in following tutorials.  At this point, it suffices to know using the function notation (like "g(y)") tells Sage you are serious about "y" being a variable.

One can also do this with the "var('z')" notation below.

{{{id=171| var('z') z^2 /// z^2 }}}

This also demonstrates that we can put several commands in one cell, each on a separate line.  The output of the last command (if any) is printed as the output of the cell.

Sage knows various common mathematical constants, like $\pi$ ("pi") and $e$.

{{{id=109| f(pi) /// pi^2 }}} {{{id=115| f(e^-1) /// e^(-2) }}}

In order to see a numeric approximation for an expression, just type the expression inside the parentheses of "N()".

{{{id=118| N(f(pi)) /// 9.86960440108936 }}}

Another option, often more useful in practice, is having the expression immediately followed by ".n()" (note the dot).

{{{id=117| f(pi).n() /// 9.86960440108936 }}}

For now, we won't go in great depth explaining the reasons behind this syntax, which may be new to you.   For those who are interested, Sage often uses this type of syntax (known as "object-oriented") because...

  • Sage uses the Python programming language, which uses this syntax, 'under the hood', and 
  • Because it makes it easier to distinguish among
    • The mathematical object,
    • The thing you are doing to it, and
    • Any ancillary arguments.

For example, the following numerically evaluates ('n') the constant $\pi$ ('pi') to twenty digits ('digits=20').

{{{id=158| pi.n(digits=20) /// 3.1415926535897932385 }}}

Sage has lots of common mathematical functions built in, like $\sqrt{x}$ ("sqrt(x)") and $\ln(x)$ ("ln(x)" or "log(x)").

{{{id=120| log(3) /// log(3) }}}

Notice that there is no reason to numerically evaluate $\log(3)$, so Sage keeps it symbolic.  The same is true in the next cell - $2\log(3)=\log(9)$, but there isn't any reason to do that; after all, depending on what you want, $\log(9)$ may be simpler or less simple than you need.

{{{id=163| log(3)+log(3) /// 2*log(3) }}} {{{id=161| log(3).n() /// 1.09861228866811 }}}

(Incidentally, one can also achieve this by telling Sage you are using an approximate decimal rather than an integer; this is more advanced, so we won't elaborate here.)

{{{id=175| log(3.) /// 1.09861228866811 }}} {{{id=121| sqrt(2) /// sqrt(2) }}}

If we want this to look nicer, we can use the "show" command.  We'll see more of this sort of things below.

{{{id=164| show(sqrt(2)) ///
\newcommand{\Bold}[1]{\mathbf{#1}}\sqrt{2}
}}} {{{id=149| sqrt(2).n() /// 1.41421356237310 }}}

Do you remember what $f$ does?

{{{id=150| f(sqrt(2)) /// 2 }}}

We can also plot functions easily.  

{{{id=122| plot(f, (x,-3,3)) /// }}}

In another tutorial, we will go more in depth with plotting.  Here, note that the preferred syntax has the variable and endpoints for the plotting domain in parentheses, separated by commas.

If you are feeling bold, plot the "sqrt" function in the next cell between 0 and 100.

{{{id=108| /// }}}

Help inside Sage

There are various ways to get help for doing things in Sage.  Here are several common ways to get help as you are working in a Sage worksheet.

Documentation

Sage includes extensive documentation covering thousands of functions, with many examples, tutorials, and other helps. 

  • One way to access these is to click the "Help" link at the top right of any worksheet, then click your preferred option at the top of the help page.
  • They are also available any time online at the Sage website, which has many other links, like video introductions.  
  • The Quick Reference cards are another useful tool once you get more familiar with Sage.

Our main focus in this tutorial, though, is help you can immediately access from within a worksheet, where you don't have to do any of those things.

Tab completion

The most useful help available in the notebook is "tab completion".   The idea is that even if you aren't one hundred percent sure of the name of a command, the first few letters should still be enough to help find it.  Here's an example.

  • Suppose you want to do a specific type of plot - maybe a slope field plot - but aren't quite sure what will do it.   
  • Still, it seems reasonable that the command might start with "pl".
  • Then one can type "pl" in an input cell, and then press the tab key to see all the commands that start with the letters "pl".

Try tabbing after the "pl" in the following cell to see all the commands that start with the letters "pl".     You should see that "plot_slope_field" is one of them.

{{{id=132| pl /// }}}

To pick one, just click on it; to stop viewing them, press the Escape/esc key.

You can also use this to see what you can do to an expression or mathematical object.

  • Assuming your expression has a name, type it;
  • Then type a period after it,
  • Then press tab.  

You will see a list pop up of all the things you can do to the expression.

To try this, evaluate the following cell, just to make sure $f$ is defined.

{{{id=135| f(x)=x^2 /// }}}

Now put your cursor after the period and press your tab key.  

{{{id=139| f. /// }}}

Again, Escape should remove the list.

One of the things in that list above was "integrate".  Let's try it.

{{{id=137| f.integrate(x) /// x |--> 1/3*x^3 }}}

Finding documentation (the question marks)

In the previous example, you might have wondered why I needed to put "f.integrate(x)" rather than just "f.integrate()", by analogy with "sqrt(2).n()".

To find out, there is another help tool one can use from right inside the notebook.  Almost all documentation in Sage has extensive examples that can illustrate how to use the function.

  • As with tab completion, type the expression, period, and the name of the function.
  • Then type a question mark.
  • Press tab or evaluate to see the documentation.

To see how this help works, move your cursor after the question mark below and press tab.

{{{id=151| f.integrate? /// }}}

The examples illustrate that the syntax requires "f.integrate(x)" and not just "f.integrate()".   (After all, the latter could be ambiguous if several variables had already been defined).

To stop viewing the documentation after pressing tab, you can press the Escape key, just like with the completion of options.

If you would like the documentation to be visible longer-term, you can evaluate a command with the question mark (like below) to access the documentation, rather than just tabbing.  Then it will stay there until you remove the input cell.

{{{id=14| binomial? ///

File: /usr/local/sage-prep/local/lib/python2.6/site-packages/sage/rings/arith.py

Type: <type ‘function’>

Definition: binomial(x, m)

Docstring:

Return the binomial coefficient

\binom{x}{m} = x (x-1) \cdots (x-m+1) / m!

which is defined for m \in \ZZ and any x. We extend this definition to include cases when x-m is an integer but m is not by

\binom{x}{m}= \binom{x}{x-m}

If m < 0, return 0.

INPUT:

  • x, m - numbers or symbolic expressions. Either m or x-m must be an integer.

OUTPUT: number or symbolic expression (if input is symbolic)

EXAMPLES:

sage: binomial(5,2)
10
sage: binomial(2,0)
1
sage: binomial(1/2, 0)
1
sage: binomial(3,-1)
0
sage: binomial(20,10)
184756
sage: binomial(-2, 5)
-6
sage: binomial(RealField()('2.5'), 2)
1.87500000000000
sage: n=var('n'); binomial(n,2)
1/2*(n - 1)*n
sage: n=var('n'); binomial(n,n)
1
sage: n=var('n'); binomial(n,n-1)
n
sage: binomial(2^100, 2^100)
1

sage: k, i = var('k,i')
sage: binomial(k,i)
binomial(k, i)

TESTS:

We test that certain binomials are very fast (this should be instant) – see trac 3309:

sage: a = binomial(RR(1140000.78), 42000000)

We test conversion of arguments to Integers – see trac 6870:

sage: binomial(1/2,1/1)
1/2
sage: binomial(10^20+1/1,10^20)
100000000000000000001
sage: binomial(SR(10**7),10**7)
1
sage: binomial(3/2,SR(1/1))
3/2

Some floating point cases – see trac 7562:

sage: binomial(1.,3)
0.000000000000000
sage: binomial(-2.,3)
-4.00000000000000
}}}

Try this with another function!

{{{id=173| /// }}}

 

Finding the source

There is one more source of help you may find useful in the long run, though perhaps not immediately.  

  • One can use two question marks after a function name to pull up the documentation and the source code for the function.  
  • Again, to see this help, you can either evaluate a cell like below, or just move your cursor after the question mark and press tab.

The ability to see the code (the underlying instructions to the computer) is one of Sage's great strengths.  You can see all the code to everything

This means:

  • You can see what Sage is doing.
  • Your curious students can see what is going on.
  • And if you find a better way to do something, then you can see how to change it!
{{{id=129| binomial?? ///

File: /usr/local/sage-prep/local/lib/python2.6/site-packages/sage/rings/arith.py

Source Code (starting at line 2784):

def binomial(x,m):
    r"""
    Return the binomial coefficient

    .. math::

                \binom{x}{m} = x (x-1) \cdots (x-m+1) / m!


    which is defined for `m \in \ZZ` and any
    `x`. We extend this definition to include cases when
    `x-m` is an integer but `m` is not by

    .. math::

        \binom{x}{m}= \binom{x}{x-m}

    If `m < 0`, return `0`.

    INPUT:

    -  ``x``, ``m`` - numbers or symbolic expressions. Either ``m``
       or ``x-m`` must be an integer.

    OUTPUT: number or symbolic expression (if input is symbolic)

    EXAMPLES::

        sage: binomial(5,2)
        10
        sage: binomial(2,0)
        1
        sage: binomial(1/2, 0)
        1
        sage: binomial(3,-1)
        0
        sage: binomial(20,10)
        184756
        sage: binomial(-2, 5)
        -6
        sage: binomial(RealField()('2.5'), 2)
        1.87500000000000
        sage: n=var('n'); binomial(n,2)
        1/2*(n - 1)*n
        sage: n=var('n'); binomial(n,n)
        1
        sage: n=var('n'); binomial(n,n-1)
        n
        sage: binomial(2^100, 2^100)
        1

        sage: k, i = var('k,i')
        sage: binomial(k,i)
        binomial(k, i)

    TESTS:

    We test that certain binomials are very fast (this should be
    instant) -- see trac 3309::

        sage: a = binomial(RR(1140000.78), 42000000)

    We test conversion of arguments to Integers -- see trac 6870::

        sage: binomial(1/2,1/1)
        1/2
        sage: binomial(10^20+1/1,10^20)
        100000000000000000001
        sage: binomial(SR(10**7),10**7)
        1
        sage: binomial(3/2,SR(1/1))
        3/2

    Some floating point cases -- see trac 7562::

        sage: binomial(1.,3)
        0.000000000000000
        sage: binomial(-2.,3)
        -4.00000000000000
    """
    if isinstance(m,sage.symbolic.expression.Expression):
        try:
            # For performance reasons, we avoid to try to coerce
            # to Integer in the symbolic case (see #6870)
            m=m.pyobject()
            m=ZZ(m)
        except TypeError:
            pass
    else:
        try:
            m=ZZ(m)
        except TypeError:
            pass
    if not isinstance(m,integer.Integer):
        try:
            m = ZZ(x-m)
        except TypeError:
            try:
                return x.binomial(m)
            except AttributeError:
                pass
            raise TypeError, 'Either m or x-m must be an integer'
    # a (hopefully) temporary fix for #3309; eventually Pari should do
    # this for us.
    if isinstance(x, (float, sage.rings.real_mpfr.RealNumber,
                      sage.rings.real_mpfr.RealLiteral)):
        P = x.parent()
        if m < 0:
            return P(0)
        from sage.functions.all import gamma
        if x > -1/2:
            a = gamma(x-m+1)
            if a:
                return gamma(x+1)/gamma(P(m+1))/a
            else:
                return P(0)
        else:
            return (-1)**m*gamma(m-x)/gamma(P(m+1))/gamma(-x)
    if isinstance(x,sage.symbolic.expression.Expression):
        try:
            x=x.pyobject()
            x=ZZ(x)
        except TypeError:
            pass
    else:
        try:
            x=ZZ(x)
        except TypeError:
            pass
    if isinstance(x,integer.Integer):
        if x >= 0 and (m < 0 or m > x):
            return ZZ(0)

        if m > sys.maxint:
            m = x - m
            if m > sys.maxint:
                raise ValueError, "binomial not implemented for m >= 2^32.\nThis is probably OK, since the answer would have billions of digits."

        return ZZ(pari(x).binomial(m))
    try:
        P = x.parent()
    except AttributeError:
        P = type(x)
    if m < 0:
        return P(0)
    return misc.prod([x-i for i in xrange(m)]) / P(factorial(m))
}}}

Annotating with Sage

Whether one uses Sage in the classroom or in research, it is usually helpful to describe to the reader what is being done, such as in the description you are now reading.   

Thanks to the mini-word processor TinyMCE and a TeX rendering engine called jsmath, you can type much more in Sage than just Sage commands.  This math-aware setup makes Sage perfect for annotating computations. 

To use the word processor, we create a text cell (as opposed to a input cell that contains Sage commands that Sage evaluates). 

To create a text cell, do the following.

  • First, move the cursor between two input cells, until the thin blue line appears.
  • Then hold the Shift key and click on the thin blue line. 
  • (So to create an input cell, one merely clicks, but one "Shift-Click"s to create a text cell.)

Try inserting a text cell between the input cells below.

{{{id=147| /// }}} {{{id=146| /// }}}

TinyMCE makes it easy for format text in many ways.  Try experimenting with the usual bold button, underline button, different text fonts and colors, ordered and unordered lists, centering, and so on.  Some of the shortcut keys you are familiar with from other word processors may also work, depending on your system.

There are two other things you can do which take advantage of the worksheet being on the web.  

  • It is easy to link to other helpful websites for additional information.  
    • While in the editor, highlight a word or two, and then click on the little chain link toward the bottom right of the buttons.  
    • You can now type in a web address to link to.  
    • Be sure to prepend http:// to the address.  Normally, one should also select it to appear in a new window (so the Sage session isn't interrupted).
  • You may have already noticed that some of the descriptions above had typeset mathematics in them. In fact we can add nearly arbitrary LaTeX to our text cells!  
    • For instance, it isn't too hard to add things like $$\zeta(s)=\sum_{n=1}^{\infty}\frac{1}{n^s}=\prod_p \left(\frac{1}{1-p^{-s}}\right)\; .$$ 
    • One just types things like "\$\$\zeta(s)=\sum_{n=1}^{\infty}\frac{1}{n^s}=\prod_p \left(\frac{1}{1-p^{-s}}\right)\$\$" in the word processor.  
    • Whether this shows up as nicely as possible depends on what fonts you have in your browser, but it should be legible.  
    • More realistically, we might type "\$f(x)=x^2\$" so that we remember that $f(x)=x^2$ in this worksheet.

Here is a simpler example.

{{{id=154| f(x)=x^2 f(9) /// 81 }}}

If $f(x)=x^2$, then $f(9)=81$.

It is simple to edit a text cell; simply double-click on the text. 

Try double-clicking on this text to edit this text cell (or any text cell) to see how we typed the mathematics!

{{{id=157| /// }}}

Of course, one can do much more, since Sage can execute arbitrary commands in the Python programming language, as well as output nicely formatted HTML, and so on.  If you have enough programming experience to do things like this, go for it!

{{{id=165| html("Sage is somewhat really cool!

(It even does HTML.)

") /// Sage is somewhat really cool!

(It even does HTML.)

}}}

This concludes the introductory tutorial.  Our hope is that now you can try finding and using simple commands and functions in Sage.  Remember, help is as close as the notebook, or at the Sage website.

The next tutorial is for basic symbolics and plotting; or feel free to just start creating worksheets!

{{{id=156| /// }}}