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).  The first part of the tutorial was to load this worksheet, of course!

This tutorial has the following sections:

As the workshop progresses, more tutorials on topics such as calculus, advanced plotting, and specific mathematical topics will become available.

Evaluating Sage Commands

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

The little boxes below are called input cells or code cells. To evaluate the content of an input cell, first click inside the cell so that the cell is active (i.e., has a bright blue border).  Then, just below the cell on the left, an "evaluate" link appears; clicking this link evaluates the cell.  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 probably automatically made the next cell active after your evaluated your first cell.

You can also evaluate a cell using a keyboard shortcut.  If the following cell isn't active, click in it; then try holding down the Shift key while you press the Enter key.  (We call this "Shift-Enter".)

{{{id=4| factor(2010) /// 2 * 3 * 5 * 67 }}}

You can edit a cell and evaluate it again.  Try changing the number "2010" above to your favorite number and evaluate the cell to find its factorization.

To create a new input cell, move your cursor over the space above or below another cell.  A blue horizontal line as wide as the browser appears. Click on the line to insert a new cell.  To 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, and deleting one of the input cells.

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

Functions in Sage

To start out, let's explore how to define variables and functions.

In the next cell, we tell Sage that "x" is a variable and we define the function $f(x)=x^2$.

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

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 }}}

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(e^-1).n() /// 0.135335283236613 }}}

Sage also 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).n() /// 1.09861228866811 }}} {{{id=121| sqrt(2) /// sqrt(2) }}} {{{id=149| sqrt(2).n() /// 1.41421356237310 }}} {{{id=150| f(sqrt(2)) /// 2 }}}

Notice that if we want this to look nicer, we can use the "show" command.  We'll look more at this sort of thing below.

{{{id=142| show(sqrt(2)) ///
\newcommand{\Bold}[1]{\mathbf{#1}}\sqrt{2}
}}}

We can also plot the function easily.  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.

{{{id=122| plot(f, (x,-3,3)) /// }}} {{{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.  To access these, just click the "Help" link at the top right of any worksheet.  Also, the Quick Reference cards are useful.

Tab completion

To see what you can do to an expression, usually you can just give the expression a name, type a period after it, and then press tab.  You will see a list pop up of all the things you can do to the expression.

Just in case you didn't do it before, evaluate this cell to (re-)define $f(x)$.

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

After evaluating the above cell, put your cursor after the period and press your tab key.  (To stop viewing the list, pressing the Escape/esc key should do the trick.)

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

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

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

This works with completing commands as well. Try tabbing after this to see all the commands that start with the letters "plot". Clicking on one of the options will use it for this cell.

{{{id=132| plot /// }}}

Remember, if you decide not to use any of the options, pressing Escape should make the list disappear.

Finding documentation (the question marks)

Use a question mark after a function name to pull up the documentation for the function.  Almost all documentation in Sage has extensive examples that can illustrate how to use the function.  To see this help, you can move your cursor after the question mark and press tab.  

For instance, do this for the integration example above to see examples illustrating that the syntax requires "f.integrate(x)" and not just "f.integrate()" (which could be ambiguous if several variables had already been defined).

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

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

Instead of using tab, you can evaluate a cell (like below) to access the documentation.

{{{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:

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=133| /// }}}

 

 

Finding the source

Finally, 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 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 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 word processor makes Sage perfect 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, first move the cursor between two input cells.  Then hold the Shift key and then click on the thin blue line that appears. (Notice that to create an input cell, one merely clicks, but one "Shift-Click"s to create a text cell.)

Now 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.  

To edit a text cell, simply double-click on the text.  Try double-clicking on this text to edit this text cell (and you can see how we typed the mathematics above!).

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

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

{{{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=155| print "Sage is somewhat really cool!

(It even does HTML.)

" /// Sage is somewhat really cool!

(It even does HTML.)

}}}

That's the end of the introductory tutorial.  Feel free to create more of your own worksheets, or watch for additional tutorials coming soon!

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