PREP Intro Tutorial
system:sage


<h1 style="text-align: left;">Introductory Sage Tutorial - Welcome!</h1>
<p style="text-align: left;">This&nbsp;<a href="http://www.sagemath.org" target="_blank">Sage</a>&nbsp;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). &nbsp;It is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (<a href="http://creativecommons.org/licenses/by-sa/3.0/" target="_blank">CC BY-SA</a>). &nbsp;</p>
<p style="text-align: left;">Click <a href="#Main">here</a> to go straight to the main content of the tutorial.</p>
<h1 style="text-align: left;">Getting a Live Copy of a Worksheet</h1>
<p style="text-align: left;">The first part of the tutorial is to load this worksheet, of course! &nbsp; You'll need your <em>own</em>&nbsp;copy of the worksheet on the server. &nbsp;It should look like this at the top:</p>
<p style="text-align: left;"><img style="border: 2px solid black;" src="LiveWorksheet" alt="" width="669" height="156" /></p>
<p style="text-align: left;">Except, of course, your username will appear! &nbsp;If you already have a live copy, please skip <a href="#Main">below</a>.</p>
<p>If you don't see this, take another look at the top of the screen. &nbsp;Does it look like this? &nbsp; &nbsp;</p>
<p><img style="border: 2px solid black;" src="NotLoggedIn" alt="" width="636" height="105" /></p>
<p style="text-align: left; ">If so, you need to log in! &nbsp;Click the link at the upper left and follow usual website login creation/login procedures. &nbsp;(You will know the magic word if there is one.)</p>
<p>Otherwise, it should look like this:</p>
<p><img style="border: 2px solid black;" src="LoggedIn" alt="" width="658" height="111" /></p>
<p>It should also look like this once you log in. &nbsp; Now just click 'Edit this' so that it looks like this! &nbsp;</p>
<p><img style="border: 2px solid black;" src="LiveWorksheet" alt="" width="669" height="156" /></p>
<p>Then you can continue with the tutorial.</p>
<p>&nbsp;</p>
<p id="Main">The main part of the tutorial has the following sections:</p>
<ul>
<li><a href="#SageCommands">Evaluating Sage Commands</a></li>
<li><a href="#SageFunctions">Functions in Sage</a></li>
<li><a href="#SageHelp">Help inside Sage</a></li>
<li><a href="#SageAnnotation">Annotating with Sage</a></li>
</ul>
<p>This tutorial only introduces the most basic level of functionality. &nbsp;Later tutorials address topics such as calculus, advanced plotting, and a wide variety of specific mathematical topics.</p>
<h1 id="SageCommands" style="text-align: left;">Evaluating Sage Commands</h1>
<h3 style="text-align: left;">(i.e., How do I get Sage to do some math?)</h3>
<p id="Evaluate">Below, and throughout this <em>worksheet</em>, are little boxes called&nbsp;<em>input cells</em><span style="font-style: italic;"><span style="font-style: normal;">&nbsp;or </span><em>code cells</em>.</span>&nbsp;&nbsp; They should be about the width of your browser. &nbsp;</p>
<p>Evaluating the content of an input cell is very easy.</p>
<ul>
<li>First, click inside the cell so that the cell is active (i.e., has a bright blue border). &nbsp;</li>
<li>Then, just below the cell on the left, an "evaluate" link appears; clicking this link evaluates the cell. &nbsp;</li>
</ul>
<p>Try evaluating the following cell.</p>

{{{id=2|
2+2
///
4
}}}

