Tutorial: Using the Sage notebook, navigating the help system, first exercises -- Thematic Tutorials v4.7.rc0
system:sage


<div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index" accesskey="I">index</a></li>
  
    
      <a href="../index.html"><img src="_static/sagelogo.png" style="vertical-align: middle" title="Sage Logo"></a>
    
  
  
        <li><a href="index.html">Thematic Tutorials v4.7.rc0</a> &raquo;</li>
 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="tutorial-using-the-sage-notebook-navigating-the-help-system-first-exercises">
<span id="tutorial-notebook-and-help-long"></span><h1>Tutorial: Using the Sage notebook, navigating the help system, first exercises<a class="headerlink" href="#tutorial-using-the-sage-notebook-navigating-the-help-system-first-exercises" title="Permalink to this headline">¶</a></h1>
<p>This worksheet is based on William Stein&#8217;s <a class="reference external" href="http://modular.math.washington.edu/talks/20090701-sage_graphics_tutorial/JPL09___intro_to_sage.sws">JPL09__intro_to_sage.sws</a>
worksheet and the <a class="reference external" href="http://wiki.sagemath.org/days20.5">Sage days 20.5_demo</a>
worksheet and aims to be an interactive introduction to Sage through exercises. You will learn how to use the notebook and call the help.</p>
<div class="section" id="making-this-help-page-into-a-worksheet">
<h2>Making this help page into a worksheet<a class="headerlink" href="#making-this-help-page-into-a-worksheet" title="Permalink to this headline">¶</a></h2>
<p>Go into the <tt class="docutils literal"><span class="pre">File</span></tt> menu at the top left of this window and click on <tt class="docutils literal"><span class="pre">Copy</span>
<span class="pre">worksheet</span></tt>. Then, you can clear all output in the menu <tt class="docutils literal"><span class="pre">Action</span></tt> by clicking
on <tt class="docutils literal"><span class="pre">Delete</span> <span class="pre">All</span> <span class="pre">Output</span></tt>.</p>
<p>TODO: explain how to do it from static documentation with Sage &gt;= 4.7</p>
</div>
<div class="section" id="entering-editing-and-evaluating-input">
<h2>Entering, Editing and Evaluating Input<a class="headerlink" href="#entering-editing-and-evaluating-input" title="Permalink to this headline">¶</a></h2>
<p>To <em>evaluate code</em> in the Sage Notebook, type the code into an input cell and
press <tt class="docutils literal"><span class="pre">shift-enter</span></tt> or click the <tt class="docutils literal"><span class="pre">evaluate</span></tt> link. Try it now with a simple
expression (e.g.,  <img class="math" src="_images/math/862d4aa8a195ae71a271f6e061af41aa1d4e6e8b.png" alt="2 + 3">). The first time you evaluate a cell takes longer
than subsequent times since a new Sage process is started:</p>
<div class="highlight-python">

{{{id=0|
2 + 3
///
5
}}}

</div>
<div class="highlight-python">

{{{id=1|
# edit here
///
}}}

</div>
<div class="highlight-python">

{{{id=2|
# edit here
///
}}}

</div>
<p>Create <em>new input cells</em> by clicking blue line that appears between cells when
you move your mouse around. Try it now:</p>
<div class="highlight-python">

{{{id=3|
1 + 1
///
}}}

{{{id=4|
# edit here
///
}}}

