Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Chapter 1 - An introduction in SageMath
A course in script languages
Introduction
This is an introductory course on computing and programming with SageMath, designed primarily for students in mathematics, informatics, and engineering, though it is also suitable for those from other disciplines such as physics, biology, and economics.
The course assumes no prior programming experience and is tailored to students with limited exposure to programming. However, we have also included topics to help more experienced programmers enhance their skills, particularly in SageMath.
We hope this material will also be useful for teachers and instructors covering similar subjects.
It's important to note that this course (and the descriptions below) does not aim to cover the mathematical theories related to the tasks and applications discussed. All relevant mathematical topics are thoroughly explained in the primary reference, the BG book, especially in the first seven chapters.
Broadly speaking, these chapters cover topics from linear algebra and its applications, complex numbers, analytic geometry, basic probability, combinatorics, and foundational concepts in calculus and analysis (mainly concerning single-variable functions), such as functions, series, limits, derivatives, integrals, Taylor series, Fourier series, numerical methods, and other.
While we do not provide formal mathematical proofs, we focus on implementing ideas using the aforementioned programming package. However, in some cases, we include the relevant mathematical details for the reader's convenience.
Use of Sage
Sage is a free, open-source software for mathematics and informatics.
It is built on Python, which serves as its foundational language—a point that will become clearer as we progress.
One key advantage of Sage is its accessibility: anyone can easily access it via the official website: .
Note: Throughout this course, we will use the terms "Sage" and "SageMath" interchangeably. We hope this does not cause confusion.
Let's start with a few practical details about Sage itself. We encourage the readers to follow the links provided for further instructions.
Sage Cells
You can access and use SageMath through a free online editor via any web browser:
In this way you do not need to have the latest version of SageMath installed on our computer.
However, online editors have some limitations.
Another way to use SageMath is to install it on your own computer.
Then you do not need an Internet connection and you can also save your own work.
CoCalc
Another flavor of Sage Math is using CoCalc, where one should create first an account in CoCalc.com.
In this case there is no longer the need to install and maintain SageMath in your machine.
The same time using the editors that CoCalc offers (Sage Worksheet, Jupiter Notebook, Latex document, etc), one can create projects, save them, and return for editing at any time.
For instance, this document is written in the editors that CoCalc offers.
Chapter 1 - An introduction in SageMath
1.1. Preliminaries (Sage as a Calculator )
1.2. Division of integers and prime numbers via Sage
1.3. Some standard functions in Sage
1.4. Python variables in Sage and other technicalities
1.5. Symbolic variables in Sage
1.6. Applications of symbolic variables
1.7. Booleans
1.8. Subsets of real numbers
1.9. Complex numbers
1.10. Functions in Sage
1.11. Preliminaries on programming with Sage
The first chapter serves as an introduction and warmly welcomes you to SageMath.
We'll explore commands for basic computations, working with numbers, and handling functions. Our goal is to give you a first glimpse of how SageMath handles mathematical expressions and performs essential mathematical tasks.
1.1. Preliminaries (Sage as a Calculator)
With a few minor exceptions, SageMath is based on the Python programming language, meaning it uses Python-like syntax. Therefore, users familiar with Python will quickly adapt to SageMath’s tasks. This also means that much of the introductory material on Python can be useful when learning or teaching SageMath.
However, SageMath’s syntax extends beyond Python’s. For instance, while Python uses for exponentiation, SageMath accepts both and and ^. We’ll encounter more examples like this as we go along.
Like Python, SageMath uses = for assignment and ==, <=, >=, <, > for comparisons. These operators work in SageMath just as they do in Python.
Additionally, common operations such as addition, abstraction, multiplication and division (corresponding to +, -, *, /, respectively), work as expected. The same applies for the use of parentheses. More details on these will follow.
Rings and fields of numbers (universes)
Before moving on the description of the main material and explain how Sage can be used to study mathematical tasks or mathematical structures, we discuss some basic syntax.
This appears in many different Sage tasks, and it is easy to master with it.
In particular, we begin with details about numbers, as integers, rationals, etc.
So, let us type the following:
Therefore, represents the ring of integers, is the field of rational numbers, is the field of real numbers and is the field of complex numbers.
To check if a given number is an integer, rational, real or complex, we can proceed as described in the following examples.
The imaginary number i satisfies .
In sage we may denote the imaginary number i also by capital I.
We see that in Sage, everything that follows the character # is a comment and Sage ignores it. This feature comes from Python.
Comments are very useful, and we'll frequently rely on them—especially in longer Sage cells or when we want to explain something directly within the code. We highly recommend using comments, particularly when sharing your code with others, as they make your work clearer and easier to understand.
The parent function
Another way to check the field, is based on the command function. For instance we may type
One can also determine the bits of precision (see also below)
For instance, with this precision Sage computes
There is the option of fixing the precision with more bits, e.g.,
Sage as a Calculator
Obviously, Sage can be used as a calculator and so basic arithmetics can be done very easily.
Later we will see that Sage can be used also as a .
Let us describe some easy examples.
Note that one could use paranethesis to get the same result
This means that the use of parenthesis in Sage is the usual one.
For example, observe the difference between the following two expressions:
Useful technicalities in Sage to remember
In SageMath it is common to use the command to display intermediate steps. For example:
While Sage will always print the output of the last line, printing any other output requires a print command.
Let us illustrate this situation by an example:
while we can type:
Note that the values "-", ", "--", "---" (using one, two, and three underscores) are the last three output values.
For instance, type
Or type:
and then
In SageMath the command supports a Latex-like pretty output. Let us compare two expressions:
Or as another example, type
Square roots, n-th roots & floating point functions
In the previous commands, we met a first example of a function in SageMath, namely the square-root function .
When the positive integer given inside the function is a perfect square, i.e., for some integer , then typing the command Sage will return the integer .
However, when is not a perfect square the following cases may appear:
In many cases we may need to know a decimal presentation of certain expressions, as .
In Sage, to arrive to a decimal number (or floating point number) there are many alternatives. For example, we may proceed as below:
To arrive to a decimal numbe presentations we can also type:
or
As another example, consider the case
However, as we saw above, we may also type:
Summary:
Both the commands and return the inserted number in a floating point format.
Thus, the functions or , they both try to convert what is inside the parentheses to a real number.
These functions come with options, e.g., we can specify the number of digits that we want to contain a floating point number.
Finally, another alternative to get a decimal approximation of a given number goes as follows:
Of course, one gets the same result via the code
We mention that one can type , where inside the parentheses we specify by a positive integer how many of precission we want. For example:
Note that the default bits are 53 bits of precision. For example, for the irrational number we get
Another classical example:
As another typical example, let us use the number , i.e., the base of the natural logarithm.
Let us also mention that for the th root of a number we type . For example:
Or we can type , that is
However, notice that
In this case to get an answer we can type
In some cases we may need to find how many digits has a number, and the command is appropriate for this. Also we may need to count hom many times a certain digit appears isnside a given number. Let us describe an example:
Example
Compute the digits of the number . Then count how many times appears the digit in the expression of .
Solution:
Thus consists of 61 digits. For the second task we type:
Thus Sage counts twelve times the digit 2 in the expression of p.
1.2. Division of integers and prime numbers via Sage
Above we saw that when dividing two integers a subtlety may appear: SageMath will return either a fraction or its decimal approximation.
Let us describe such an example:
In general, SageMath will attempt to be as precise as possible and will return the fraction unless told otherwise.
As we saw above, one way to tell to SageMath that we want the decimal approximation, is to include a decimal in the expression itself.
Otherwise we can use some of the functions or , introduced above.
Now, during the procedure of division of integers in many cases we may need to know the integer quotient and also the remainder of the division.
To calculate the quotient we use the // operator. On the other hand, the % operator is used for the remainder.
We can take both the quotient and the remainder, all at once, via the command . For instance
In Sage there is also a built-in command available to check whether one integer divides another. This goes as follows:
We can also find all positive divisors of a fixed integer. We can do this via the command :
Hence from the above we conclude for example that between the numbers 14, 16, and 5 only 5 is a prime number.
To check if an integer is prime, we can also use the command .
Finally, let us mention the syntax which is about the prime factorization of an integer.
In case we need to locate the prime numbers dividing an integer, SageMaths provides the command .
Another available command is .
There is also the command which returns the largest between the common divisors of two given integers.
Exercise
Compute a decimal approximation of with five digits.
Compute a decimal approximation of with seven bits of precision.
Compute the integer quotient of 25 by 4, and find the remainder.
Is the number 163 prime?
Provide the prime factorization of the integers 120, 121, 1020 and 1021.
Find the prime divisors of the integers 165 and 169.
Find the greatest common divisor for the integers (18, 76).
Solution:
1.3. Some standard functions in Sage
SageMath becomes very attractive and useful since it includes most of the standard functions that we encounter studying basic mathematical structures.
Above we already met the square-root function .
Below we will refresh some other very commonly used functions, as the absolute value, the maximum, minimum, floor, ceiling, trigonometric, exponential, and logarithm functions.
A summary of standard functions in Sage
The function returns the absolute value of a real number.
The and functions return the largest and smallest of a set of numbers.
The function rounds a number down to the nearest integer, while the function rounds up (see also below).
The trigonometric functions , , . These functions, during evaluation, have the same behavior as .
The inverse trigonometric functions are built-in, for instance the inverse of corresponds to .
Most of the hyperbolic functions are also built-in, as .
In SageMath exponentiation base , can be done using the function (or simply by using e and raising to the appropriate power).
In SageMath for the logarithm (the inverse function to exponentiation) we can use the functions or , which both represent the logarithm in base .
We may also specify a different base as a second argument to the command. Therefore, to compute in SageMath, use the command .
Exercise
Compute in SageMath the following:
The absolute value (length) of the complex number (see below for complex numbers)
The absolute value of .
The value of as a fraction.
The values , .
The value with accuracy of 10 digits.
Construct further examples yourself.
Solution:
We will return on functions and how we can treat them in Sage a few below.
Tip:
To access the help page for a function in SageMath, type the name of the function and then add a question mark.
After running such a command, a new window area will open where are given the details for the corresponding function.
Finally, using two question marks will show the source code of the function under question.
For instance, ask yourself Sage for the cos function.
1.4. Python variables in Sage and other technicalities
In SageMath variables are defined using the "=" operator.
Often, such variables are called , and should be distinguished from the in Sage, that we will introduce below.
Note that some operations (such as variable assignment) do not have an output and we add another line to print the value of our variable.
For instance:
In this way we have assigned a value to the variable , namely the value .
Thus is a Python variable, which we can use to implement further operations:
Another example: We introduce a python variable that we call ``example''
We can now combine both Python variable, ``mul'' and ''example'' introduced above to construct a new variable:
As another example, entering means that will be assigned the value :
If we then evaluate for example the expression , Sage will return 15:
Or type
Or you can combine both the variables and :
Tip
To restore all predefined variables and functions instead, the command is the appropriate one.
When, in addition, all user-defined Python variables should be deleted, we type .
Try some examples yourselves.
On the other hand, a double-equal sign (==) is a test of equality between two expressions.
Since we previously set , then evaluating returns , whereas evaluating return :
Note that variables can be useful for many reasons, and especially in computations. E.g.:
Remark
We mention that in SageMath mathematical objects and variables can be inserted in print commands using commas, or using carefully empty curly braces {} and .
Let us present an example:
Consider the function
Now, as we said, SageMath is essentially built on Python, and hence uses much of the same syntax.
Hence, for example, indentation is extremely important.
To understand better what we mean, the description of an example is helpful:
We will meet further examples how to use the statements , and in the final section of this introductory chapter.
Tip
Useful to know that an statement can be written in one line, as follows:
1.5. Symbolic variables in Sage
In Sage you can declare your own variables, no matter what the application is.
These ``Sage variables'' are often called .
Roughly speaking the symbolic variables play the role of “” that we often use in mathematical solving.
There are several ways to establish or introduce a symbolic variable in Sage, as we will see below via examples.
or
In both cases Sage returns a symbolic variable named . Or you can simply type .
A variable can also given by , or , or , etc.
Moreover, one can introduce many variables together in a row:
Sage now treats the expression x+y+z as a function on the variables x, y, z. For instance
Remark
As we will explain also below, SageMath realizes as a symbolic variable, which is not the case for other variables.
Hence working only with the symbolic variable , it is general unnecessary to declare it as a symbilic variable (especially in https://sagecell.sagemath.org).
Often, dealing with mathematical expressions we need to be sure that our symbolic variables live in the right domain.
For that, we can use the command (or we can make Sage to ``forgot'' assumptions, via the command ). For instance:
Another example of this type:
We can also create symbolic variables by using the syntax
This returns the symbolic variables for for some positive integer . For example:
In the previous result we may fix the parameters to obtain a polynomial of degree three.
For such substitutions one may use the command , in a cell as follows:
If we want to plot the resulting polynomial we may type
We will discuss more details on 2D-ploting in SageMath in Chapter 2.
Now, let us mention that using the function we can take the coefficients of any term in a given polynomials.
For instance the following cell returns the coefficient of in the previous expression:
1.6. Applications of symbolic variables
Let us present now some very basic applications of , in terms of exercises.
We will treat equations (and in particular polynomial equations) and also plots (graphs) of functions, although these topics will be analyzed in more details in Chapter 2.
Exercise
Let be three real numbers. Assuming that , solve the equations , and with respect to .
Solution:
Notice that the command returns a list of solutions. Sage uses brackets to indicate a list.
In our case, there is only one solution so the list contains only one element.
We will learn more on lists in Sage a few below.
For the second equation, type the following:
Remark
To get the 2nd entry of the list presented by Sage in the previous example, there are many methods. One of them goes as follows:
Notice here that Sage, as Python, starts all lists (and array) indices with element zero. Hence the second element of our list corresponds to 1.
Lists are important in Sage, and hence below we will analyze more their implementation, by further applications.
Notice that above we used the command to assume that .
Keep in mind that this command applies to many cases and we will meet it again.
Finally, you may want to plot a polynomial of degree two to arrive to a certain parabola.
Let us present an example (with discriminant , and thus a double root).
Exercise for practice
Indicate in the previous plot the point on induced by the double root of the equation .
Hint: in case you find difficulties see the first section in Chapter 2.
Exercise
Let positive real numbers. Show that where .
Solution:
Of course the statement is obvious. We pose this task to improve our understanding on the use of symbolic variables, and also of the command .
Exercise
Present the graph of the function with .
Solution:
Note that we dont need to setup as a symbolic variable, although we want to treat a function of and find its plot. Indeed, we may just type:
However, one will arrive to the same figure, if instead use the following Sage cell:
This simple example verifies that SageMath understands automatically as a symbolic variable.
In other words, Sage initializes the Symbolic Ring to have one symbolic variable, namely , and this obeys the arithmetical rules that one may expect.
However, note that this is not the case for other variables as , etc.
For instance running the command we will get an error (make the experiment in your editor).
We will analyze further the importance of symbolic variable in Sage in the sequel.
Although we will meet more details on polynomials in Chapter 2, let us list some commands useful when treating such kind of functions.
Try yourself to explore them, and realize their implementation by making some tests.
, , , .
Signature: floor(x, **kwds)
Type: Function_floor
String form: floor
File: /ext/sage/9.7/src/sage/functions/other.py
Docstring:
The floor function.
The floor of x is computed in the following manner.
1. The "x.floor()" method is called and returned if it is there. If
it is not, then Sage checks if x is one of Python's native
numeric data types. If so, then it calls and returns
"Integer(math.floor(x))".
2. Sage tries to convert x into a "RealIntervalField" with 53 bits
of precision. Next, the floors of the endpoints are computed. If
they are the same, then that value is returned. Otherwise, the
precision of the "RealIntervalField" is increased until they do
match up or it reaches "bits" of precision.
3. If none of the above work, Sage returns a symbolic "Expression"
object.
EXAMPLES:
sage: floor(5.4)
5
sage: type(floor(5.4))
<class 'sage.rings.integer.Integer'>
sage: var('x')
x
sage: a = floor(5.4 + x); a
floor(x + 5.40000000000000)
sage: a.simplify()
floor(x + 0.4000000000000004) + 5
sage: a(x=2)
7
sage: floor(cos(8) / cos(2))
0
sage: floor(log(4) / log(2))
2
sage: a = floor(5.4 + x); a
floor(x + 5.40000000000000)
sage: a.subs(x==2)
7
sage: floor(log(2^(3/2)) / log(2) + 1/2)
2
sage: floor(log(2^(-3/2)) / log(2) + 1/2)
-1
sage: floor(factorial(50)/exp(1))
11188719610782480504630258070757734324011354208865721592720336800
sage: floor(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000000
sage: floor(SR(10^50 - 10^(-50)))
99999999999999999999999999999999999999999999999999
sage: floor(int(10^50))
100000000000000000000000000000000000000000000000000
Small numbers which are extremely close to an integer are hard to
deal with:
sage: floor((33^100 + 1)^(1/100))
Traceback (most recent call last):
...
ValueError: cannot compute floor(...) using 256 bits of precision
This can be fixed by giving a sufficiently large "bits" argument:
sage: floor((33^100 + 1)^(1/100), bits=500)
Traceback (most recent call last):
...
ValueError: cannot compute floor(...) using 512 bits of precision
sage: floor((33^100 + 1)^(1/100), bits=1000)
33
sage: import numpy
sage: a = numpy.linspace(0,2,6)
sage: floor(a)
array([0., 0., 0., 1., 1., 2.])
sage: floor(x)._sympy_()
floor(x)
Test pickling:
sage: loads(dumps(floor))
floor
Init docstring:
The floor function.
The floor of x is computed in the following manner.
1. The "x.floor()" method is called and returned if it is there. If
it is not, then Sage checks if x is one of Python's native
numeric data types. If so, then it calls and returns
"Integer(math.floor(x))".
2. Sage tries to convert x into a "RealIntervalField" with 53 bits
of precision. Next, the floors of the endpoints are computed. If
they are the same, then that value is returned. Otherwise, the
precision of the "RealIntervalField" is increased until they do
match up or it reaches "bits" of precision.
3. If none of the above work, Sage returns a symbolic "Expression"
object.
EXAMPLES:
sage: floor(5.4)
5
sage: type(floor(5.4))
<class 'sage.rings.integer.Integer'>
sage: var('x')
x
sage: a = floor(5.4 + x); a
floor(x + 5.40000000000000)
sage: a.simplify()
floor(x + 0.4000000000000004) + 5
sage: a(x=2)
7
sage: floor(cos(8) / cos(2))
0
sage: floor(log(4) / log(2))
2
sage: a = floor(5.4 + x); a
floor(x + 5.40000000000000)
sage: a.subs(x==2)
7
sage: floor(log(2^(3/2)) / log(2) + 1/2)
2
sage: floor(log(2^(-3/2)) / log(2) + 1/2)
-1
sage: floor(factorial(50)/exp(1))
11188719610782480504630258070757734324011354208865721592720336800
sage: floor(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000000
sage: floor(SR(10^50 - 10^(-50)))
99999999999999999999999999999999999999999999999999
sage: floor(int(10^50))
100000000000000000000000000000000000000000000000000
Small numbers which are extremely close to an integer are hard to
deal with:
sage: floor((33^100 + 1)^(1/100))
Traceback (most recent call last):
...
ValueError: cannot compute floor(...) using 256 bits of precision
This can be fixed by giving a sufficiently large "bits" argument:
sage: floor((33^100 + 1)^(1/100), bits=500)
Traceback (most recent call last):
...
ValueError: cannot compute floor(...) using 512 bits of precision
sage: floor((33^100 + 1)^(1/100), bits=1000)
33
sage: import numpy
sage: a = numpy.linspace(0,2,6)
sage: floor(a)
array([0., 0., 0., 1., 1., 2.])
sage: floor(x)._sympy_()
floor(x)
Test pickling:
sage: loads(dumps(floor))
floor
Call docstring:
Allows an object of this class to behave like a function. If
"floor" is an instance of this class, we can do "floor(n)" to
obtain the floor of "n".
Exercise
Recall from above that the floor of a real number (also called the integer part of ), is the greatest integer which is less than or equal to .
This is usually denoted by or simply by .
The floor function is then defined by , for all .
Plot in Sage the floor function. Hint: Use the command .
Solution:
Let us try to use the command , as it is suggested, and sketch the graph of the floor function for . We type:
Of course, the vertical lines are not part of the graph. Moreover, the floor functions has discontinuities at any integer .
To sketch in a better way the graph of the floor function we may use inside the plot function the option , to exlude these discontinuities.
The result is a the same figure as above, but without the vertical lines, see here:
Finally, one can plot the floor function in a more manual way and present the discontinuities by a small circle.
Our method for this relies on the logical and goes as follows:
Exercise
Plot in Sage via the command the function , for different values of .
Solution:
For the implicit plotting of will give a line. For we get a circle:
Further details on plotting with Sage will be covered in the forthcoming chapters. Additionally, examples of working with symbolic variables often involve computing sums, both finite and infinite, which are of particular importance in mathematics. Thus, it is useful to know how to compute a given sum using a mathematical package. Let us present such an example.
Exercise
It is well-known that using the principle of mathematics induction over the natural number one can show that Such integers are called triangular numbers. Verify In Sage this result.
Solution:
We use the command , which we will meet again in Chapter 2 when we will study series. For out task, its implementation goes as follows
Exercise
Compute the sum .
Solution:
Exercise
Compute the sum .
Solution:
Further examples on symbolic variables
1.7. Booleans
Next, we will explore how to evaluate set operations. This can be done using the function. The function in Python and SageMath is used to convert a given value or expression into a Boolean value, either True or False. It can be used in conditions involving sets or other collections, where it helps to determine if the collection is empty or contains elements, etc. For example:
Let us now work with sets that contain strings, where you asked to test various properties of these sets. In SageMath (and in Python), sets are defined by using the curly braces .
Exercise
For the sets given below (consisting of words (strings)), use SageMath to test membership using the bool() function. In particular, do the following:
Test if "cherry" is in both sets.
Test if "apple" is in the colors set.
Check if the intersection of the sets is non-empty.
Check if the fruits set is a subset of the colors set.
Perform a union of the two sets.
Test if "banana" is in the combined set and "blue" is in the colors set.
Test if "date" is not in the colors set or "green" is in the fruits set.
Solution:
Next, we have:
Moreover:
Exercise for practice
Consider the sets:
Use the bool() function to test the following:
Check if the string "apple" is in both sets.
Check if the number 2 is in set1 but not in set2.
Check if the string "apple" is in both sets.
Check if the number 2 is in set1 but not in set2.
Check if the intersection of set1 and set2 is non-empty.
Check if the union of set1 and set2 is non-empty.
Check if "banana" is in set1 or set2.
Check if the number 3 is in set2 and the string "cherry" is in set2.
We will return to Boolean operations on general sets in Chapter 2.
1.8. Subsets of real numbers
Many of the given tasks in this course require the use of real numbers only.
Hence it can be useful to pose already in this place some commands in SageMath appropriate to treat subsets of the real line.
Remark
The known mathematical notation for open (or closed) intervals of applies in Sage too. However, there are alternatives:
For instance, one can type , for some , which gives the open interval .
Let us present some examples.
Or, to get a closed subset we may type:
However, since brackets must be balanced in Python, we see that typing , for example, we will get an error:
Input In [47]
(Integer(0), Integer(1)]
^
SyntaxError: closing parenthesis ']' does not match opening parenthesis '('
The naive notation for half-open intervals works only as follows:
We may also define single sets, as follows:
Or we may type
Here are some further options that we can use to define subsets of the real line:
The real line forms a very basic example of a (smoth) manifold, and Sage knows about manifolds - a notion that unfortunatelly we will not discuss further in these notes.
However, lets us present the real line as a manifold in Sage, which provides an alternative interpretation of the outpout given for the previous case.
Let us now discuss some methods, which all return as a result the union of subsets of the real line:
We will meet some (topological) characteristics of subsets of the real line, as upper/lower bounds, interior, closure, etc, in Chapter 2.
Let us now present additional syntax referring to subsets of .
Basic Boolean tasks using subsets of the real line
Union of subsets - a further perspective
We may also type:
Example
1.9. Complex numbers
There are many ways to introduce a complex number in SageMath.
For instance for the complex number we can type , or simple (or ).
Exercise
For the complex number and compute the following:
The real/imaginary part of ;
, , ;
The argument of , and of ;
The complex conjugate of and ;
Plot the complex numbers , , .
Solution:
Exercise
Express the complex nmber in the form with . Next, find its real and imaginary part.
Solution:
Thus and , that is and . In Sage we may type:
Exercise
Sketch the following sets of points in via Sage:
Solution:
We first introduce as variables and then define the complex number .
Then we use the the command or the command , appropriatelly:
So, represents the imaginary line. For the second set of points we get the annulus around :
The third set is the hyperbola :
The last set is the exterior of the unit disc centered at~.
1.10. Functions with Sage
Next we will introduce some examples which will help us to understand better how to use Sage when studying basic objects in mathematics, as functions, etc.
This section can be read briefly, since we will return on functions in details in Chapters 2 and 3.
We have already been familiar with the method introducing functions in Sage using symbolic variables. Let us recall such an example.
Exercise
Present in Sage the code for defining the following function: . Next, find its value at the points and .
Solution:
Or we may type
Another method - The command
Another way to introduce functions in SageMath follows the standard way to create a function in Python.
This is based on the keyword (usually, a Python function ends with the command, which returns the result).
The related syntax is as follows:
def ’name’(’arguments’):
’instructions’
return ’result’
Notice however that the block positioning is important, something that we will see better via examples.
Exercise
Type in Sage a short routine to define the function . Then compute the values , , and .
Solution:
Or we can type
Tip
For computing all the given values together, we can proceed as follows (we use the commands and ).
Finally recall that typing the given values in decimal way, we can obtain a decimal presentation of , and :
1.11. Preliminaries on programming with Sage
Lists
As we saw before, like Python, Sage uses (squared) brackets to indicate a list.
Recall also that Sage starts all lists (and array) indices with element zero.
The entries of a list are are separated with commas and are included inside " " or ' ' .
When we want to create a list of numbers, we should avoid to include them inside " " or ' ' (in the latter case, the numbers will be treated only as strings).
Moreover, list of numbers can be also written using round brackets (parenthesis) (), instead of brackets (as the vectors in linear algebra).
In the latter case we can still extract any entry, but one cannot perform operations as changing the inputs of entries, etc.
Hence in general we will create list using square brackets.
Exercise
Create in Sage a list consisting of the countries India, Germany, Brazil, Japan, Ukraine, Italy, Czech Republic, Thailand, Spain, Greece. Next print the list, find its length and extract the third and sixth member of this list.
Create in Sage a list consisting of the population of the above countries, according to the following link: https://www.worldometers.info/world-population/population-by-country/ Next print the list and extract the third, fifth, sixth and tenth member of this list.
Add the populations of the countries appearing in the previous list.
Use the command to plot the numerical values of the populations given in 2) in a bar graph.
Create a table which will assing the countries from the list in 1) with the populations in list 2). Hint: Use appropriatelly the command .
Add in the first list the country Mexico and in the second list its populations. Next construct the new table (as in case 5) and the new bar graph. Hint: Use appropriatelly the command .
Solution:
Let us call the first list ``countries''
To find the 3rd and 6th member of the list we type and , respectively (recall that the list indices start from 0).
For the second list one can work similarly (here we post the populations based on the mentioned link, as it was on April 2024).
To add the populations inclued in the list ``pop_per_country'' one can use the command and type .
To produce the required bar graph (also known as a ``bar chart") we can use the command as follows:
To create this table we can use the command as follows:
For this, give the following cells:
Exercise for practice
Repeat the previous task, for the same countries, but with respect to the total deaths by Covid (according to the link of wikipedia: https://en.wikipedia.org/wiki/COVID-19_pandemic_by_country_and_territory)
Dictionaries
Dictionaries are also very useful to encode data. Let us describe their implementation via an example.
Exercise
Create (and print) a dictionary assigning to each country appearing in 1) of the previous problem, the corresponding population.
--according to the link: https://www.worldometers.info/world-population/population-by-country/
Locate the keys and the values of the dictionary.
Solution:
The solution goes as follows:
Sage has built-in functions to perform these `operations', which can be done via the commands and , respectively.
Conditionals
In SageMath an important instruction is the conditional (or test), which enables us to execute some instructions depending on the result of a boolean condition.
Exercise
Present a syntax in Sage printing when some given number c is bigger than 5, and in the opposite way.
Solution:
Example
Exercise
Introduce the function for and for in Sage. Next evaluate .
Solution:
In this case we need to add conditions, so we may type:
Note that:
However, we also obtain
Hence we may type:
(For) Loops
In Sage (enumeration) loops perform the same computation for all integer values of an index running in specific set of indices, say .
In other words, loops are statements that allow us to repeat a set of instructions either for a number of times, or until an expression (condition) becomes false.
For this reason loops become very important in programming and as such they often appear in coding with Sage.
Therefore, it can be useful to describe a few details, useful for applications in forthcoming chapters.
Exercise
Type a code in Sage that will output the multiplication for .
Solution:
Exercise
Type a code in Sage that will output the multiplication for .
Solution:
Or we can equivalently type:
Example
This example provides a way to ask from Sage to return to our screen terms of a given sequence (when is running in for some certain range).
Here. we also use the command which is about substitutions (see also Capter 2).
Often, it maybe be useful to illustrate these terms (and so part of the seqence). We can do this in many different ways, one of them given below.
For the command type the following syntax below to read details for its use. Note that we will examine many details on sequences and how we can treat them (even graphically) via Sage, in Chapter 2.
Exercise
Program Sage with the aim to print the expression
where and represent positive numbers.
Solution:
Exercise
Type a code in Sage that will simultaneously return the prime factorization of the integers 20, 21, 22, 23, and 24. The code should print each one of these numbers, together with it’s factorization.
Solution:
As we saw above, the statement (which is a short for ), can be used when we want to specify/check whether our expression satisfies more than one condition. As another example:
Also, we saw that the operator can be used if we need to execute some code. For example, we can use this to establish another way to introduce piecewise functions. Let us present an example.
Exercise
Define in Sage the function