
- •Credits
- •About the Author
- •About the Reviewers
- •www.PacktPub.com
- •Preface
- •Getting started
- •More advanced graphics
- •Summary
- •Start Sage
- •Installing Sage
- •Starting Sage
- •Prerequisites
- •Installation
- •Summary
- •Command history
- •Working with code
- •Arithmetic operators
- •Strings
- •Functions
- •Functions with keyword arguments
- •Objects
- •Summary
- •Python 2 and Python 3
- •Running scripts
- •Strings
- •List comprehensions
- •Storing data in a dictionary
- •Summary
- •Vectors and vector spaces
- •Creating a vector space
- •Vector operators and methods
- •Decomposing matrices
- •Summary
- •Using graphics primitives
- •Summary
- •Substitutions
- •Finding roots
- •Derivatives
- •Integrals
- •Series and summations
- •Summary
- •Computing gradients
- •Constrained optimization
- •Probability
- •Summary
- •Making our tanks move
- •Unit testing
- •Summary
- •Introducing Python decorators
- •Making interactive graphics
- •Summary
- •Index

Getting Started with Sage
Functions
Functions are a way to encapsulate and modularize data processing. Data can be passed to a function using arguments. The function performs some kind of operation, and (optionally) returns a result.
Timeforaction–callingfunctions
We've already seen many simple examples of calling functions. Now, we'll use the plot function to illustrate more advanced ways to call functions. Evaluate the following code:
var('x')
sinc(x) = sin(x) / x
plot(sinc, (x, -10, 10))
The result should look like this:
Now, let's customize our plot:
plot(sinc, x, xmin=-15, xmax=15, thickness=2, color='red', legend_label='sinc')
[ 66 ]

Chapter 3
The customized plot should look like this:
What just happened?
In the first part of the example, we defined a callable symbolic expression that represents the sinc function. This function has important applications in signal processing and information theory. We plotted the function using a simple call to the plot function. When calling a function with multiple arguments, it is important to put the arguments in the right order. The first argument to plot is the callable symbolic expression. The second argument is known as a tuple, which we'll learn about in the next chapter. The tuple contains the independent variable, the minimum value of the plotting domain, and the maximum value of the domain.
In the second part of the example, we used keyword arguments to customize the plot. The arguments we used in previous examples are called positional arguments. Positional arguments are required, and they must occur in the correct order. A keyword argument is optional—if a keyword argument is not specified in the function call, it takes on a default value. If keywords are used, the arguments can be placed in any order. However, keyword
arguments must come after all the positional arguments. In general, a function is called using the syntax:
result = function_name(argument_1, argument_2, … , argument_n, keyword=value)
[ 67 ]

Getting Started with Sage
The number of positional arguments in the function call must match the number in the definition. The function does not have to return a value, and you don't have to assign its return value to a variable. In simple cases, it's possible to pass optional arguments without keywords by passing the optional arguments in the right order. However, this is discouraged, because it makes the code less readable and more prone to bugs.
Sage has very sophisticated plotting capabilities, which we will cover in Chapter 6. If you are interested in learning more now, evaluate the command plot? in a worksheet cell or in the interactive shell to get help on the plot function.
Haveagohero–makesomemoreplots
Use the plot command to make plots of some of the built-in mathematical functions listed in the next section. Practice using keyword arguments to customize the plots. Then, use the built-in functions to define a callable symbolic expression, and plot it.
Built-infunctions
A vast number of functions are pre-defined in Sage. Even more are available through Python modules, which we will learn about in the next chapter. For now, here is a brief summary of the most commonly used mathematical functions, and how to access them in Sage:
Function |
Sage |
Function |
Sage |
sine |
sin(x) |
square root |
sqrt(x) |
cosine |
cos(x) |
ex |
exp(x) |
tangent |
tan(x) |
natural logarithm |
log(x) |
arcsine |
arcsin(x) |
absolute value |
abs(x) |
arccosine |
arccos(x) |
complex conjugate |
conjugate(x) |
arctangent |
arctan(x) |
|
|
Numericalapproximations
Any numerical type in Sage can be converted to a real number with the numerical_approx function (this function can also be abbreviated as n or N). For example:
print(pi) print(numerical_approx(pi)) print(type(numerical_approx(pi))) print(numerical_approx(pi, prec=16)) print(numerical_approx(pi, digits=5))
[ 68 ]

