# Math Forum - Sage Intro 2013

## Math Forum

### February 21, 2013

Welcome to Math Forum!

So what is Sage?  Sage is comprehensive mathematics software that you can use from your computer, or even certain mobile devices.

The first thing we'll want to do is get people started up on Sage.   Nowadays, nothing could be easier.

See this screenshot.

If you ever have trouble during the talk, you can always go and type commands here to your heart's content!

However, this can only handle one-off computations.  So let's get you set up on the local Gordon server if you don't already have an account.  You may want to double up with a partner to talk through it.  See http://sagemath.org/doc/prep/Logging-On.html for some nice screenshots.

• open a worksheet (New Worksheet in the upper left), and
• evaluate $2+2$.

This last thing is done by clicking in the 'cell' like the one below, typing 2+2, and then either clicking "Evaluate" or pressing Shift and Enter simultaneously (Shift-Enter).

2+2
 4 4

Once you've done this, the main goal for today is to give you an introduction to how to use Sage, whether or not you are required to use it in a class.

Sage can function as:

• a calculator
• a high-end scientific computation program
• an exploratory vehicle for mathematics research
• a homework aid

Of course, there are many programs which can do that!  There are some advantages to Sage, of course:

• Free
• Open Source (not the same as free)
• Mathematically Comprehensive

But those alone would not make it something I would necessarily ask students to use on a regular basis.  Here is why I use Sage, and why I often ask my classes to do so:

• Sage is the ONLY comprehensive program, free or not, which is freely available from any internet-accessible computer with a reasonably modern web browser.  There is nothing to download, no Java applet which needs to load, nothing like that.   It's all modern Web 2.0 technology like Google Docs/Drive.

Now let's get cracking!  First, let's recall the three examples on the advertising flyer for the Math Forum.  They were from:

• Calculus
• Linear Algebra
• Differential Equations
f(x)=x^2+5*x+1

As you can see, when you click on a "cell", there is a little 'evaluate' link right below it on the left.  You may click on this to ask Sage to do something, or you can press Shift and Enter at the same time.  In the case above, I have asked it to define a function of a variable $x$.  Notice that exponentiation is denoted with the carat (Shift-6) and multiplication with the asterisk (Shift-8).  Other than this, Sage 'knows' about most math expressions via something called a preparser, but you must do these correctly (especially multiplication!).

You should also notice that nothing appeared to happen when I clicked 'evaluate'.  That is because I did not ask Sage to show any output.  The last thing I type is the thing that gets displayed, if it is an actual calculation.  Here, I just defined something, but didn't calculate it.  On the other hand:

 $\newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ x^{2} + 5 \, x + 1$

Notice that if I check the "Typeset" button at the top, it is nicely typeset, using MathJax, a new standard for web mathematics.  Surrounding something with "show()" also will do this.

Now, if I wanted to do everything above all at once, I could have typed the following:

f(x)=x^2+5*x+1 f
 x \ {\mapsto}\ {x}^{2} + {5 x} + 1 x \ {\mapsto}\ {x}^{2} + {5 x} + 1

If I want more than one thing to show up at the same time, I put it all on the last line and separate by semicolons, like so:

f;f(2);sqrt(f)

And now it is a simple matter to do some calculus homework checking.  What was the integral of the square root of $x^2+5x+1$ again?

integrate(sqrt(f),x)
 $\newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ \frac{1}{2} \, \sqrt{x^{2} + 5 \, x + 1} x + \frac{5}{4} \, \sqrt{x^{2} + 5 \, x + 1} - \frac{21}{8} \, \log\left(2 \, x + 2 \, \sqrt{x^{2} + 5 \, x + 1} + 5\right)$

Notice I included the variable; otherwise, how does Sage know I didn't mean an integral with respect to some other variable?

If I want the definite integral, the syntax is similar, and intuitive:

