MAT 223 - Intro to Sage

743 days ago by kcrisman

A Beginning of Sage

Parts based on a worksheet by Mike May, S.J., 2010, licensed CC BY-NC-SA 3.0

The purpose of this worksheet is to learn just enough of Sage to be able to start using it in the course.  Maybe soon you'll start making your own worksheets!

The first detail is to get an account.  Look at the upper left corner of your browser window, where the red box is in this picture.

If you've already logged in, you'll see this.  If you do not see the option to "Edit a copy", but instead to "Log in to edit a copy", you are not yet logged in, so select "Log in to edit a copy".  

You should see a screen similar to this.

Then click on "Sign up for a new Sage Notebook account", and follow the instructions to do this.  

Finally, log in with that account, and return to this page in your browser.  People often skip this step and wonder why they can't try it out!

You should now see the option in the picture to "Edit a copy".

Select the "Edit" option; you will now have your own version of this worksheet you can use.

 

The rest of this worksheet introduces you to basic Sage stuff, at least somewhat systematically.  If you are only interested in using commands from class, you can go straight to another published worksheet (see the link at the top) and click "Edit a copy" for those.  In that case, good luck!  

 

Otherwise, continue reading.

 
       

Doing Math in Sage

Basics

We now walk through how to actually do some mathematics!

The easiest operation is evaluating a cell that someone has already prepared for you.  Notice the two math cells pictured below, which also appear beneath the text region.

The same cells are below.

2*3+5 
       
11
11
2^117 
       
166153499473114484112975882535043072
166153499473114484112975882535043072

When your cursor is in the math region, it becomes active.  As the picture shows, an evaluate link appears, and the cell has a bluish border.  You can evaluate the region by clicking the evaluate link. 

When you do either, the cursor evaluates the contents of the cell, prints out the last result, and moves the cursor to the next math cell.  Try this.

 

(If you get bored with clicking the "evaluate" link, you can also click inside the cell, and then press 'Shift' and 'Enter' at the same time to evaluate the cell.  We call this "Shift-Enter".)

 

 

As you can see, we can use Sage to do easy calculations, or longer computations we would not want to do by hand.  To see the output, always highlight the cell (with up/down arrows or by clicking) and then evaluate it. 

Try evaluating the ones above, or be brave and try something new in the cell below!

 
       

Plots