</div>
<p>You can <em>go back</em> and edit any cell by clicking in it (or using the
keyboard to move up or down). Go back and change your 2+2 above to 3 +
3 and re-evaluate it.</p>
<p>You can also <em>edit this text</em> right here by double clicking on it,
which will bring up the TinyMCE Javascript text editor.  You can even
put embedded mathematics like this $sin(x) - y^3$ just like with
LaTeX.</p>
</div>
<div class="section" id="help-systems">
<h2>Help systems<a class="headerlink" href="#help-systems" title="Permalink to this headline">¶</a></h2>
<p>There are various ways of getting help in Sage.</p>
<ul class="simple">
<li>navigate through the documentation (there is a link <tt class="docutils literal"><span class="pre">Help</span></tt> at the top right
of the worksheet),</li>
<li><tt class="docutils literal"><span class="pre">tab</span></tt> completion,</li>
<li>contextual help.</li>
</ul>
<p>We detail in what follows the two last methods through examples.</p>
</div>
<div class="section" id="completion-and-contextual-documentation">
<h2>Completion and contextual documentation<a class="headerlink" href="#completion-and-contextual-documentation" title="Permalink to this headline">¶</a></h2>
<p>Start typing something and press the <tt class="docutils literal"><span class="pre">tab</span></tt> key. The interface tries to
complete it with a command name. If there is more than one completion, then they
are all presented to you. Remember that Sage is case sensitive, e.g. it
differentiates lower case from lower case. Hence the <tt class="docutils literal"><span class="pre">tab</span></tt> completion of
<tt class="docutils literal"><span class="pre">klein</span></tt> won&#8217;t show you the <tt class="docutils literal"><span class="pre">KleinFourGroup</span></tt> command that build the group
<img class="math" src="_images/math/f0cfdeec7259b0334fa74c8134048411e0219557.png" alt="\ZZ/2 \times \ZZ/2"> as a permutation group. Try it on the next cells</p>
<div class="highlight-python">

{{{id=5|
klein
///
}}}

{{{id=6|
Klein
///
}}}

</div>
<p>To see documentation and examples for a command, type a question mark <tt class="docutils literal"><span class="pre">?</span></tt> at
the end of the command name and press the <tt class="docutils literal"><span class="pre">tab</span></tt> key as</p>
<div class="highlight-python"><pre>sage: KleinFourGroup?&lt;tab&gt;</pre>
</div>
<div class="highlight-python">

{{{id=7|
# edit here
///
}}}

</div>
<p><em>Exercise A:</em> What is the largest prime factor of <img class="math" src="_images/math/cbc20e67dd1f52efa39d92ff7c96648e7fb6383e.png" alt="600851475143">?</p>
<div class="highlight-python"><pre>sage: factor?&lt;tab&gt;</pre>
</div>
<div class="highlight-python">

{{{id=8|
# edit here
///
}}}

</div>
<p>In the above exercise we do not store any mathematical data for later use.
This can be done in Sage with the <tt class="docutils literal"><span class="pre">=</span></tt> symbol as in:</p>
<div class="highlight-python">

{{{id=9|
a = 3
b = 2
print a+b
///
5
}}}

</div>
<p>This can be understood as Sage evaluating the expression to the right of the
<tt class="docutils literal"><span class="pre">=</span></tt> sign and creating the appropriate object, and then associating that
object with a label, given by the right hand side. Multiple assignments can be
done simultaneously:</p>
<div class="highlight-python">

{{{id=10|
a,b = 2,3
print a,b
///
2 3
}}}

</div>
<p>This allows us to swap variables directly:</p>
<div class="highlight-python">

{{{id=11|
a,b = 2,3
a,b = b,a
print a,b
///
3 2
}}}

</div>
<p>Note that when we use the word <em>variable</em> in the computer-science sense we
mean &#8220;a label associated to some data stored by Sage&#8221;.  Once an object is
created, some <em>methods</em> apply to it. This means <em>functions</em> but instead of
writing <strong>f(my_object)</strong> you write <strong>my_object.f()</strong>.:</p>
<div class="highlight-python">

{{{id=12|
p = 17
p.is_prime()
///
True
}}}

</div>
<p>To know all methods of an object you can still use tab-completion. Write the
name of the object followed by a dot and then press tab.:</p>
<div class="highlight-python"><pre>a.&lt;tab&gt;</pre>
</div>
<div class="highlight-python">

{{{id=13|
# edit here
///
}}}

{{{id=14|
# edit here
///
}}}