integrate(sqrt(f),x,0,5)
 $\newcommand{\Bold}[1]{\mathbf{#1}}\frac{15}{4} \, \sqrt{51} - \frac{21}{8} \, \log\left(2 \, \sqrt{51} + 15\right) + \frac{21}{8} \, \log\left(7\right) - \frac{5}{4}$

Here is what happens if you try to use any variable or constant other than $x$, $e$, or $pi$ without "declaring" it first:

integrate(sqrt(f),y)
 Traceback (click to the left of this block for traceback) ... NameError: name 'y' is not defined Traceback (most recent call last): File "", line 1, in File "_sage_input_11.py", line 10, in exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("aW50ZWdyYXRlKHNxcnQoZikseSk="),globals())+"\\n"); execfile(os.path.abspath("___code___.py")) File "", line 1, in File "/tmp/tmpyuKtiX/___code___.py", line 2, in exec compile(u'integrate(sqrt(f),y) File "", line 1, in NameError: name 'y' is not defined

But if you do declare it (the syntax is always the same), neat things can happen!

var('y') integrate(sqrt(f),y)
 $\newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ \sqrt{x^{2} + 5 \, x + 1} y$

And of course other calculus stuff works, too.

diff(sqrt(f),x)
 $\newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ \frac{2 \, x + 5}{2 \, \sqrt{x^{2} + 5 \, x + 1}}$

Before we see what else Sage can do, I should point out that you should feel free to just type whatever you can and see what works.

You should especially try to make mistakes and find new commands.  How might one do that?  There are a few ways to do it:

• If you don't remember a name of a command, but suspect it starts with a certain letter or combination of letters, you can type them and then [tab].  This tab-completion is very handy.
• If you find the name but don't remember the syntax or what it does, you can type the command and ?, then evaluate or tab and it will give you that information.
• If you already have an object defined (like the function $f$ above), you can type a period/dot after its name, and then [tab].  This will give you everything you can do to this object.
I'll demonstrate these below.

deriv
derivative?
f.

Before we move on to linear algebra, I wanted to show you some eye candy.  Just in case you thought Sage wasn't up to applications.

import pylab A=pylab.imread(DATA + 'gordon_college_medium.png') graphics_array([matrix_plot(A^(-1)),matrix_plot(1-A[0:,0:,2])]).show(figsize=[8,3])
 Warning: divide by zero encountered in reciprocal Warning: divide by zero encountered in reciprocal
import pylab A_image = pylab.mean(pylab.imread(DATA + 'gordon_college_medium.png'), 2) @interact def svd_image(i=(20,(1..100)),display_axes=True): u,s,v = pylab.linalg.svd(A_image) A = sum(s[j]*pylab.outer(u[0:,j],v[j,0:]) for j in range(i)) g = graphics_array([matrix_plot(A),matrix_plot(A_image)]) show(g,axes=display_axes, figsize=[8,3]) html('<h2>Compressed using %s eigenvalues</h2>'%i)

## Click to the left again to hide and once more to show the dynamic interactive window

Now, those of you in the know noticed that the specific commands I used seem to indicate doing things like matrix inversion and other matrix operations - that is to say, it involves linear algebra!  So let's see what Sage can do with linear algebra.

A = Matrix([[1,2,3],[3,2,1],[1,1,1]]) A
 $\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rrr} 1 & 2 & 3 \\ 3 & 2 & 1 \\ 1 & 1 & 1 \end{array}\right)$