Chapter 3
The result should look like this:
The numerical_approx function accepts three arguments. The first argument, which is mandatory, is the item to be converted to a real number. The keyword argument prec can be used to specify the number of bits of precision for the real number. Alternately, the keyword argument digits can be used to specify the number of digits of precision.
Theresetandrestorefunctions
It's possible to accidentally re-define a built-in function or constant. For example, the letters i and n are commonly used as names for counting variables in loops. Fortunately, the restore function can be used to restore predefined global variables (such as i and n) to their default values. Here's a short example:
print(e + i * 5)
i = 10 e = 5
print(e + i * 5)
restore('e i') print(e + i * 5)
The result should look like this:
If you call restore without any arguments, it will restore all the predefined variables to their default values. Another useful function is called reset. This function deletes all the variables you have defined, restores all global variables to their default values, and resets the interfaces to other computer algebra systems.
[ 69 ]

Getting Started with Sage
If you start getting strange results from your calculations, you may have accidentally re-defined a built-in function or constant. Try calling the reset() function and running the calculation again. Remember that reset will delete any variables or functions that you may have defined, so your calculation will have to start over from the beginning.
Definingyourownfunctions
Sage allows you to define your own functions using Python syntax. This will be very useful for keeping your code organized, especially as we move into writing longer programs.
Timeforaction–definingandusingyourownfunctions
Let's return to the series RC circuit that we have been using as an example. We will now define a function that computes the voltage across the capacitor. You can enter the following code in an input cell in a worksheet, or on the command line. When you type the colon at the end of the first line and press Enter, the cursor will automatically indent the lines that follow. Make sure that you consistently indent each line inside the function.
def |
RC_voltage(v0, R, C, t): |
||
|
""" |
|
|
|
Calculate |
the voltage at time t for an R-C circuit |
|
|
with initial voltage v0. |
||
|
""" |
|
|
|
tau = R * |
C |
|
|
return v0 |
* exp(-t / tau) |
|
R = |
250e3 |
# |
Ohms |
C = |
4e-6 |
# |
Farads |
v0 = 100.0 |
|
# Volts |
|
t = |
1.0 |
|
# seconds |
v = |
RC_voltage(v0, R, C, t) |
print('Voltage at t=' + str(n(t, digits=4)) + 's is ' + str(n(v, digits=4)) + 'V')
This block of code produces the following output:
Voltage at t=1.000s is 36.79V
[ 70 ]

Chapter 3
If you are using the interactive shell, pressing Enter after the first line will create a blank line so that you can enter the next line of the function, instead of executing the code. To return to the command prompt, press Enter on a blank line. Defining a function on the command line looks like this:
sage: def RC_voltage(v0, R, C, t,):
....: """
....: Calculate the voltage at time t for a series R-C circuit
....: with initial voltage v0.
....: """
....: tau = R * C
....: return v0 * exp(-t / tau)
....:
Our function even has documentation like a built-in function. Executing the following command displays the documentation:
RC_voltage?
Having trouble getting the code running?
Python, like most programming languages, is very picky about how you type in the code. This is often frustrating for new programmers, but you'll quickly get used to it. Go over what you typed in and look for these common mistakes.
Did you forget the colon after the parenthesis when defining the function? Did you uniformly indent each line within the function? Did you use three double quotes on each end of the documentation string? Also, pay attention to the error messages that are produced, particularly the last one.
What just happened?
We defined a function and found that it can be used just like the built-in functions in Sage. Sage functions are defined using the general form:
def function_name(argument_1, argument_2, … , argument_n):
"""
Documentation string here
"""
statement one statement two
...
return some_value
[ 71 ]