<div style="color: #000000; background-image: initial; background-repeat: initial; background-attachment: initial; -webkit-background-clip: initial; -webkit-background-origin: initial; background-color: #ffffff; background-position: initial initial; margin: 8px;">
<p>Sage prints out its response just below the cell (that's the "4" above, so Sage confirms that $2+2=4$). &nbsp; Note also that Sage has automatically made the next cell active after you evaluated your first cell.</p>
<p>You can also evaluate a cell using a keyboard shortcut. &nbsp;</p>
<ul>
<li>If the following cell isn't active, click in it.&nbsp;</li>
<li>Then hold down the Shift key while you press the Enter key. &nbsp;</li>
</ul>
We call this "Shift-Enter". &nbsp;Try doing Shift-Enter with this cell.</div>

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

<p>An input cell isn't much use if it can only do one thing, so you can edit a cell and evaluate it again. &nbsp;Just click inside, and then make any changes you wish by typing as usual. &nbsp;</p>
<p>Try changing the number "2010" above to "2011" and evaluate the cell to find its factorization (surprised?); then try your own favorite number.</p>
<p>To do more math, we'll need to be able to create new input cells. &nbsp;This is also easy.</p>
<ul>
<li>Move your cursor over the space above or below another cell. &nbsp;</li>
<li>A blue horizontal line as wide as the browser should appear.&nbsp;</li>
<li>Click on the line to insert a new cell. &nbsp;</li>
</ul>
<p>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.</p>
<p>Try creating a few new input cells below, doing some arithmetic in those cells, and then deleting one of the input cells.</p>

{{{id=6|

///
}}}

{{{id=125|

///
}}}

<h1 id="SageFunctions" style="text-align: left;">Functions in Sage</h1>
<p>To start out, let's explore how to define and use functions in Sage.</p>
<p>For a typical mathematical function, it's pretty straightforward to define it. &nbsp;Below, we define the function $$f(x)=x^2\; .$$</p>

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

<p>Since all we wanted was to create the function $f(x)$, Sage just does this and doesn't print anything out back to us.</p>
<p>We can check the definition by asking Sage what $f(x)$ is:</p>

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

<p>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 "|--&gt;").</p>

{{{id=126|
f
///
x |--> x^2
}}}

<p>We can evaluate $f$ at various values.</p>

{{{id=103|
f(3)
///
9
}}}

{{{id=166|
f(3.1)
///
9.61000000000000
}}}

<p>Naturally, we are not restricted to $x$ as a variable. &nbsp;In the next cell, we define the function $g(y)=2y-1$.</p>

{{{id=167|
g(y)=2*y-1
///
}}}

<p>However, we need to make sure we do define a function if we use a new variable. &nbsp;In the next cell, we see what happens if we try to use a random input by itself.</p>

{{{id=169|
z^2
///
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_12.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("el4y"),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single')
  File "", line 1, in <module>
    
  File "/tmp/tmpmnlwvp/___code___.py", line 3, in <module>
    exec compile(u'z**_sage_const_2 ' + '\n', '', 'single')
  File "", line 1, in <module>
    
NameError: name 'z' is not defined
}}}

<p>This is explained in some detail in following tutorials. &nbsp;At this point, it suffices to know using the function notation (like "g(y)") tells Sage you are serious about "y" being a variable.</p>
<p>One can also do this with the "var('z')" notation below.</p>

{{{id=171|
var('z')
z^2
///
z^2
}}}

<p>This also demonstrates that we can put several commands in one cell, each on a separate line.&nbsp; The output of the last command (if any) is printed as the output of the cell.</p>
<p>Sage knows various common mathematical constants, like $\pi$ ("pi") and $e$.</p>

{{{id=109|
f(pi)
///
pi^2
}}}

{{{id=115|
f(e^-1)
///
e^(-2)
}}}

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

{{{id=118|
N(f(pi))
///
9.86960440108936
}}}

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

{{{id=117|
f(pi).n()
///
9.86960440108936
}}}

<p>For now, we won't go in great depth explaining the reasons behind this syntax, which may be new to you. &nbsp;&nbsp;For those who are interested, Sage often uses this type of syntax (known as "object-oriented") because...</p>
<ul>
<li>Sage uses the Python programming language, which uses this syntax,&nbsp;'under the hood', and&nbsp;</li>
<li>Because it makes it easier to distinguish among 
<ul>
<li>The mathematical object,</li>
<li>The thing you are doing to it, and</li>
<li>Any ancillary arguments. </li>
</ul>
</li>
</ul>
<p>For example, the following numerically evaluates ('n') the constant $\pi$ ('pi') to twenty digits ('digits=20').</p>

{{{id=158|
pi.n(digits=20)
///
3.1415926535897932385
}}}

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

{{{id=120|
log(3)
///
log(3)
}}}

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

{{{id=163|
log(3)+log(3)
///
2*log(3)
}}}

{{{id=161|
log(3).n()
///
1.09861228866811
}}}

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

{{{id=175|
log(3.)
///
1.09861228866811
}}}

{{{id=121|
sqrt(2)
///
sqrt(2)
}}}

