Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
30 views

Getting Started With Sage

This worksheet is designed to help you get started using Sage, a free and open source tool for mathematical computations.

 

The first thing you need to do is get an account at cocalc.com.

I recommend you set up your account using your TCNJ username.

The rest of this worksheet is designed to teach you some basic Sage commands.

Note: This Sage worksheet is based on a tutorial developed for the MAA PREP Workshop "Sage: Using Open-Source Mathematics Software with Undergraduates" (funding provided by NSF DUE 0817071).

 

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.

  • First, click inside the cell so that the cell is active (i.e., has a pale blue background).  
  • Then, to evaluate the cell, press SHIFT and ENTER at the same time.  

Try evaluating the following cell.

2+22
24

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

 

Now try calculating 42 (123 + 456). Click on a grey line to get a new input cell. NOTE: You need to use * for multiplication.  

Try evaluating the next cell:
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, in the cell below, try factoring your phone number.  You can change a few digits if you're worried I might call you.

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

  • Move your cursor over one of the grey lines where you want to type your input.  
  • A blue horizontal line as wide as the browser should appear. 
  • Type your new input into the blue line.  

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.

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)=x2  .f(x)=x^2\; .

f(x)=x^2

Since all we wanted was to create the function f(x)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)f(x) is:

f(x)

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

f

We can evaluate ff at various values.

f(3)
f(3.1)

Create a cell below this text and evaluate g(x+2y)g(x + 2*y)  (you always need to use a * for multiplication).

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

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.

z^2

You can define multiple variables at a time. In the cell below, define variables aa and BB by typing var('a, B').

Then do aBa^B .

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.

var('z') 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 ee.

f(pi)
f(e^-1)

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

N(f(pi))

Find the numeric approximation of πe\pi^e and eπe^{\pi}.

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

f(pi).n()

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').

pi.n(digits=200)
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303820

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

log(3)

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

log(3)+log(3)
log(3).n()

(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.)

log(3.)
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.

show(sqrt(2))
sqrt(2).n()

Evaluate  f(a+B)f(a + B).

Use "show" to make f(a+B)f(a + B) look nice.

Do you remember what ff does?

f(sqrt(2))

In other tutorials, 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.

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.

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.

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 ff is defined.

f(x)=x^2

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

f.

Again, Escape should remove the list.

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

f.integrate(x)

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.

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.

binomial?

Try this with another function!

 

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!
gcd??

Hello world.

eπi=e^{\pi i} = what?

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 ζ(s)=n=11ns=p(11ps)  .\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)=x2f(x)=x^2 in this worksheet.

Here is a simpler example.

f(x)=x^2 f(9)

If f(x)=x2f(x)=x^2, then f(9)=81f(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!

Now evaluate the next cell.

html("Sage is <a style='text-decoration:line-through'>somewhat</a> <b>really</b> cool! <p style='color:red'>(It even does HTML.)</p>")
%html <p>This concludes the introductory tutorial. &nbsp;Our hope is that now you can try finding and using simple commands and functions in Sage. &nbsp;Remember, help is as close as your instructor, the notebook, or at <a href="http://www.sagemath.org" target="_blank">the Sage website</a>.</p> <p>&nbsp;</p> <p>&nbsp;</p> <p><u><strong>When you are done working with this or any worksheet, SAVE IT!!!!</strong></u> <p>&nbsp;</p>

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 your instructor, the notebook, or at the Sage website.

 

 

When you are done working with this or any worksheet, SAVE IT!!!!