w = vector([1,1,-4]) w
 $\newcommand{\Bold}[1]{\mathbf{#1}}\left(1,\,1,\,-4\right)$
w*A; A*w

So Sage can pretty easily create matrices and vectors and do things with them.  One interesting point here is that vectors are not regarded as $1\times n$ or $n\times 1$ matrices, but as their own entities.  Even w*w makes sense, and gives the dot product (the only reasonable interpretation of the product of two vectors).

We can also use it to solve systems of linear equations in this context, for instance

• $x+2y+3z=0$
• $3x+2y+z=-4$
• $x+y+z=-1$
Y = vector([0,-4,-1]) X = A.solve_right(Y) A \ Y; X; A*X

It also tells me if there is not a solution, which certainly can happen!

A.solve_right(w)
 Traceback (click to the left of this block for traceback) ... ValueError: matrix equation has no solutions Traceback (most recent call last): File "", line 1, in File "_sage_input_30.py", line 10, in exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("QS5zb2x2ZV9yaWdodCh3KQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py")) File "", line 1, in File "/tmp/tmprYYtCb/___code___.py", line 2, in exec compile(u'A.solve_right(w) File "", line 1, in File "matrix2.pyx", line 322, in sage.matrix.matrix2.Matrix.solve_right (sage/matrix/matrix2.c:4641) File "matrix2.pyx", line 440, in sage.matrix.matrix2.Matrix._solve_right_general (sage/matrix/matrix2.c:5454) ValueError: matrix equation has no solutions

I can also get other things I might want.  Remember, type the dot/period and then [tab] to see what options I have:

A.
 Syntax Error: A. Syntax Error: A.
A.echelon_form();A.determinant();A.rank()
 \left(\begin{array}{rrr} 1 & 0 & -1 \\ 0 & 1 & 2 \\ 0 & 0 & 0 \end{array}\right) 0 2 \left(\begin{array}{rrr} 1 & 0 & -1 \\ 0 & 1 & 2 \\ 0 & 0 & 0 \end{array}\right) 0 2

Notice that most commands are accessed by dot/period and function_name().  This allows Sage to only try to do math on things that deserve it; for instance, you don't want the determinant of a polynomial to be possible!  What would that even mean?

We can do more complicated things if we tell Sage that we are allowing non-integer values:

B = Matrix(RDF,[[1,2,3],[3,2,1],[1,1,1]]) B;B.LU()
 \left(\begin{array}{rrr} 1.0 & 2.0 & 3.0 \\ 3.0 & 2.0 & 1.0 \\ 1.0 & 1.0 & 1.0 \end{array}\right) \left(\left(\begin{array}{rrr} 0.0 & 1.0 & 0.0 \\ 1.0 & 0.0 & 0.0 \\ 0.0 & 0.0 & 1.0 \end{array}\right), \left(\begin{array}{rrr} 1.0 & 0.0 & 0.0 \\ 0.333333333333 & 1.0 & 0.0 \\ 0.333333333333 & 0.25 & 1.0 \end{array}\right), \left(\begin{array}{rrr} 3.0 & 2.0 & 1.0 \\ 0.0 & 1.33333333333 & 2.66666666667 \\ 0.0 & 0.0 & 1.11022302463 \times 10^{-16} \end{array}\right)\right) \left(\begin{array}{rrr} 1.0 & 2.0 & 3.0 \\ 3.0 & 2.0 & 1.0 \\ 1.0 & 1.0 & 1.0 \end{array}\right) \left(\left(\begin{array}{rrr} 0.0 & 1.0 & 0.0 \\ 1.0 & 0.0 & 0.0 \\ 0.0 & 0.0 & 1.0 \end{array}\right), \left(\begin{array}{rrr} 1.0 & 0.0 & 0.0 \\ 0.333333333333 & 1.0 & 0.0 \\ 0.333333333333 & 0.25 & 1.0 \end{array}\right), \left(\begin{array}{rrr} 3.0 & 2.0 & 1.0 \\ 0.0 & 1.33333333333 & 2.66666666667 \\ 0.0 & 0.0 & 1.11022302463 \times 10^{-16} \end{array}\right)\right)

A.eigenvalues()
 \left[5, 0, -1\right] \left[5, 0, -1\right]
A.eigenvectors_left()
 \begin{array}{l}[\left(5, \left[\left(1,1,1\right)\right], 1\right),\\ \left(0, \left[\left(1,1,-4\right)\right], 1\right),\\ \left(-1, \left[\left(1,-\frac{1}{5},-\frac{7}{5}\right)\right], 1\right)]\end{array} \begin{array}{l}[\left(5, \left[\left(1,1,1\right)\right], 1\right),\\ \left(0, \left[\left(1,1,-4\right)\right], 1\right),\\ \left(-1, \left[\left(1,-\frac{1}{5},-\frac{7}{5}\right)\right], 1\right)]\end{array}

Differential equations can be nicely modeled too.  Here is a slope field, just for you!

var('x,y') plot_slope_field(sin(x+y)+cos(x+y), (x,-3,3), (y,-3,3)).show()

It is possible to even plot solutions, solve numerically, get exact answer, etc., depending on how hard they are:

y = var('y') P=plot_slope_field(1-y,(x,0,3),(y,0,20)) x = var('x') y = function('y',x) f = desolve(diff(y,x) + y - 1, y, ics=[2,2]) Q=plot(f,0,3) show(P+Q)
 $\newcommand{\Bold}[1]{\mathbf{#1}}{\left(e^{2} + e^{x}\right)} e^{\left(-x\right)}$

If you know how to ask a little more of Sage, you can define your own interactive demos.  This is not too hard, but does require you to be able to follow the examples given in interact? fairly closely.

@interact def _(initial_y=([2..5]),initial_x=([2..5])): x,y = var('x,y') P=plot_slope_field(1-y,(x,0,initial_x),(y,0,(initial_y-1)*e^initial_x)) x = var('x') y = function('y',x) f = desolve(diff(y,x) + y - 1, y, ics=[initial_x,initial_y]) Q=plot(f,0,initial_x) show(f.expand()) show(P+Q)

## Click to the left again to hide and once more to show the dynamic interactive window

Of course there is a lot more to math than just this!  In fact, Sage's greatest strong suit is in things like high-precision numerical computing, number theory and abstract algebra, because that is the roots of its founders.  But the examples I've shown you are all the basic ones in freshman and sophomore courses.

Interlude: What kind of program is Sage?  What language does it use?

• It is based on the Python language we use for our intro course at Gordon.
• So all the same stuff that works there, works here!
[i^2 if i%4 == 2 else 'hi' for i in range(20) ]
 $\newcommand{\Bold}[1]{\mathbf{#1}}\left[\verb|hi|, \verb|hi|, 4, \verb|hi|, \verb|hi|, \verb|hi|, 36, \verb|hi|, \verb|hi|, \verb|hi|, 100, \verb|hi|, \verb|hi|, \verb|hi|, 196, \verb|hi|, \verb|hi|, \verb|hi|, 324, \verb|hi|\right]$

There is one last thing I haven't shown too much of, namely plotting.  But we should certainly return to that as our final set of examples before I set us all loose.

plot(x^2,0,1)
P=Graphics() for i in [1..10]: P += plot(x^i,0,1,hue=i*0.1) show(P)
plot([x^i for i in [1..10]],(x,0,1),fill = dict((i,[i+1]) for i in [0..9]))
x, y = var('x,y') #plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1),viewer='canvas3d') #plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1),viewer='tachyon') plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1))

There are MANY MANY resources for Sage online.  A few:

Remember, for once-off computations you have some nice options with the Sage cell servers; for more in-depth ones, use these notebook servers.