<p>If we want this to look nicer, we can use the "show" command. &nbsp;We'll see more of this sort of things below.</p>

{{{id=164|
show(sqrt(2))
///
<html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\sqrt{2}</div></html>
}}}

{{{id=149|
sqrt(2).n()
///
1.41421356237310
}}}

<p>Do you remember what $f$ does?</p>

{{{id=150|
f(sqrt(2))
///
2
}}}

<p>We can also plot functions easily. &nbsp;</p>

{{{id=122|
plot(f, (x,-3,3))
///
<html><font color='black'><img src='cell://sage0.png'></font></html>
}}}

<p>In another tutorial, we will go more in depth with plotting. &nbsp;Here, note that the preferred syntax has the variable and endpoints for the plotting domain in parentheses, separated by commas.</p>
<p>If you are feeling bold, plot the "sqrt" function in the next cell between 0 and 100.</p>

{{{id=108|

///
}}}

<h1 id="SageHelp">Help inside Sage</h1>
<p>There are various ways to get help for doing things in Sage.&nbsp; Here are several common ways to get help as you are working in a Sage worksheet.</p>
<h2>Documentation</h2>
<p>Sage includes extensive documentation covering thousands of  functions, with many examples, tutorials, and other helps.&nbsp;</p>
<ul>
<li>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.</li>
<li>They are also available any time online at the <a href="http://www.sagemath.org/help.html" target="_blank">Sage website</a>, which has many other links, like video introductions.&nbsp;&nbsp;</li>
<li>The <a href="http://wiki.sagemath.org/quickref" target="_blank">Quick Reference cards</a> are another useful tool once you get more familiar with Sage.</li>
</ul>
<p>Our main focus in this tutorial, though, is help you can immediately access from within a worksheet, where you don't have to do <em>any</em>&nbsp;of those things.</p>
<h2>Tab completion</h2>
<p>The most useful help available in the notebook is "tab completion". &nbsp; 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. &nbsp;Here's an example.</p>
<ul>
<li>Suppose you want to do a specific type of plot - maybe a slope field plot - but aren't quite sure what will do it. &nbsp;&nbsp;</li>
<li>Still, it seems reasonable that the command might start with "pl".</li>
<li>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".</li>
</ul>
<p>Try tabbing after the "pl" in the following cell to see all the commands that start with the letters "pl". &nbsp; &nbsp; You should see that "plot_slope_field" is one of them.</p>

{{{id=132|
pl
///
}}}

<p>To pick one, just click on it; to stop viewing them, press the Escape/esc key.</p>
<p>You can also use this to see what you can do to an expression or mathematical object.</p>
<ul>
<li>Assuming your expression has a name, type it;</li>
<li>Then type a period after it,</li>
<li>Then press tab.&nbsp;&nbsp;</li>
</ul>
<p>You will see a list pop up of all the things you can do to the expression.</p>
<p>To try this, evaluate the following cell, just to make sure $f$ is defined.</p>

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

<p>Now put your cursor after the period and press your tab key. &nbsp;</p>

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

<p>Again, Escape should remove the list.</p>
<p>One of the things in that list above was "integrate".&nbsp; Let's try it.</p>

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

<h2><strong>Finding documentation (the question marks)</strong></h2>
<p>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()".</p>
<p>To find out, there is another help tool one can use from right inside the notebook. &nbsp;Almost all documentation in Sage has extensive examples that can illustrate how to use the function.</p>
<ul>
<li>As with tab completion, type the expression, period, and the name of the function.</li>
<li>Then type a question mark.</li>
<li>Press tab <em>or</em>&nbsp;evaluate to see the documentation.</li>
</ul>
<p>To see how this help works, move your cursor after the question mark below and press tab.</p>
<ul>
</ul>

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

<p>The examples illustrate that the syntax requires "f.integrate(x)" and not just "f.integrate()". &nbsp; (After all, the latter could be ambiguous if several variables had already been defined).</p>
<p>To stop viewing the documentation after pressing tab, you can press the Escape key, just like with the completion of options.</p>
<p>If you would like the documentation to be visible longer-term, you can <em>evaluate</em> a command with the question mark (like below) to access the documentation, rather than just tabbing. &nbsp;Then it will stay there until you remove the input cell.</p>

