Sage Tutorial for Calculus

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.  Just for a refresher, make sure the syntax below for defining a function and getting a value makes sense; then evaluate the cell by clicking the "evaluate" link, or by pressing Shift-Enter (hold down Shift while pressing the Enter key).  We'll use this function several times in this tutorial, so it's important that it is evaluated!

{{{id=134| f(x)=x^3+1 f(2) /// 9 }}}

Calculus 1

The calculus is amazing not so much because it solves problems of tangency or area - individual solutions to these problems have been known before.  It is amazing because it gives a remarkably comprehensive set of rules for symbolic manipulation for solving such problems in great generality!

The most typical use of a computer system like Sage in this context is thus simply to help check (or make less tedious) basic symbolic manipulation of things like derivatives.  Let's first show what our function $f$ is again, then do things with it.

{{{id=91| show(f) ///
\newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ x^{3} + 1
}}}

Something most (but not all) curricula for first-semester calculus do is spend a fair amount of time with limits.  What is the limit of this function as $x$ approaches $1$?  

{{{id=138| lim(f,x=1) /// 2 }}}

The syntax for limits is pretty straightforward, though may differ slightly from that of other systems, so be sure to notice that Sage uses $x=1$ to show the input value approached, even though the function may not actually be defined at $x=1$.

{{{id=159| lim((x^2-1)/(x-1),x=1) /// 2 }}}

Getting back to the original function, let's also check the two directional limits, and compare them with $f(1)$ to ensure that $f(x)$ is continuous at $x=1$.  Notice that by separating several commands with semicolons, we can tell Sage to evaluate all of them while still seeing all their outputs.

{{{id=140| lim(f,x=1,dir='below'); lim(f,x=1,dir='above'); f(1) /// 2 2 2 }}}

Naturally, what we spend the most time on in Calculus 1 is derivatives, and Sage is fully-featured here.  For example, here are three ways to get the basic, single-variable derivative of $f(x)=x^3+1$. 

{{{id=111| diff(f,x); derivative(f,x); f.derivative(x) /// x |--> 3*x^2 x |--> 3*x^2 x |--> 3*x^2 }}}

Let's review the plotting from the previous tutorial.  Before looking below to recall how to do it, try to plot this function, together with its tangent line at $x=1$, in the empty cells below.

{{{id=151| /// }}} {{{id=152| /// }}}

Did you get it?  

Of course, in general we want to see tangent lines at lots of different points.  In the following cell, there are several auxiliary elements:

Finally, we plot everything together in the last line, and that is what appears.

{{{id=149| P=plot(f,(x,-1,1)) c=1/3 fprime=derivative(f,x) L(x)=fprime(c)*(x-c)+f(c) Q=plot(L,(x,-1,1), color="red", linestyle="--") P+Q /// }}}

You may want to experiment changing $c$ to some other value, or  changing the function $f$, or changing the colors, or something else.

However, it would be nice to make this changing of the parameter easier.  In the cell below, we show our second example of an "interact", where dragging a slider will show the tangent line moving.  Toward the end of the summer, you will learn how to create such interactive things from scratch.  

Notice also that we have put "%auto" in the very first line; that line tells this cell to load up immediately upon your opening the worksheet, which can be very useful.  You may need to click on or move the slider briefly to get it started up again, but you should not need to evaluate the cell.

{{{id=154| %auto f(x)=x^3+1 @interact def _(c=(1/3,(-1,1))): P=plot(f,(x,-1,1)) fprime=derivative(f,x) L(x)=fprime(c)*(x-c)+f(c) Q=plot(L,(x,-1,1),color="red", linestyle="--") show(P+Q+point((c,f(c)), pointsize=40, color='red'),ymin=0,ymax=2) ///
}}}

Sage knows all of the derivatives you want.

{{{id=114| derivative(sinh(x^2+sqrt(x-1)),x) /// 1/2*(4*x + 1/sqrt(x - 1))*cosh(sqrt(x - 1) + x^2) }}}

And maybe even those you don't want.  Here, we use "show()" again since the output is so long.  Also note that Sage does not check automatically if there is some "simpler" version, since this problem is in general undecidable.

{{{id=120| show(derivative(sinh(x^2+sqrt(x-1)),x,3)) ///
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{8} \, {\left(4 \, x + \frac{1}{\sqrt{x - 1}}\right)}^{3} \cosh\left(\sqrt{x - 1} + x^{2}\right) - \frac{3}{8} \, {\left(\frac{1}{{\left(x - 1\right)}^{\left(\frac{3}{2}\right)}} - 8\right)} {\left(4 \, x + \frac{1}{\sqrt{x - 1}}\right)} \sinh\left(\sqrt{x - 1} + x^{2}\right) + \frac{3 \, \cosh\left(\sqrt{x - 1} + x^{2}\right)}{8 \, {\left(x - 1\right)}^{\left(\frac{5}{2}\right)}}
}}}

And of course, usually in Calculus 1 we do begin integration.  The syntax for indefinite integration is similar to that for differentiation.

{{{id=141| integral(cos(x),x) /// sin(x) }}}

We don't get the whole indefinite integral, just a convenient antiderivative.  Definite integration has similar syntax to plotting.

{{{id=143| integral(cos(x),(x,0,pi/2)) /// 1 }}}

Calculus 2

Second-semester calculus is typically more challenging.  One reason for that is that the computational problems are not so straightforward as computing derivatives and basic integrals.

Nonetheless, Sage can handle a large number of indefinite integrals (via Maxima), though not all the ones you will find in a comprehensive table.

{{{id=115| h(x)=sec(x); h.integrate(x) /// x |--> log(tan(x) + sec(x)) }}} {{{id=145| integrate(1/(1+x^5),x) /// 1/5*(sqrt(5) - 1)*sqrt(5)*arctan((4*x - sqrt(5) - 1)/sqrt(-2*sqrt(5) + 10))/sqrt(-2*sqrt(5) + 10) + 1/5*(sqrt(5) + 1)*sqrt(5)*arctan((4*x + sqrt(5) - 1)/sqrt(2*sqrt(5) + 10))/sqrt(2*sqrt(5) + 10) - 1/10*(sqrt(5) - 3)*log((sqrt(5) - 1)*x + 2*x^2 + 2)/(sqrt(5) - 1) - 1/10*(sqrt(5) + 3)*log(-(sqrt(5) + 1)*x + 2*x^2 + 2)/(sqrt(5) + 1) + 1/5*log(x + 1) }}}

Some are a little tricky, in which case Sage returns as much of it as it (more properly, as Maxima) could do.

{{{id=146| integral(1/(1+x^10),x) /// 1/5*arctan(x) - 1/5*integrate((x^6 - 2*x^4 + 3*x^2 - 4)/(x^8 - x^6 + x^4 - x^2 + 1), x) }}} {{{id=116| integral(sinh(x^2+sqrt(x-1)),x) /// integrate(sinh(sqrt(x - 1) + x^2), x) }}}

This last one stumps other systems too.

However, if there is a special function which helps compute the integral, Sage will look for it. In this case there is no elementary antiderivative, but the "erf" function will help out.

{{{id=117| integral(e^(-x^2),x) /// 1/2*sqrt(pi)*erf(x) }}}

Don't forget, if you have momentarily forgotten this function, Sage's contextual help system comes to the rescue.

{{{id=147| erf? ///

File: /usr/local/sage-prep/local/lib/python2.6/site-packages/sage/functions/other.py

Type: <class ‘sage.functions.other.Function_erf’>

Definition: erf(*args, coerce=True, hold=False)

Docstring:

The error function, defined as erf(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} dt.

Sage currently only implements the error function (via a call to PARI) when the input is real.

EXAMPLES:

sage: erf(2)
erf(2)
sage: erf(2).n()
0.995322265018953
sage: loads(dumps(erf))
erf

The following fails because we haven’t implemented erf yet for complex values:

sage: complex(erf(3*I))
...
TypeError: unable to simplify to complex approximation

TESTS:

Check if conversion from maxima elements work:

sage: merf = maxima(erf(x)).sage().operator()
sage: merf == erf
True
}}}

There are several ways to do definite integrals in Sage.  Most obvious is simply turning $\int f(x)dx$ into $\int_a^b f(x)dx$, as indicated in the Calculus I section.  The preferred syntax puts the variable and endpoints together in parentheses.

{{{id=123| integral(cos(x),(x,0,pi/2)) /// 1 }}}

We can also visualize this integral using some of the plotting options from the plotting tutorial.

{{{id=155| plot(cos(x),(x,0,pi/2),fill=True) /// }}}

It is possible to be completely symbolic in doing integration.

{{{id=124| var('a,b') integral(cos(x),(x,a,b)) /// -sin(a) + sin(b) }}}

On the numerical side, sometimes the answer one gets from the Fundamental Theorem of Calculus is not entirely helpful.  Recall that $h$ is the secant function.

{{{id=125| h(x); integral(h,(x,0,pi/8)) /// sec(x) x |--> -1/2*log(-sin(1/8*pi) + 1) + 1/2*log(sin(1/8*pi) + 1) }}}

Here, just a number might be more helpful.  Sage has several ways of numerical evaluating integrals.

The first one, using the n or N function for numerical approximation, was also mentioned in the introductory tutorial.

{{{id=127| N(integral(h,(x,0,pi/8))) /// 0.403199719161512 }}}

The second function, "numerical_integral", uses a powerful numerical program (the GNU Scientific Library).  Unfortunately, the syntax for this function is not  yet consistent with the rest of Sage.  The output has two elements - the answer you desire, and its error tolerance.  

{{{id=112| numerical_integral(h,0,pi/8) /// (0.40319971916151143, 4.4764161173550687e-15) }}}

Finally, the ".nintegrate()" method from Maxima gives even more extra information.  Notice again the period/dot needed to use this, and that it is only possible to use "h(x)"; doing "h.nintegrate()" raises an error.

{{{id=129| h(x).nintegrate(x,0,pi/8) /// (0.40319971916151143, 4.4764161173550703e-15, 21, 0) }}}

Second-semester calculus usually also covers various topics in summation.  Sage can sum many abstract series.

{{{id=160| var('n') # Don't forget to declare your variables sum((1/3)^n,n,0,oo) /// 3/2 }}} {{{id=162| var('k') # We already declared n, so now we just need k sum(binomial(n,k), k, 0, n) /// 2^n }}}

And Sage also can compute Taylor polynomials.  Whenever there are several inputs, keeping syntax straight is important.  Here we have as inputs:

In the next cell, we call $g(x)$ the Taylor polynomial in question.

{{{id=164| g(x)=taylor(log(x),x,1,6); g(x) /// -1/6*(x - 1)^6 + 1/5*(x - 1)^5 - 1/4*(x - 1)^4 + 1/3*(x - 1)^3 - 1/2*(x - 1)^2 + x - 1 }}}

Notice how close the approximation is to the function on this interval!

{{{id=166| plot(g,(x,0,2))+plot(log(x),(x,0,2),color='red') /// }}}

Calculus 3

We have already seen three-dimensional plotting, so it is not surprising that Sage has support for a variety of multivariable calculus problems.  Remember, we will usually need to define all variables other than $x$!  

{{{id=130| var('y') f(x,y)=3*sin(x)-2*cos(y)-x*y /// }}}

Above, we have defined a typical function of two variables.  Below, we use the separating semicolons to demonstrate several things one might do with such a function, including a double partial derivative of $f$ with respect to $x$, then $y$.  

{{{id=132| f.gradient(); f.hessian(); f.diff(x,y) /// ((x, y) |--> -y + 3*cos(x), (x, y) |--> -x + 2*sin(y)) [(x, y) |--> -3*sin(x) (x, y) |--> -1] [ (x, y) |--> -1 (x, y) |--> 2*cos(y)] (x, y) |--> -1 }}}

In an effort to make the syntax simpler, the gradient and Hessian are also available by asking for a total derivative.  The last thing is, of course, the Jacobian of the function!  This is a good place to remind that it's possible to ask for nicer typesetting for complicated output.

{{{id=168| show(f.diff()); show(f.diff(2)); show(f.diff(2).det()) ///
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\left( x, y \right) \ {\mapsto} \ -y + 3 \, \cos\left(x\right),\left( x, y \right) \ {\mapsto} \ -x + 2 \, \sin\left(y\right)\right)
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rr} \left( x, y \right) \ {\mapsto} \ -3 \, \sin\left(x\right) & \left( x, y \right) \ {\mapsto} \ -1 \\ \left( x, y \right) \ {\mapsto} \ -1 & \left( x, y \right) \ {\mapsto} \ 2 \, \cos\left(y\right) \end{array}\right)
\newcommand{\Bold}[1]{\mathbf{#1}}\left( x, y \right) \ {\mapsto} \ -6 \, \sin\left(x\right) \cos\left(y\right) - 1
}}}

This is particularly helpful if one wants to plot a vector field (this example is of the gradient).  The vector plotted is the unit vector in the direction $(1,2)$.

{{{id=170| P=plot_vector_field(f.diff(), (x,-3,3), (y,-3,3)) u=vector([1,2]) Q=plot(u/u.norm()) P+Q /// }}}

The directional derivative itself (in that direction, at the origin) could be computed in this way.

{{{id=173| (f.diff()*u/u.norm())(0,0) /// 3/5*sqrt(5) }}}

We can do contour plotting as well.  This is highly customizable, thanks to the matplotlib Python package, and we have used several of its options in the following plot.  Notice that we must explicitly ask for $y$ to be a variable here; this will come up a few more times.

{{{id=148| var('y') contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), contours=[-8,-4,0,4,8], colorbar=True, labels=True, label_colors='red') /// }}}

As you gain experience in Sage, we will slowly explain less and less of the syntax of commands in these tutorials, as in the last few cells.  However, for the next example, a multiple integral, we won't do that! Notice that "integrate(f,(x,0,pi))" has been itself placed as the function inside "integrate(...,(y,0,pi))".

{{{id=158| integrate(integrate(f,(x,0,pi)),(y,0,pi)) /// (x, y) |--> 6*pi - 1/4*pi^4 }}}

And a 3D plot could help visualize this (see our previous worksheet).

{{{id=175| plot3d(f,(x,0,pi),(y,0,pi),color='red')+plot3d(0,(x,0,pi),(y,0,pi)) /// }}}

In addition to multivariate calculus, Calculus 3 often covers parametric calculus of a single variable.  Sage can do arbitrary parametric plots, with fairly natural syntax.  This plot shows the tangent line to this Lissajous curve at $t=1$; the commands should be strongly reminiscent of the ones at the beginning of this tutorial.  

{{{id=59| var('t') my_curve(t)=(sin(t), sin(2*t)) PP=parametric_plot( my_curve, (t, 0, 2*pi), color="purple" ) my_prime=my_curve.diff(t) L=my_prime(1)*t+my_curve(1) # tangent line at t=1 parametric_plot(L, (t,-2,2))+PP /// }}}

Two comments:

'Exam'

Before moving out of the calculus world, it is good to have a sort of miniature exam.  Here we have a cell which plots a slope field for a differential equation as well as a solution, whose symbolic formula is given before the plot.  

Here we are assuming you have never seen several of these commands before.  Can you nonetheless figure out which commands are doing each piece, and what their syntax is?  How would you look for help to find out more?

{{{id=92| y = var('y') Plot1=plot_slope_field(2-y,(x,0,3),(y,0,20)) y = function('y',x) # declare y to be a function of x h = desolve(diff(y,x) + y - 2, y, ics=[0,7]) Plot2=plot(h,0,3) show(expand(h)); show(Plot1+Plot2) ///
\newcommand{\Bold}[1]{\mathbf{#1}}5 \, e^{\left(-x\right)} + 2
}}}

We've done the following:

As you gain experience, you will see how to glean what you are looking for from examples in the documentation like this - which is one of the real goals of the workshop.

Congratulations!  You are now armed with the basics of deploying Sage in the calculus sequence.  We hope you will also look at one or two of the other tutorials geared toward different interests of the participants of the workshop. Some of the topics may include:

Thank you and good luck!

{{{id=133| /// }}}