One main thing you might want to do is to plot functions (for instance, if you didn't have a graphing calculator, or if you realized that they are very wimpy).  The syntax is pretty simple, and you can reuse the same cell as often as you like.

plot(5*x^2, (x,-1,3)) 
       

There's a few things to note about this syntax.

  • First type in "plot".  Well, duh.
  • Then comes a parenthesis, and the function.
    • We use $x$ as the variable, though later we can use others.
    • Exponents are '^', and multiplication must be '*'.  (There are good reasons for this.)
  • After a comma, you put the variable and the part of the domain you'd like to examine in parentheses, separated by commas, and finally end with another parenthesis.  

You can think of it the whole syntax like a big function.  

  • The input is a pair - the function and the triple of variable and endpoints.
  • The output isn't a number, but a plot.

Try plotting $x^3+\frac{1}{x}$ between $x=1$ and $x=2$ in the next cell, which is currently empty.

 
       

You'll notice that Sage doesn't try to tell you how far you want to zoom, and (appropriately) shows the very high asymptotes.  You can use some so-called "keywords" to try to see this closer-up.  Try typing in "plot(x^3+1/x,(x,-1,2),ymin=-10,ymax=10)" instead, to keep the vertical frame from $-10$ to $10$.

 

Naturally, you won't always have nice spots to do things.  You might want to put math in between other math, for instance.

As you can see in the picture, when you have the cursor just above a math cell, a thin blue line appears.  Clicking while your cursor in in the blue line will cause another math cell to appear above the current cell.

Try this anywhere you want to on the worksheet, and calculate $2+4$ (or something more interesting, if you want).

 

Incidentally, if you want to put text in the page, look for the same blue line, but hold down "Shift" while you click (we call this "Shift-Click").  A nice fully featured editor will pop up.  Or, take some existing text and double-click on it!

 

Using functions

One of the most important things we can do in math is create new functions.  

In the following cell, I've typed $f(x)=\sin(x^3)$, which assigns the name $f$ to that function.  Then I plotted $f$ between $-2$ and $5$.  

f(x) = sin(x^3) plot(f, (x,-2,5)) 
       

Notice that I can just type $f$ in the plot command to do this.

 

There are lots of things I can do with this.  One thing we often do in calculus, for instance, is to compare two related functions.  If I wanted to compare this with $f(x-2)$, I would just plot this, like below.  

plot(f(x-2), (x,-2,5)) 
       

Or I might want to use different endpoints - it's up to you.

There are two interesting ways to compare the two plots.  I can put both functions together, inside of square brackets $[f(x-2),f]$:

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

Or I can add the plots themselves with the $+$ symbol.   First, I'll assign them both to variables - to names in the computer program.  In the second plot, I've added some cool options, so that they look different.

P = plot(f, (x,-2,5)) Q = plot(f(x-2), (x,-2,5), color='red', linestyle = '--') 
       

Now, to show them both, I just add them.

P+Q 
       

Finding out more

Well, there is lots more math to do.  All we've really seen are how to plot basic functions and do some arithmetic and function evaluation.  The rest of this worksheet is intended to help you find out more; it assumes that the rest of the worksheet is done in a classroom environment.

Now, there are lots of great references on the web.

But I want you to be able to help yourselves, right here, right now.  So here is how it works.

  • You want to do something in Sage.
    • Let's say it's integration.
  • You try your best at guessing a name for this.
    • Say, "integrate".
  • Then you type the first few letters of this in, and press "tab".
int 
       
    • What do you know - a bunch of options show up!  And one of them is "integrate" - convenient.
  • Next, you try the command out.  
integrate(sin(x^3)) 
       
/usr/local/sage/local/lib/python2.6/site-packages/sage/misc/functional.p\
y:718: DeprecationWarning: Variable of integration should be specified
explicitly.
  return x.integral(*args, **kwds)
-1/12*((-I*sqrt(3) + 1)*gamma(1/3, -I*x^3) + (I*sqrt(3) + 1)*gamma(1/3,
I*x^3))*x/(x^3)^(1/3)
/usr/local/sage/local/lib/python2.6/site-packages/sage/misc/functional.py:718: DeprecationWarning: Variable of integration should be specified explicitly.
  return x.integral(*args, **kwds)
-1/12*((-I*sqrt(3) + 1)*gamma(1/3, -I*x^3) + (I*sqrt(3) + 1)*gamma(1/3, I*x^3))*x/(x^3)^(1/3)
    • Hmm, that looks confusing.  What is that weird warning?  
  • So next, because you don't want to use results that trigger warnings, you want to find out what the right thing to do is.
    • So you type the command with a question mark to find help.
integrate? 
       

File: /usr/local/sage/local/lib/python2.6/site-packages/sage/misc/functional.py

Type: <type ‘function’>

Definition: integrate(x, *args, **kwds)

Docstring:

Returns an indefinite or definite integral of an object x.

First call x.integrate() and if that fails make an object and integrate it using Maxima, maple, etc, as specified by algorithm.

For symbolic expression calls sage.calculus.calculus.integral - see this function for available options.

EXAMPLES:

sage: f = cyclotomic_polynomial(10)
sage: integral(f)
1/5*x^5 - 1/4*x^4 + 1/3*x^3 - 1/2*x^2 + x
sage: integral(sin(x),x)
-cos(x)
sage: y = var('y')
sage: integral(sin(x),y)
y*sin(x)
sage: integral(sin(x), x, 0, pi/2)
1
sage: sin(x).integral(x, 0,pi/2)
1
sage: integral(exp(-x), (x, 1, oo))
e^(-1)

Numerical approximation:

sage: h = integral(tan(x)/x, (x, 1, pi/3)); h
integrate(tan(x)/x, x, 1, 1/3*pi)
sage: h.n()
0.07571599101...

Specific algorithm can be used for integration:

sage: integral(sin(x)^2, x, algorithm='maxima')
1/2*x - 1/4*sin(2*x)
sage: integral(sin(x)^2, x, algorithm='sympy')
-1/2*sin(x)*cos(x) + 1/2*x

File: /usr/local/sage/local/lib/python2.6/site-packages/sage/misc/functional.py

Type: <type ‘function’>

Definition: integrate(x, *args, **kwds)

Docstring:

Returns an indefinite or definite integral of an object x.

First call x.integrate() and if that fails make an object and integrate it using Maxima, maple, etc, as specified by algorithm.

For symbolic expression calls sage.calculus.calculus.integral - see this function for available options.

EXAMPLES:

sage: f = cyclotomic_polynomial(10)
sage: integral(f)
1/5*x^5 - 1/4*x^4 + 1/3*x^3 - 1/2*x^2 + x
sage: integral(sin(x),x)
-cos(x)
sage: y = var('y')
sage: integral(sin(x),y)
y*sin(x)
sage: integral(sin(x), x, 0, pi/2)
1
sage: sin(x).integral(x, 0,pi/2)
1
sage: integral(exp(-x), (x, 1, oo))
e^(-1)

Numerical approximation:

sage: h = integral(tan(x)/x, (x, 1, pi/3)); h
integrate(tan(x)/x, x, 1, 1/3*pi)
sage: h.n()
0.07571599101...

Specific algorithm can be used for integration:

sage: integral(sin(x)^2, x, algorithm='maxima')
1/2*x - 1/4*sin(2*x)
sage: integral(sin(x)^2, x, algorithm='sympy')
-1/2*sin(x)*cos(x) + 1/2*x
  • And sure enough, every single example also has the variable of integration in it.  Well, that does make sense!
    • And you try it again.
integrate(sin(x^3),x) 
       
-1/12*((-I*sqrt(3) + 1)*gamma(1/3, -I*x^3) + (I*sqrt(3) + 1)*gamma(1/3,
I*x^3))*x/(x^3)^(1/3)
-1/12*((-I*sqrt(3) + 1)*gamma(1/3, -I*x^3) + (I*sqrt(3) + 1)*gamma(1/3, I*x^3))*x/(x^3)^(1/3)
plot(integrate(sin(x^3),x),(x,-2,5)) 
       
verbose 0 (4101: plot.py, generate_plot_points) WARNING: When plotting,
failed to evaluate function at 58 points.
verbose 0 (4101: plot.py, generate_plot_points) Last error message:
'unable to simplify to float approximation'
verbose 0 (4101: plot.py, generate_plot_points) WARNING: When plotting, failed to evaluate function at 58 points.
verbose 0 (4101: plot.py, generate_plot_points) Last error message: 'unable to simplify to float approximation'

By this point I hope you have realized that you are playing with fire!  

  • Why the errors?  
  • What is "sqrt"?  Squirrel...?  
  • What the heck is "gamma"?  
  • Yet... it's such a cool graph.  

The answers are out there!  In this case, it's our fault, though - we tried to integrate a function which does not have an integral in terms of elementary functions.  

And there's so much more...

Dot notation

A = integrate(sin(x^3),(x,0, pi^(1/3) )) 
       

Here, I assigned the value of a definite integral to $A$.   What is its value?

A.numerical_approx() 
       
0.493747393665062
0.493747393665062

What's this?  The syntax is really confusing.  But here's all I did:

  • I took $A$.
  • I placed a dot, indicating I want to find out something about $A$.
  • I decided I wanted a "numerical_approx" - a numerical approximation.
  • I used parentheses, to remind myself (and Sage) that this is just like doing a function.

And - here's the kicker - I can use the same tab and ? to find out information about these!

  • What's the name of the function?
A.num 
       
1/6*gamma(1/3) - 1/12*gamma(1/3, -I*pi) - 1/12*gamma(1/3, I*pi)
1/6*gamma(1/3) - 1/12*gamma(1/3, -I*pi) - 1/12*gamma(1/3, I*pi)
  • What's any information I need about it?
A.numerator? 
       

File: /usr/local/sage/devel/sage/sage/symbolic/expression.pyx

Type: <type ‘builtin_function_or_method’>

Definition: A.numerical_approx(prec=None, digits=None)

Docstring:

Return a numerical approximation this symbolic expression as either a real or complex number with at least the requested number of bits or digits of precision.

EXAMPLES:

sage: sin(x).subs(x=5).n()
-0.958924274663138
sage: sin(x).subs(x=5).n(100)
-0.95892427466313846889315440616
sage: sin(x).subs(x=5).n(digits=50)
-0.95892427466313846889315440615599397335246154396460
sage: zeta(x).subs(x=2).numerical_approx(digits=50)
1.6449340668482264364724151666460251892189499012068

sage: cos(3).numerical_approx(200)
-0.98999249660044545727157279473126130239367909661558832881409
sage: numerical_approx(cos(3),200)
-0.98999249660044545727157279473126130239367909661558832881409
sage: numerical_approx(cos(3), digits=10)
-0.9899924966
sage: (i + 1).numerical_approx(32)
1.00000000 + 1.00000000*I
sage: (pi + e + sqrt(2)).numerical_approx(100)
7.2740880444219335226246195788

TESTS:

We test the evaluation of different infinities available in Pynac:

sage: t = x - oo; t
-Infinity
sage: t.n()
-infinity
sage: t = x + oo; t
+Infinity
sage: t.n()
+infinity
sage: t = x - unsigned_infinity; t
Infinity
sage: t.n()
+infinity

Some expressions can’t be evaluated numerically:

sage: n(sin(x))
Traceback (click to the left of this block for traceback)
...
                                
                            

File: /usr/local/sage/devel/sage/sage/symbolic/expression.pyx

Type: <type ‘builtin_function_or_method’>

Definition: A.numerical_approx(prec=None, digits=None)

Docstring:

Return a numerical approximation this symbolic expression as either a real or complex number with at least the requested number of bits or digits of precision.

EXAMPLES:

sage: sin(x).subs(x=5).n()
-0.958924274663138
sage: sin(x).subs(x=5).n(100)
-0.95892427466313846889315440616
sage: sin(x).subs(x=5).n(digits=50)
-0.95892427466313846889315440615599397335246154396460
sage: zeta(x).subs(x=2).numerical_approx(digits=50)
1.6449340668482264364724151666460251892189499012068

sage: cos(3).numerical_approx(200)
-0.98999249660044545727157279473126130239367909661558832881409
sage: numerical_approx(cos(3),200)
-0.98999249660044545727157279473126130239367909661558832881409
sage: numerical_approx(cos(3), digits=10)
-0.9899924966
sage: (i + 1).numerical_approx(32)
1.00000000 + 1.00000000*I
sage: (pi + e + sqrt(2)).numerical_approx(100)
7.2740880444219335226246195788

TESTS:

We test the evaluation of different infinities available in Pynac:

sage: t = x - oo; t
-Infinity
sage: t.n()
-infinity
sage: t = x + oo; t
+Infinity
sage: t.n()
+infinity
sage: t = x - unsigned_infinity; t
Infinity
sage: t.n()
+infinity

Some expressions can’t be evaluated numerically:

sage: n(sin(x))
Traceback (most recent call last):
...
TypeError: cannot evaluate symbolic expression numerically
sage: a = var('a')
sage: (x^2 + 2*x + 2).subs(x=a).n()
Traceback (most recent call last):
...
TypeError: cannot evaluate symbolic expression numerically

Reading this tells me a way to get 50 digits of the area in the final plot here!

A.numerical_approx(digits=50) 
       
0.49374739366506238127138825017677521668593000673647
0.49374739366506238127138825017677521668593000673647
plot(sin(x^3),(x,0,pi^(1/3)), fill=True)