{{{id=14|
binomial?
///
<html><!--notruncate-->
<div class="docstring">
    
  <p><strong>File:</strong> /usr/local/sage-prep/local/lib/python2.6/site-packages/sage/rings/arith.py</p>
<p><strong>Type:</strong> &lt;type &#8216;function&#8217;&gt;</p>
<p><strong>Definition:</strong> binomial(x, m)</p>
<p><strong>Docstring:</strong></p>
<blockquote>
<p>Return the binomial coefficient</p>
<div class="math">
\binom{x}{m} = x (x-1) \cdots (x-m+1) / m!</div>
<p>which is defined for <span class="math">m \in \ZZ</span> and any
<span class="math">x</span>. We extend this definition to include cases when
<span class="math">x-m</span> is an integer but <span class="math">m</span> is not by</p>
<div class="math">
\binom{x}{m}= \binom{x}{x-m}</div>
<p>If <span class="math">m &lt; 0</span>, return <span class="math">0</span>.</p>
<p>INPUT:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">x</span></tt>, <tt class="docutils literal"><span class="pre">m</span></tt> - numbers or symbolic expressions. Either <tt class="docutils literal"><span class="pre">m</span></tt>
or <tt class="docutils literal"><span class="pre">x-m</span></tt> must be an integer.</li>
</ul>
<p>OUTPUT: number or symbolic expression (if input is symbolic)</p>
<p>EXAMPLES:</p>
<div class="highlight-python"><div class="highlight"><pre class="literal-block"><span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">5</span><span class="p">,</span><span class="mf">2</span><span class="p">)</span>
<span class="go">10</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">2</span><span class="p">,</span><span class="mf">0</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">1</span><span class="o">/</span><span class="mf">2</span><span class="p">,</span> <span class="mf">0</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">3</span><span class="p">,</span><span class="o">-</span><span class="mf">1</span><span class="p">)</span>
<span class="go">0</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">20</span><span class="p">,</span><span class="mf">10</span><span class="p">)</span>
<span class="go">184756</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="o">-</span><span class="mf">2</span><span class="p">,</span> <span class="mf">5</span><span class="p">)</span>
<span class="go">-6</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="n">RealField</span><span class="p">()(</span><span class="s">&#39;2.5&#39;</span><span class="p">),</span> <span class="mf">2</span><span class="p">)</span>
<span class="go">1.87500000000000</span>
<span class="gp">sage: </span><span class="n">n</span><span class="o">=</span><span class="n">var</span><span class="p">(</span><span class="s">&#39;n&#39;</span><span class="p">);</span> <span class="n">binomial</span><span class="p">(</span><span class="n">n</span><span class="p">,</span><span class="mf">2</span><span class="p">)</span>
<span class="go">1/2*(n - 1)*n</span>
<span class="gp">sage: </span><span class="n">n</span><span class="o">=</span><span class="n">var</span><span class="p">(</span><span class="s">&#39;n&#39;</span><span class="p">);</span> <span class="n">binomial</span><span class="p">(</span><span class="n">n</span><span class="p">,</span><span class="n">n</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">sage: </span><span class="n">n</span><span class="o">=</span><span class="n">var</span><span class="p">(</span><span class="s">&#39;n&#39;</span><span class="p">);</span> <span class="n">binomial</span><span class="p">(</span><span class="n">n</span><span class="p">,</span><span class="n">n</span><span class="o">-</span><span class="mf">1</span><span class="p">)</span>
<span class="go">n</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">2</span><span class="o">^</span><span class="mf">100</span><span class="p">,</span> <span class="mf">2</span><span class="o">^</span><span class="mf">100</span><span class="p">)</span>
<span class="go">1</span>

<span class="gp">sage: </span><span class="n">k</span><span class="p">,</span> <span class="n">i</span> <span class="o">=</span> <span class="n">var</span><span class="p">(</span><span class="s">&#39;k,i&#39;</span><span class="p">)</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="n">k</span><span class="p">,</span><span class="n">i</span><span class="p">)</span>
<span class="go">binomial(k, i)</span>
</pre></div>
</div>
<p>TESTS:</p>
<p>We test that certain binomials are very fast (this should be
instant) &#8211; see trac 3309:</p>
<div class="highlight-python"><div class="highlight"><pre class="literal-block"><span class="gp">sage: </span><span class="n">a</span> <span class="o">=</span> <span class="n">binomial</span><span class="p">(</span><span class="n">RR</span><span class="p">(</span><span class="mf">1140000.78</span><span class="p">),</span> <span class="mf">42000000</span><span class="p">)</span>
</pre></div>
</div>
<p>We test conversion of arguments to Integers &#8211; see trac 6870:</p>
<div class="highlight-python"><div class="highlight"><pre class="literal-block"><span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">1</span><span class="o">/</span><span class="mf">2</span><span class="p">,</span><span class="mf">1</span><span class="o">/</span><span class="mf">1</span><span class="p">)</span>
<span class="go">1/2</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">10</span><span class="o">^</span><span class="mf">20</span><span class="o">+</span><span class="mf">1</span><span class="o">/</span><span class="mf">1</span><span class="p">,</span><span class="mf">10</span><span class="o">^</span><span class="mf">20</span><span class="p">)</span>
<span class="go">100000000000000000001</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="n">SR</span><span class="p">(</span><span class="mf">10</span><span class="o">**</span><span class="mf">7</span><span class="p">),</span><span class="mf">10</span><span class="o">**</span><span class="mf">7</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">3</span><span class="o">/</span><span class="mf">2</span><span class="p">,</span><span class="n">SR</span><span class="p">(</span><span class="mf">1</span><span class="o">/</span><span class="mf">1</span><span class="p">))</span>
<span class="go">3/2</span>
</pre></div>
</div>
<p>Some floating point cases &#8211; see trac 7562:</p>
<div class="highlight-python"><div class="highlight"><pre class="literal-block"><span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="mf">1.</span><span class="p">,</span><span class="mf">3</span><span class="p">)</span>
<span class="go">0.000000000000000</span>
<span class="gp">sage: </span><span class="n">binomial</span><span class="p">(</span><span class="o">-</span><span class="mf">2.</span><span class="p">,</span><span class="mf">3</span><span class="p">)</span>
<span class="go">-4.00000000000000</span>
</pre></div>
</div>
</blockquote>


</div>
</html>
}}}

<p>Try this with another function!</p>

{{{id=173|

///
}}}

<p>&nbsp;</p>
<h2>Finding the source</h2>
<p>There is one more source of help you may find useful in the long run, though perhaps not immediately. &nbsp;</p>
<ul>
<li>One can use <em>two</em> question marks after a function name to pull up the documentation <em>and</em> the source code for the function. &nbsp;</li>
<li>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.</li>
</ul>
<p>The ability to see the code (the underlying instructions to the computer) is one of Sage's great strengths.&nbsp; You can see <em>all</em> the code to <em>everything</em>.&nbsp;</p>
<p>This means:</p>
<ul>
<li><em>You</em> can see what Sage is doing.</li>
<li>Your curious students can see what is going on.</li>
<li>And if you find a better way to do something, then you can see how to change it!</li>
</ul>

{{{id=129|
binomial??
///
<html><!--notruncate-->
<div class="docstring">
    
  <p><strong>File:</strong> /usr/local/sage-prep/local/lib/python2.6/site-packages/sage/rings/arith.py</p>
<p><strong>Source Code</strong> (starting at line 2784):</p>
<div class="highlight-python"><div class="highlight"><pre class="literal-block"><span class="k">def</span> <span class="nf">binomial</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">m</span><span class="p">):</span>
    <span class="s">r&quot;&quot;&quot;</span>
<span class="s">    Return the binomial coefficient</span>

<span class="s">    .. math::</span>

<span class="s">                \binom{x}{m} = x (x-1) \cdots (x-m+1) / m!</span>


<span class="s">    which is defined for `m \in \ZZ` and any</span>
<span class="s">    `x`. We extend this definition to include cases when</span>
<span class="s">    `x-m` is an integer but `m` is not by</span>

<span class="s">    .. math::</span>

<span class="s">        \binom{x}{m}= \binom{x}{x-m}</span>

<span class="s">    If `m &lt; 0`, return `0`.</span>

<span class="s">    INPUT:</span>

<span class="s">    -  ``x``, ``m`` - numbers or symbolic expressions. Either ``m``</span>
<span class="s">       or ``x-m`` must be an integer.</span>

<span class="s">    OUTPUT: number or symbolic expression (if input is symbolic)</span>

<span class="s">    EXAMPLES::</span>

<span class="s">        sage: binomial(5,2)</span>
<span class="s">        10</span>
<span class="s">        sage: binomial(2,0)</span>
<span class="s">        1</span>
<span class="s">        sage: binomial(1/2, 0)</span>
<span class="s">        1</span>
<span class="s">        sage: binomial(3,-1)</span>
<span class="s">        0</span>
<span class="s">        sage: binomial(20,10)</span>
<span class="s">        184756</span>
<span class="s">        sage: binomial(-2, 5)</span>
<span class="s">        -6</span>
<span class="s">        sage: binomial(RealField()(&#39;2.5&#39;), 2)</span>
<span class="s">        1.87500000000000</span>
<span class="s">        sage: n=var(&#39;n&#39;); binomial(n,2)</span>
<span class="s">        1/2*(n - 1)*n</span>
<span class="s">        sage: n=var(&#39;n&#39;); binomial(n,n)</span>
<span class="s">        1</span>
<span class="s">        sage: n=var(&#39;n&#39;); binomial(n,n-1)</span>
<span class="s">        n</span>
<span class="s">        sage: binomial(2^100, 2^100)</span>
<span class="s">        1</span>

<span class="s">        sage: k, i = var(&#39;k,i&#39;)</span>
<span class="s">        sage: binomial(k,i)</span>
<span class="s">        binomial(k, i)</span>

<span class="s">    TESTS:</span>

<span class="s">    We test that certain binomials are very fast (this should be</span>
<span class="s">    instant) -- see trac 3309::</span>

<span class="s">        sage: a = binomial(RR(1140000.78), 42000000)</span>

<span class="s">    We test conversion of arguments to Integers -- see trac 6870::</span>

<span class="s">        sage: binomial(1/2,1/1)</span>
<span class="s">        1/2</span>
<span class="s">        sage: binomial(10^20+1/1,10^20)</span>
<span class="s">        100000000000000000001</span>
<span class="s">        sage: binomial(SR(10**7),10**7)</span>
<span class="s">        1</span>
<span class="s">        sage: binomial(3/2,SR(1/1))</span>
<span class="s">        3/2</span>

<span class="s">    Some floating point cases -- see trac 7562::</span>

<span class="s">        sage: binomial(1.,3)</span>
<span class="s">        0.000000000000000</span>
<span class="s">        sage: binomial(-2.,3)</span>
<span class="s">        -4.00000000000000</span>
<span class="s">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">m</span><span class="p">,</span><span class="n">sage</span><span class="o">.</span><span class="n">symbolic</span><span class="o">.</span><span class="n">expression</span><span class="o">.</span><span class="n">Expression</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="c"># For performance reasons, we avoid to try to coerce</span>
            <span class="c"># to Integer in the symbolic case (see #6870)</span>
            <span class="n">m</span><span class="o">=</span><span class="n">m</span><span class="o">.</span><span class="n">pyobject</span><span class="p">()</span>
            <span class="n">m</span><span class="o">=</span><span class="n">ZZ</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
            <span class="k">pass</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">m</span><span class="o">=</span><span class="n">ZZ</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
            <span class="k">pass</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">m</span><span class="p">,</span><span class="n">integer</span><span class="o">.</span><span class="n">Integer</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">m</span> <span class="o">=</span> <span class="n">ZZ</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="n">m</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="k">return</span> <span class="n">x</span><span class="o">.</span><span class="n">binomial</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
            <span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
                <span class="k">pass</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="s">&#39;Either m or x-m must be an integer&#39;</span>
    <span class="c"># a (hopefully) temporary fix for #3309; eventually Pari should do</span>
    <span class="c"># this for us.</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="p">(</span><span class="nb">float</span><span class="p">,</span> <span class="n">sage</span><span class="o">.</span><span class="n">rings</span><span class="o">.</span><span class="n">real_mpfr</span><span class="o">.</span><span class="n">RealNumber</span><span class="p">,</span>
                      <span class="n">sage</span><span class="o">.</span><span class="n">rings</span><span class="o">.</span><span class="n">real_mpfr</span><span class="o">.</span><span class="n">RealLiteral</span><span class="p">)):</span>
        <span class="n">P</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">parent</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">m</span> <span class="o">&lt;</span> <span class="mf">0</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">P</span><span class="p">(</span><span class="mf">0</span><span class="p">)</span>
        <span class="kn">from</span> <span class="nn">sage.functions.all</span> <span class="kn">import</span> <span class="n">gamma</span>
        <span class="k">if</span> <span class="n">x</span> <span class="o">&gt;</span> <span class="o">-</span><span class="mf">1</span><span class="o">/</span><span class="mf">2</span><span class="p">:</span>
            <span class="n">a</span> <span class="o">=</span> <span class="n">gamma</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="n">m</span><span class="o">+</span><span class="mf">1</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">a</span><span class="p">:</span>
                <span class="k">return</span> <span class="n">gamma</span><span class="p">(</span><span class="n">x</span><span class="o">+</span><span class="mf">1</span><span class="p">)</span><span class="o">/</span><span class="n">gamma</span><span class="p">(</span><span class="n">P</span><span class="p">(</span><span class="n">m</span><span class="o">+</span><span class="mf">1</span><span class="p">))</span><span class="o">/</span><span class="n">a</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="k">return</span> <span class="n">P</span><span class="p">(</span><span class="mf">0</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="p">(</span><span class="o">-</span><span class="mf">1</span><span class="p">)</span><span class="o">**</span><span class="n">m</span><span class="o">*</span><span class="n">gamma</span><span class="p">(</span><span class="n">m</span><span class="o">-</span><span class="n">x</span><span class="p">)</span><span class="o">/</span><span class="n">gamma</span><span class="p">(</span><span class="n">P</span><span class="p">(</span><span class="n">m</span><span class="o">+</span><span class="mf">1</span><span class="p">))</span><span class="o">/</span><span class="n">gamma</span><span class="p">(</span><span class="o">-</span><span class="n">x</span><span class="p">)</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">sage</span><span class="o">.</span><span class="n">symbolic</span><span class="o">.</span><span class="n">expression</span><span class="o">.</span><span class="n">Expression</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">x</span><span class="o">=</span><span class="n">x</span><span class="o">.</span><span class="n">pyobject</span><span class="p">()</span>
            <span class="n">x</span><span class="o">=</span><span class="n">ZZ</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
            <span class="k">pass</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">x</span><span class="o">=</span><span class="n">ZZ</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
            <span class="k">pass</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">integer</span><span class="o">.</span><span class="n">Integer</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">x</span> <span class="o">&gt;=</span> <span class="mf">0</span> <span class="ow">and</span> <span class="p">(</span><span class="n">m</span> <span class="o">&lt;</span> <span class="mf">0</span> <span class="ow">or</span> <span class="n">m</span> <span class="o">&gt;</span> <span class="n">x</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">ZZ</span><span class="p">(</span><span class="mf">0</span><span class="p">)</span>

        <span class="k">if</span> <span class="n">m</span> <span class="o">&gt;</span> <span class="n">sys</span><span class="o">.</span><span class="n">maxint</span><span class="p">:</span>
            <span class="n">m</span> <span class="o">=</span> <span class="n">x</span> <span class="o">-</span> <span class="n">m</span>
            <span class="k">if</span> <span class="n">m</span> <span class="o">&gt;</span> <span class="n">sys</span><span class="o">.</span><span class="n">maxint</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">,</span> <span class="s">&quot;binomial not implemented for m &gt;= 2^32.</span><span class="se">\n</span><span class="s">This is probably OK, since the answer would have billions of digits.&quot;</span>

        <span class="k">return</span> <span class="n">ZZ</span><span class="p">(</span><span class="n">pari</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">binomial</span><span class="p">(</span><span class="n">m</span><span class="p">))</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">P</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">parent</span><span class="p">()</span>
    <span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
        <span class="n">P</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">m</span> <span class="o">&lt;</span> <span class="mf">0</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">P</span><span class="p">(</span><span class="mf">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">misc</span><span class="o">.</span><span class="n">prod</span><span class="p">([</span><span class="n">x</span><span class="o">-</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">m</span><span class="p">)])</span> <span class="o">/</span> <span class="n">P</span><span class="p">(</span><span class="n">factorial</span><span class="p">(</span><span class="n">m</span><span class="p">))</span>
</pre></div>
</div>


</div>
</html>
}}}

<h1 id="SageAnnotation" style="font-size: 2em;">Annotating with Sage</h1>
<p>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. &nbsp;&nbsp;</p>
<p>Thanks to&nbsp;<a title="Open external site in a new window" href="http://tinymce.moxiecode.com/" target="_blank">the mini-word processor TinyMCE</a>&nbsp;and a TeX rendering engine called&nbsp;<a title="Open external site in a new window" href="http://www.math.union.edu/~dpvc/jsMath/" target="_blank">jsmath</a>, you can type much more in Sage than just Sage commands.&nbsp; This math-aware setup makes Sage perfect for annotating computations.&nbsp;</p>
<p>To use the word processor, we create a&nbsp;<em>text cell</em>&nbsp;(as opposed to a&nbsp;<em>input cell</em>&nbsp;that contains Sage commands that Sage evaluates).&nbsp;</p>
<p>To create a text cell, do the following.</p>
<ul>
<li>First, move the cursor between two input cells, until the thin blue line appears.</li>
<li>Then hold the Shift key and click on the thin blue line.&nbsp;</li>
<li>(So to create an input cell, one merely clicks, but one "Shift-Click"s to create a text cell.)</li>
</ul>
<p>Try inserting a text cell between the input cells below.</p>

{{{id=147|

///
}}}

{{{id=146|

///
}}}

<p>TinyMCE makes it easy for format text in many ways.&nbsp; Try experimenting with the usual <strong>bold</strong> button, <span style="text-decoration: underline;">underline</span> button, different text <span style="font-family: 'comic sans ms', sans-serif;">fonts</span> and <span style="background-color: #00ffff;"><span style="color: #ff0000;">colors</span></span>, ordered and unordered lists, centering, and so on. &nbsp;Some of the shortcut keys you are familiar with from other word processors may also work, depending on your system.</p>
<p>There are two other things you can do which take advantage of the worksheet being on the web. &nbsp;</p>
<ul>
<li>It is easy to link to other helpful websites for additional information. &nbsp; 
<ul>
<li>While in the editor, highlight a word or two, and then click on the little chain link toward the bottom right of the buttons. &nbsp;</li>
<li>You can now type in a web address to link to. &nbsp;</li>
<li>Be sure to prepend http:// to the address. &nbsp;Normally, one should also select it to appear in a new window (so the Sage session isn't interrupted).</li>
</ul>
</li>
<li>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! &nbsp; 
<ul>
<li>For instance, it isn't too hard to add things like $$\zeta(s)=\sum_{n=1}^{\infty}\frac{1}{n^s}=\prod_p \left(\frac{1}{1-p^{-s}}\right)\; .$$&nbsp;</li>
<li>One just types things like&nbsp;"\$\$\zeta(s)=\sum_{n=1}^{\infty}\frac{1}{n^s}=\prod_p \left(\frac{1}{1-p^{-s}}\right)\$\$" in the word processor. &nbsp;</li>
<li>Whether this shows up as nicely as possible depends on what fonts you have in your browser, but it should be legible. &nbsp;</li>
<li>More realistically, we might type "\$f(x)=x^2\$" so that we remember that $f(x)=x^2$ in this worksheet.</li>
</ul>
</li>
</ul>
<p>Here is a simpler example.</p>
<ul>
</ul>

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

<p>If $f(x)=x^2$, then $f(9)=81$.</p>
<p>It is simple to edit a text cell; simply double-click on the text.&nbsp;</p>
<p>Try double-clicking on this text to edit this text cell (or any text cell) to see how we typed the mathematics!</p>

{{{id=157|

///
}}}

<p>Of course, one can do much more, since Sage can execute arbitrary commands in the&nbsp;<a href="http://www.python.org" target="_blank">Python</a>&nbsp;programming language, as well as output nicely formatted HTML, and so on. &nbsp;If you have enough programming experience to do things like this, go for it!</p>

{{{id=165|
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><font color='black'>Sage is <a style='text-decoration:line-through'>somewhat</a> <b>really</b> cool! <p style='color:red'>(It even does HTML.)</p></font></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 the notebook, or at <a href="http://www.sagemath.org" target="_blank">the Sage website</a>.</p>
<p>The next tutorial is for basic symbolics and plotting; or feel free to just start creating worksheets!</p>

{{{id=156|

///
}}}