Sage Tutorial for Symbolics and Plotting

This Sage worksheet is one of the tutorials developed for the MAA PREP Workshop "Sage: Using Open-Source Mathematics Software with Undergraduates" (funding provided by NSF DUE 0817071). 

This tutorial has the following sections:

This tutorial assumes that one is familiar with the basics of Sage.  We provide a (very) brief refresher.

  1. Make sure the syntax below for defining a function and getting a value makes sense.
  2. Then evaluate the cell by clicking the "evaluate" link, or by pressing Shift-Enter (hold down Shift while pressing the Enter key).
{{{id=134| f(x)=x^3+1 f(2) /// 9 }}}

Symbolic Expressions

In addition to defining functions like we did above, we can just define expressions involving variables.  In the cell below, we define an expression $FV$ which is the future value of an investment of \$100, compounded continuously.  We then substitute in values for $r$ and $t$ which calculate the future value for $t=5$ years and $r=5\%$ nominal interest.

{{{id=56| var('r,t') FV=100*e^(r*t) FV(r=.05,t=5) /// 128.402541668774 }}}

Some things to remember when working with symbolic expressions are:

Notice that when we define a function, we don't need to specify which variable has which value, since when we define a function, we must specify the order:

{{{id=136| FV2(r,t)=100*e^(r*t) FV2(.05,5) /// 128.402541668774 }}}

Next, let's do some algebraic manipulations with expressions.

In the cells below, you'll notice something new: the number sign "#".  In Sage (and in Python), anything on a single line after the number sign is ignored.  We say that "#" is a comment character.  We use it below to mention alternative ways to do the same thing.

{{{id=58| z = (x+1)^3 /// }}} {{{id=81| expand(z) # or z.expand() /// x^3 + 3*x^2 + 3*x + 1 }}} {{{id=82| y = expand(z) y.factor() # or factor(y) /// (x + 1)^3 }}}

In the previous cell, we assigned the expression which is the expansion of $z$ to the variable $y$ with the first line.  After that, anything we want to do to the expansion of $z$ can be done by doing it to $y$.

There are more commands like this as well.  Notice that $z$ will no longer be $(x-1)^3$ after this cell is evaluated, since we've assigned $z$ to a (much more complex) expression.

{{{id=84| z = ((x - 1)^(3/2) - (x + 1)*sqrt(x - 1))/sqrt((x - 1)*(x + 1)) z.simplify_full() /// -2/sqrt(x + 1) }}} {{{id=140| z.simplify_rational() # Just simplify the fraction part of the expression by combining it. /// -2*sqrt(x - 1)/sqrt(x^2 - 1) }}}

You can see various methods for simplifying an expression by using tab completion.  Put your cursor at the end of the next cell (after the "simplify") and press tab to see lots of different methods.  Remember that you can use the question mark (e.g., "z.simplify_rational?") to get help about a particular method.

{{{id=142| z.simplify /// ((x - 1)^(3/2) - sqrt(x - 1)*(x + 1))/sqrt((x - 1)*(x + 1)) }}}

Don't forget, you can get nicely typeset versions of the output in several ways.  One option is to click the 'Typeset' button at the top, while another is to use the "show" command.

{{{id=86| show(z.simplify_rational()) ///
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{-2 \, \sqrt{x - 1}}{\sqrt{x^{2} - 1}}
}}}

Another Sage command that is useful is the "solve" command.  Here, we solve the equation $x^2=-1$.  In the solve command, we type an equals sign in the equation as two equal signs (since the single equals sign means assignment, as we've done above).  We also denote the variable we'd like to solve for.

{{{id=87| solve(x^2==-1,x) # solve x^2==-1 for x /// [x == -I, x == I] }}} {{{id=89| solve(z==0,x) /// [x == 1] }}}

Basic 2D Plotting

Before going into how Sage can be used for various calculus topics, we include a brief introduction to plotting the sorts of things which can be quite useful in calculus.  There will be a separate tutorial for seeing more advanced plotting techniques.

Recall that we can generate a plot using fairly simple syntax:

{{{id=135| f(x)=x^3+1 plot(f,(x,-1,1)) /// }}}

We can give the plot a name, so that if we want to do something with the plot later, we don't have to type out the entire plot command.  In the next cell, we give the plot the name $P$.

{{{id=19| P=plot(f,(x,-1,1)) /// }}}

You can superimpose plots by adding them together.  For instance, observe that the tangent line to $f$ at $x=0$ is just the line $y=1$.  Let's plot this, in a different color, and with a different style for the line, but over the same interval.  Notice that we can get the plot $Q$ to show up by putting it in a separate line by itself.

{{{id=23| Q=plot(1,(x,-1,1),color="red", linestyle="--") Q /// }}}

To show both plots superimposed on each other, we simply add them.

{{{id=27| P+Q /// }}}

Suppose we wanted to zoom in on this.  We could create another plot.  Another way to zoom in is to set the plot window using the "show" command:

{{{id=31| (P+Q).show(xmin=-.1,xmax=.1,ymin=.99,ymax=1.01) /// }}}

Since the axes no longer cross in the frame of reference, Sage shows a short gap between the horizontal and vertical axes. 

There are many options one can pass in for various purposes.  Pay very close attention to which ones require quotes around the values (such as the color option when we made a "red" line) and which ones do not (such as the xmin in the previous plot, where the minimum x value was just $-.1$).  Usually (though not always) quotes are required for option values which are words or strings of characters, and not required for numerical values.

Perhaps one of the most useful of these options is the "axes_labels" option to get labels for the axes; as with the word processor, using dollar signs (like in Latex) to make the labels typeset nicely.  Here we need both quotes and brackets for proper syntax, since there are two axes to label and the labels are not actually numbers.

{{{id=35| plot(f,(x,-1,1),axes_labels=['$x$','$y$']) /// }}}

One final note is that plots of functions with vertical asymptotes may need their vertical viewing range set manually to be useful.

{{{id=47| plot(1/x^2,(x,-10,10),ymax=10) /// }}}

Remember, you can use the command "plot?" to find out about most of the options demonstrated above.

Below are a few plotting options that you can experiment with.  Just evaluate the cell below and play with the sliders, buttons, color picker, etc., to change the plot options.  This uses a feature of Sage called "interacts", and is a very powerful way to engage a student in exploring a problem.

{{{id=151| var('x') @interact def plot_example(f=sin(x^2),r=range_slider(-5,5,step_size=1/4,default=(-3,3)), color=color_selector(widget='colorpicker'), thickness=(3,(1..10)), adaptive_recursion=(5,(0..10)), adaptive_tolerance=(0.01,(0.001,1)), plot_points=(20,(1..100)), linestyle=['-','--','-.',':'], gridlines=False, fill=False, frame=False, axes=True ): show(plot(f, (x,r[0],r[1]), color=color, thickness=thickness, adaptive_recursion=adaptive_recursion, adaptive_tolerance=adaptive_tolerance, plot_points=plot_points, linestyle=linestyle, fill=fill if fill else None), gridlines=gridlines, frame=frame, axes=axes) ///
color 
thickness 
adaptive_recursion 
adaptive_tolerance 
plot_points 
linestyle 
gridlines 
fill 
frame 
axes 
}}}

Basic 3D Plotting

There are several mechanisms for viewing three-dimensional plots in Sage, but we will stick to the default option in the notebook interface, which is via Java applets from the program Jmol.

Plotting a 3D plot is similar to plotting a 2D plot, but we need to specify ranges for two variables instead of one.

{{{id=69| g(x,y)=sin(x^2+y^2) plot3d(g,(x,-5,5),(y,-5,5)) /// }}}

There is a lot you can do with the 3D plots.  Try rotating the plot above by clicking and dragging the mouse inside of the plot.  Also, right-click (Control-click if you have only one mouse button) inside of the plot to see other options in a menu.  If you have a wheel on your mouse, you can scroll the mousewheel to zoom.  You can also right-click to see other options, such as spinning the plot, changing various colors, and even making the plot suitable for viewing through 3D glasses (under the "style", then "stereographic" submenus)

When using the "plot3d" command, the first variable range specified is plotted along the usual "x" axis, while the second range specified is plotted along the usual "y" axis.

The plot above is somewhat crude because the function is not sampled enough times.  We can make the plot smoother by telling Sage to sample the function using a grid of 300 by 300 points.  Sage then samples the function at 90,000 points!

{{{id=74| plot3d(g,(x,-5,5),(y,-5,5),plot_points=300) /// }}}

As with 2D plots, we can superimpose 3D plots by adding them together.

{{{id=148| var('x,y') b = 2.2 P=plot3d(sin(x^2-y^2),(x,-b,b),(y,-b,b), opacity=.7) Q=plot3d(0, (x,-b,b), (y,-b,b), color='red') P+Q /// }}}

We close with a cool plot that we define implicitly as a 3D contour plot.

{{{id=145| var('x,y,z') T = golden_ratio p = 2 - (cos(x + T*y) + cos(x - T*y) + cos(y + T*z) + cos(y - T*z) + cos(z - T*x) + cos(z + T*x)) r = 4.78 implicit_plot3d(p, (x, -r, r), (y, -r, r), (z, -r, r), plot_points=50, color='yellow') /// }}}

The next tutorial will use all that you have learned about Sage basics, symbolics, and plotting in a specific mathematical venue - the calculus sequence!

{{{id=147| /// }}}