</div>
<p><em>Exercise B:</em> Create the <tt class="docutils literal"><span class="pre">Permutation</span></tt> 51324 and assign it to the variable <tt class="docutils literal"><span class="pre">p</span></tt>.</p>
<div class="highlight-python"><pre>sage: Permutation?&lt;tab&gt;</pre>
</div>
<div class="highlight-python">

{{{id=15|
# edit here
///
}}}

</div>
<p>What is the <tt class="docutils literal"><span class="pre">inverse</span></tt> of <tt class="docutils literal"><span class="pre">p</span></tt> ?</p>
<div class="highlight-python">

{{{id=16|
p.inv&lt;tab&gt;
///
}}}

</div>
<div class="highlight-python">

{{{id=17|
# edit here
///
}}}

</div>
<p>Does <tt class="docutils literal"><span class="pre">p</span></tt> have the <tt class="docutils literal"><span class="pre">pattern</span></tt> 123 ? What about 1234 ? And 312 ? (even if you don&#8217;t
know what a pattern is, you should be able to find a command that does this).</p>
<div class="highlight-python">

{{{id=18|
p.pat&lt;tab&gt;
///
}}}

</div>
<div class="highlight-python">

{{{id=19|
# edit here
///
}}}

</div>
</div>
<div class="section" id="some-linear-algebra">
<h2>Some linear algebra<a class="headerlink" href="#some-linear-algebra" title="Permalink to this headline">¶</a></h2>
<p><em>Exercise C:</em> Use the <tt class="docutils literal"><span class="pre">matrix</span></tt> command to create the following matrix.</p>
<div class="math">
<p><img src="_images/math/90cfddc5fb80e3bed47bd5f99909b1647fd9ad64.png" alt="M = \left(\begin{array}{rrrr}
10 & 4 & 1 & 1 \\
4 & 6 & 5 & 1 \\
1 & 5 & 6 & 4 \\
1 & 1 & 4 & 10
\end{array}\right)"></p>
</div><div class="highlight-python"><pre>sage: matrix?&lt;tab&gt;</pre>
</div>
<div class="highlight-python">

{{{id=20|
# edit here
///
}}}

</div>
<p>Then using methods of the matrix:</p>
<ol class="arabic simple">
<li>Find the determinant of the matrix.</li>
<li>Find the echelon form of the matrix.</li>
<li>Find the eigenvalues of the matrix.</li>
<li>Find the kernel of the matrix.</li>
<li>Find the LLL decomposition of the matrix.</li>
</ol>
<div class="highlight-python">

{{{id=21|
# edit here
///
}}}

{{{id=22|
# edit here
///
}}}

</div>
<p>Now you know how to access the different methods of matrices:</p>
<ol class="arabic simple" start="6">
<li>Create the vector <img class="math" src="_images/math/841671e81c38f08fbc6037af7043fa9015da6e8f.png" alt="v = (1,-1,-1,1)">.</li>
<li>Compute the products: <img class="math" src="_images/math/93348571dfccb297b8e357cd37b5665907738520.png" alt="M*v"> and <img class="math" src="_images/math/cdd3f8d9178ccd6d9c834754298a1acd0759b288.png" alt="v*M">.</li>
</ol>
<div class="highlight-python"><pre>sage: vector?&lt;tab&gt;</pre>
</div>
<div class="highlight-python">

{{{id=23|
# edit here
///
}}}

</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Vectors in Sage are row vectors. A method such as <tt class="docutils literal"><span class="pre">eigenspaces</span></tt> might not
return what you expect, so it is best to specify <tt class="docutils literal"><span class="pre">eigenspaces_left</span></tt> or
<tt class="docutils literal"><span class="pre">eigenspaces_right</span></tt> instead. Same thing for kernel (<tt class="docutils literal"><span class="pre">left_kernel</span></tt> or
<tt class="docutils literal"><span class="pre">right_kernel</span></tt>), and so on.</p>
</div>
</div>
<div class="section" id="some-plotting">
<h2>Some Plotting<a class="headerlink" href="#some-plotting" title="Permalink to this headline">¶</a></h2>
<p>The <tt class="docutils literal"><span class="pre">plot</span></tt> command allows you to draw plots of functions. Recall that you can
access the documentation by pressing the <tt class="docutils literal"><span class="pre">tab</span></tt> key after writing <tt class="docutils literal"><span class="pre">plot?</span></tt> in
a cell.:</p>
<div class="highlight-python"><pre>sage: plot?&lt;tab&gt;</pre>
</div>
<div class="highlight-python">

