*This is one in a series of posts containing short snippets of Sage code for my students to use: see my page on Sage.*

Basic computations can be done by simply entering in the expression you want to evaluate. For example,

2+3/5 - 5/9

If you want to display the result more nicely, you might try

show(2+3/5 - 5/9)

If you want to express the result as a decimal approximation, use

n(2+3/5 - 5/9)

If you want to obtain the LaTeX code for the result, use

latex(2+3/5 - 5/9)

Sometimes you it helps to use the command

simplify( )

**Defining functions**

In order to define functions, we need to have independent variables. Sage recognizes “x” as an independent variable. For other variables, we need to tell Sage that we are using them. For example:

var('t') f(t) = t^2 f(4)

Here’s another example:

var('t','y') f(t,y) = t*t - cos(t*y) f(1,pi)

Notice three things about this previous example: (1) the cosine function is built in, (2) the constant pi is built in, and (3) we need to explicitly tell Sage to multiply — Sage does not interpret juxtaposition as multiplication.

It is also possible to define anonymous functions, though I rarely use this.

g = lambda t: t^2 g(7/3)

**Basic calculus**

Derivatives are rather straightforward:

var('t') p(t) = t^2 q = derivative(p,t) q(t)

Anti-derivatives do not include the arbitrary constant:

var('t') p(t) = t^2 q = integral(p,t) q(t)

In order to compute a definite integral, simply put in the desired interval:

var('t') p(t) = t^2 integral(p(t),(t,2,pi))

If you want a numerical approximation, use the numerical_integral command:

var('t') p(t) = exp(t^2) numerical_integral(p,2,pi)

Notice that the output of the numerical integral has two pieces: the first is the approximate value; the second is an estimate of the error. If you only want the estimate, use this:

var('t') p(t) = exp(t^2) numerical_integral(p,2,pi)[0]