Sage: Basics – computation, functions, calculus 1

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:

f(t) = t^2

Here’s another example:

f(t,y) = t*t - cos(t*y)

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

Basic calculus

Derivatives are rather straightforward:

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

Anti-derivatives do not include the arbitrary constant:

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

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

p(t) = t^2

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

p(t) = exp(t^2)

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:

p(t) = exp(t^2)
This entry was posted in Sage. Bookmark the permalink.

Leave a comment here

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s