{{{id=24|
# edit here
///
}}}

</div>
<p>Here is a simple example:</p>
<div class="highlight-python">

{{{id=25|
var(&#39;x&#39;)   # make sure x is a symbolic variable
plot(sin(x^2), (x,0,10))
///
}}}

</div>
<p>Here is a more complicated plot. Try to change every single input to the plot
command in some way, evaluating to see what happens:</p>
<div class="highlight-python">

{{{id=26|
P = plot(sin(x^2), (x,-2,2), rgbcolor=(0.8,0,0.2), thickness=3, linestyle=&#39;--&#39;, fill=&#39;axis&#39;)
show(P, gridlines=True)
///
}}}

</div>
<p>Above we used the <tt class="docutils literal"><span class="pre">show</span></tt> command to show a plot after it was created. You can
also use <tt class="docutils literal"><span class="pre">P.show</span></tt> instead:</p>
<div class="highlight-python">

{{{id=27|
P.show(gridlines=True)
///
}}}

</div>
<p>Try putting the cursor right after <tt class="docutils literal"><span class="pre">P.show(</span></tt> and pressing tab to get a list of
the options for how you can change the values of the given inputs.:</p>
<div class="highlight-python">

{{{id=28|
P.show(
///
}}}

</div>
<p>Plotting multiple functions at once is as easy as adding them together:</p>
<div class="highlight-python">

{{{id=29|
P1 = plot(sin(x), (x,0,2*pi))
P2 = plot(cos(x), (x,0,2*pi), rgbcolor=&#39;red&#39;)
P1 + P2
///
}}}

</div>
</div>
<div class="section" id="symbolic-expressions">
<h2>Symbolic Expressions<a class="headerlink" href="#symbolic-expressions" title="Permalink to this headline">¶</a></h2>
<p>Here is an example of a symbolic function:</p>
<div class="highlight-python">

{{{id=30|
f(x) = x^4 - 8*x^2 - 3*x + 2
f(x)
///
x^4 - 8*x^2 - 3*x + 2
}}}

{{{id=31|
f(-3)
///
20
}}}

</div>
<p>This is an example of a function in the <em>mathematical</em> variable <img class="math" src="_images/math/26eeb5258ca5099acf8fe96b2a1049c48c89a5e6.png" alt="x">. When Sage
starts, it defines the symbol <img class="math" src="_images/math/26eeb5258ca5099acf8fe96b2a1049c48c89a5e6.png" alt="x"> to be a mathematical variable. If you want
to use other symbols for variables, you must define them first.:</p>
<div class="highlight-python">

{{{id=32|
x^2
///
x^2
}}}

{{{id=33|
u + v
///
Traceback (click to the left of this block for traceback)

NameError: name 'u' is not defined
}}}

{{{id=34|
var(&#39;u v&#39;)
u + v
///
u + v
}}}

</div>
<p>It is possible, though, to define symbolic functions without first defining
the variables.:</p>
<div class="highlight-python">

{{{id=35|
f(w) = w^2
f(3)
///
9
}}}

</div>
<p><em>Exercise D:</em> Define the symbolic function <img class="math" src="_images/math/c1de89d139524e91a45002e98868fbb89f6f26ee.png" alt="f(x) = x \sin(x^2)">. Plot <img class="math" src="_images/math/bb2c93730dbb48558bb3c4738c956c4e8f816437.png" alt="f"> on the
domain <img class="math" src="_images/math/7dd9bb98fa7c18cbff92c6d09b49af1520aeb302.png" alt="[-3,3]"> and colour it red. Use the <tt class="docutils literal"><span class="pre">find_root</span></tt> method to numerically
approximate the root of <img class="math" src="_images/math/bb2c93730dbb48558bb3c4738c956c4e8f816437.png" alt="f"> on the interval <img class="math" src="_images/math/92bb4c21c8491453be13b7f2d521b1934160031f.png" alt="[1,2]">:</p>
<div class="highlight-python">

{{{id=36|
# edit here
///
}}}

</div>
<p>Compute the tangent line to <img class="math" src="_images/math/bb2c93730dbb48558bb3c4738c956c4e8f816437.png" alt="f"> at <img class="math" src="_images/math/4c52e02a35db152495396584bfeae1d0599cd753.png" alt="x=1">:</p>
<div class="highlight-python">

{{{id=37|
# edit here
///
}}}

</div>
<p>Plot <img class="math" src="_images/math/bb2c93730dbb48558bb3c4738c956c4e8f816437.png" alt="f"> and the tangent line to <img class="math" src="_images/math/bb2c93730dbb48558bb3c4738c956c4e8f816437.png" alt="f"> at <img class="math" src="_images/math/4c52e02a35db152495396584bfeae1d0599cd753.png" alt="x=1"> in one image:</p>
<div class="highlight-python">

{{{id=38|
# edit here
///
}}}

</div>
<p><em>Exercise E (Advanced):</em>  Solve the following equation for <img class="math" src="_images/math/092e364e1d9d19ad5fffb0b46ef4cc7f2da02c1c.png" alt="y"></p>
<div class="math">
<p><img src="_images/math/a0ebf003b7c529cd5a21b6923dd1ef83599aa950.png" alt="y = 1 + x y^2"></p>
</div><p>There are two solutions, take the one for which <img class="math" src="_images/math/699f68d1afcd0f36016009c49edfaf86e913e150.png" alt="\lim_{x\to0}y(x) = 1">. (Don&#8217;t
forget to create the variables <img class="math" src="_images/math/26eeb5258ca5099acf8fe96b2a1049c48c89a5e6.png" alt="x"> and <img class="math" src="_images/math/092e364e1d9d19ad5fffb0b46ef4cc7f2da02c1c.png" alt="y">!).:</p>
<div class="highlight-python">

{{{id=39|
# edit here
///
}}}

</div>
<p>Expand <img class="math" src="_images/math/092e364e1d9d19ad5fffb0b46ef4cc7f2da02c1c.png" alt="y"> as a truncated Taylor series around <img class="math" src="_images/math/bc1f9d9bf8a1b606a4188b5ce9a2af1809e27a89.png" alt="0"> and containing <img class="math" src="_images/math/dcc1b21210db29332b1a7d9ce088fd457f23aeee.png" alt="n=10">
terms.</p>
<div class="highlight-python">

{{{id=40|
# edit here
///
}}}

</div>
<p>Do you recognize the coefficients of the Taylor series expansion? You might
want to use the <a class="reference external" href="http://oeis.org">On-Line Encyclopedia of Integer Sequences</a>,
or better yet, Sage&#8217;s command <tt class="docutils literal"><span class="pre">sloane_find</span></tt> which queries the encyclopedia:</p>
<div class="highlight-python"><pre>sloane_find?&lt;tab&gt;</pre>
</div>
<div class="highlight-python">

{{{id=41|
# edit here
///
}}}

</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference internal" href="#">Tutorial: Using the Sage notebook, navigating the help system, first exercises</a><ul>
<li><a class="reference internal" href="#making-this-help-page-into-a-worksheet">Making this help page into a worksheet</a></li>
<li><a class="reference internal" href="#entering-editing-and-evaluating-input">Entering, Editing and Evaluating Input</a></li>
<li><a class="reference internal" href="#help-systems">Help systems</a></li>
<li><a class="reference internal" href="#completion-and-contextual-documentation">Completion and contextual documentation</a></li>
<li><a class="reference internal" href="#some-linear-algebra">Some linear algebra</a></li>
<li><a class="reference internal" href="#some-plotting">Some Plotting</a></li>
<li><a class="reference internal" href="#symbolic-expressions">Symbolic Expressions</a></li>
</ul>
</li>
</ul>

            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="_sources/tutorial-notebook-and-help-long.txt" rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index">index</a></li>
  
    
      <a href="../index.html"><img src="_static/sagelogo.png" style="vertical-align: middle" title="Sage Logo"></a>
    
  
  
        <li><a href="index.html">Thematic Tutorials v4.7.rc0</a> &raquo;</li>
 
      </ul>
    </div>
    
    <div class="footer">
        &copy; Copyright 2005--2011, The Sage Development Team.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.4.
    </div>
    <script type="text/javascript">
/*global jQuery, window */
/* Sphinx sidebar toggle.  Putting this code at the end of the body
 * enables the toggle for the live, static, and offline docs.  Note:
 * sage.misc.html.math_parse() eats jQuery's dollar-sign shortcut. */
var jq = jQuery;  
jq(document).ready(function () {
    var bar, bod, bg, fg, key, tog, wid_old, wid_new, resize, get_state, set_state;
    bod = jq('div.bodywrapper');
    bar = jq('div.sphinxsidebar');
    tog = jq('<div class="sphinxsidebartoggle"></div>');
    
    /* Delayed resize helper.  Not perfect but good enough. */
    resize = function () {
        setTimeout(function () {
            tog.height(bod.height());
        }, 100);
    };
    jq(window).resize(function () {
        resize();
    });
    
    /* Setup and add the toggle. See Sphinx v0.5.1 default.css. */
    fg = jq('div.sphinxsidebar p a').css('color') || 'rgb(152, 219, 204)';
    bg = jq('div.document').css('background-color') || 'rgb(28, 78, 99)';
    wid_old = '230px';
    wid_new = '5px';
    tog.css('background-color', bg)
        .css('border-width', '0px')
        .css('border-right', wid_new + ' ridge ' + bg)
        .css('cursor', 'pointer')
        .css('position', 'absolute')
        .css('left', '-' + wid_new)
        .css('top', '0px')
        .css('width', wid_new);
    bod.css('position', 'relative');
    bod.prepend(tog);
    resize();
    
    /* Cookie helpers. */
    key = 'sphinxsidebar=';
    set_state = function (s) {
        var date = new Date();
        /* Expiry in 7 days. */
        date.setTime(date.getTime() + (7 * 24 * 3600 * 1000));
        document.cookie = key + encodeURIComponent(s) + '; expires=' +
            date.toUTCString() + '; path=/';
    };
    get_state = function () {
        var i, c, crumbs = document.cookie.split(';');
        for (i = 0; i < crumbs.length; i += 1) {
            c = crumbs[i].replace(/^\s+/, '');
            if (c.indexOf(key) === 0) {
                return decodeURIComponent(c.substring(key.length, c.length));
            }
        }
        return null;
    };
    
    /* Event handlers. */
    tog.mouseover(function (ev) {
        tog.css('border-right-color', fg);
    }).mouseout(function (ev) {
        tog.css('border-right-color', bg);
    }).click(function (ev) {
        if (bod.hasClass('wide')) {
            bod.removeClass('wide');
            bod.css('margin-left', wid_old);
            bar.css('width', wid_old);
            bar.show();
            set_state('visible');
        } else {
            set_state('hidden');
            bar.hide();
            bar.css('width', '0px');
            bod.css('margin-left', wid_new);
            bod.addClass('wide');
        }
        resize();
    });
    
    /* Hide the normally visible sidebar? */
    if (get_state() === 'hidden') {
        tog.trigger('click');
    } else {
        set_state('visible');
    }
});
    </script>