Chapter 2 - Sage & basic mathematical structures - A warmup
2.1. Solving equations and inequalities
2.2. One-variable functions and 2D-plotting
2.3. Basics on sets and combinatorics
2.4. Classical & conditional probability
2.5. Plane geometry
2.6. Relations & mappings
2.7. Difference equations
In this chapter, we will explore various methods in SageMath for solving different mathematical tasks, starting with an overview of how to tackle equations and inequalities. Given the diverse types of equations—such as polynomial, linear, difference, or differential equations (and their systems)—we will encounter additional techniques for solving these equations with SageMath later in the course. The material in the first section of this chapter focuses on introducing the reader to fundamental methods in SageMath for solving relatively simple equations, rather than delving into specialized types. We will then move on to plotting functions and discuss methods for providing graphical confirmation of our findings.
2.1. Solving equations and inequalities
In Chapter 1, we learned that Sage can solve equations (and inequalities) using the command . In fact, this command can be effectively applied to systems of equations involving more than one variable. It's important to note that the command aims to express the solution of an equation without resorting to floating-point numbers. If this is not possible, it will return the solution in symbolic form. To obtain a numeric approximation of the solution, we can use the command, among other techniques.
Exercise
Solve the following equations or inequalities in SageMath:
;
;
;
;
;
;
.
Solution:
Or we use the command , as follows:
The second number inside the parenthesis indicates the multiplicity of the root (1 in our case).
As for the second equation, which is of degree 3, by the Fundamental Theorem of Algebra we know that there exist 3 complex solutions.
SageMath computes them very quickly:
However, as it seems from Sage's output, extracting or copying these solutions can be messy.
To overpass this problem, or at least encode in a better way the given solutions, one can work as follows:
Then we obtain any solutions seperately, by typing (recall that Sage's labeling in lists starts by 0).
In case we want the real/imaginry part of some solution, we can use the commands and .
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [42], in <cell line: 1>()
----> 1 sols[Integer(3)]
, in Sequence_generic.__getitem__(self, n)
521 return Sequence(list.__getitem__(self, n),
522 universe = self.__universe,
523 check = False,
524 immutable = False,
525 cr = self.__cr)
526 else:
--> 527 return list.__getitem__(self,n)
IndexError: list index out of range
Recall that Sage allows us to compute the ``length of a collection or list'' , via the command . Hence, typing we expect that Sage will print out the number 3.
Of course, this fits with the fact that the initial equation was of degree 3 (Fundamental Theorem of Algebra).
Let us now treat the given inequality:
As usual, we see that the solution set of certain inequalities consists of the union and intersection of open intervals.
The next is again a polynomial equation of degree 3, so we expect 3 roots over the complex numbers:
Note however that the choice of the ring affects the result!
By creating the polynomial ring over the rational numbers (ℚ) using the command , you are working within a context where only rational numbers (fractions) are considered. So in this case the method only provides roots that are rational numbers!
The command used above returns the generator of this polynomial ring, which in this case is the variable . The comand computes the roots of the polynomial . It returns a list of pairs, where each pair consists of a root and its multiplicity.
As we pronounced , to find a numeric approximation we can use the command . This requires also a closed interval on which to search for a solution (however, this command will only return one solution on the specified interval, if one exists. It will not find the complete solution set over the entire real numbers)
Let us illustrate the solution (and see below for more examples in 2D-plotting )
Let us also solve the equation given in 8. In this point recall that in Sage means the natural logarithm.
Hence we get two solutions satisfying the given equation.
Remark
We mention that the command can be very slow for large systems of equations. Below we present a few simple examples.
Notice that systems of linear equations will be treated later in terms of linear algebra functions.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 solve( [Integer(3)*x -Integer(2)* y == Integer(2), -Integer(2)*x -Integer(5)*y == Integer(1) ], x,y)
NameError: name 'y' is not defined
This mean that we forgot to introduce as a variable, since in fact we first typed , in order to ``clear'' some possible assignement to this variable.
This is because SageMath has been programmed to keep in its memory any assignment we have done, untill we decide to reset it.
Thus, to solve the system of equations given above we may proceed as follows:
Another example:
Above, (or better written ) is a free variable (and this parametrizes the solution set).
When there is more than one free variable, SageMath enumerates them by (that is, by ).
Finally, let us solve a system of inequalities in several variables (this can lead to complicated expressions).
To explore a full list of options of the command in SageMath, type the following:
2.2. One-variable functions and 2D-plotting
In SageMath the graph of a real-valued function defined in some subset of the real line , is given by the command , where are the end points of .
Exercise
Present the graph of the folowing trigonometric functions for :
,
,
,
.
Solution:
For the function , we get the graph
Or, after introducing the function we could just type .
Similarly, in this case we type
Let us now plot the function :
The function has asymptotes. In SageMath to produce a meaningful plot for this function one can proceed with the syntax
Remark
The options xmin (or ymin) and xmax (or ymax) are interval bounds over the -axis (respectively over -axis) for which the Sage will display the function.
For instance, above we required the function to be dispalyed in the -axis from to .
So this option changes the window range of the graph.
We also used the option since its defaul value is False.
This option often enables to draw a vertical asymptote at poles of the function.
Note that without these options the graph of will not appear correctly.
Other options that we can often use are color, thickness, linestyle etc.
Thickness is about the thickness of the curves in the graph, and the defaul value is 1.
Linestyle has as default the solid, or "", while we also have further options for this, as “” or “dashed” , “” or “dashdot”, “” or “dotted”, etc.
Later we will see that we can add text in a graph, plot a single point, give labels to the axes, etc.
Exercise
Plot in one figure the graph of for and the line passing through the points and , together with these two points.
Solution:
Here we fixed the option , to have equal scales for and .
More details on points, lines, etc, we will meet below when we will use Sage to study plane geometry.
Exercise
Plot the following functions for the given domain:
, ;
, ;
, for .
, for .
Solution:
Recall that the domain of is the open set , with , hence the given function is not defined at . Sage indicate this as follows:
In the second case the given function is well-defined since for instance is required and so .
In this case one arrives to the graph
In this case one can use the options , or , together with an arrangement of window size options. In particular, we may proceed with the syntax
Or we could directly type: .
Tips
In SageMath it is very easy to join two (or more) graphs in one system of axes together, as in the following example:
Let us present another similar example:
When one is not interested in the domain of a given function , it is still possible to plot as follows (Sage will consider itself a domain for ).
In SageMath one can use the option , which is about the minimal number of computed points, with 200 as default value.
For instance:
Note that the marker can be a TeX symbol. As an example
We can add a name/title to a plot (see also below for the command ). Let us give an example.
In fact, we can also set the position of the title, including coordinates, via the option . For instance:
We can add labels to the axes:
. In some cases we may want the axes to use values such as , etc.
We may obtain this by using the option .
Let us present an example:
We may also like to add a legend. For instance
. Sage allows us to fix the color that we like in the legend, as below:
Often it can be useful to plot together two graphs (or more) but using distinct system of axes, or even labeling. For instance
Note that if we write the last command as we will not obtain an optimal result:
To explore further options of the command in SageMath, type the following and scroll down the appearing file.
Exercise for practice
Plot together the graphical presentation of the functions and for , label the axes, and for the -axis use values as , etc.
Finally put a title to the figure.
Plot of piecewise functions
Suppose that is a real-valued function defined by
or with different kind of domains. In Sage to define such functions we can use the command. Let us present examples.
To obtain the collection of domains of the component functions we may type . On the other hand, to otain the end points of the intervals, we may type . For our example this gives
Exercise
Plot the following functions in SageMath:
Solution:
For the first case we use the cell
To correct the above graph (that is, to avoid the vertical line, which is not part of the graph), we should use the command.
For the second case, we may type:
Another Example of 2D-graphics (lines Vs circles)
Note that editing where is evaluated, we result to different figures:
A colourful example (rainbow colors)
2.3. Basics on sets and combinatorics
Combinatorics is a branch of mathematics that deals with counting and arranging objects in a systematic way.
Combinatorics is used in a wide range of fields, including computer science, statistics, physics, and biology.
It is also used in various real-life situations, such as in the design of codes and ciphers, scheduling of events, and the arrangement of seating in a theater or stadium.
With Sage it's much easier to do combinatorics in a quick way, as we will see soon via examples.
Sets
We will be working with sets a lot, so let's see how do declare them and what you can do with them after.
Sets can be finite and infinite and we can check this with .is_finite() method
Basic operations with sets
We now describe some basic operations that we can apply when we use sets.
A) Intersection
The intersection of some given sets can be treated with .intersection() method. For example:
B) Union
The union of some given sets can be treated with the .union() method or plus '+' sign. For instance:
C) Difference of sets
The difference of some given sets is treated with the .difference() method or minus '-' sign
D) Cartesian product of sets
We can also do Cartesian product with different sets with cartesian_product() function:
Hint:
We can check the cardinality of our sets and Cart. products with .cardinality() method
We can choose random elements from our sets with .random_element() method
Subsets
To create subsets from some give set, we can apply yhe Subsets() wrapper, as below.
Hint: If and are sets, then is a subset of , denoted by , if and only if every element of is also an element of
Combinatorics
In this section we use natural numbers to describe some indivisible items located in real life space, and deal with questions in how many ways certain events may appear.
For instance, how to compute the number of their (pre)orderings, specific choices, and so on. In many of these problems, “common sense” is sufficient.
We just need to use the rules of product and sum in the right way, as we show in the following examples. We proceed with exercises on combinatorics.
Permutations (without repetition)
Suppose we have a set of (distinguishable) objects, and we wish to arrange them in some order. We can choose a first object in ways, then a second in ways, a third in ways, and so on, until we choose the last object for which there is only one choice. The total number of possible arrangements is the product of these, hence there are exactly distinct orders of the objects.
The number of distinct orderings of a finite set with elements is given by the factorial function:
Exercise
Find out how many permutations we can make with integers from to and from to
Solution:
We can use built-in function for 3 and then for 4 permutations
We can also use the function
Hint:
Exercise
In how many ways can chemistry, math, and physics books be set on a shelf, if the chemistry books are set on the left, math books in the middle, and physics books on the right?
Solution:
In this case we will use the function for each group and then multiply them.
Exercise
In how many ways can chemistry, math, and physics books be set on a shelf, if they are grouped by subject?
Solution:
We will, again, use the function for each subject and then add them up, but as we can change the place of subjects on shelf, we will also multiply the sum by the number of subjects.
-Permutations (without repetitions)
Suppose is a set with elements. Suppose we wish to choose and arrange in order just of the members of , where .
This is called a k-permutation without repetition of the elements.
The same reasoning as above shows that this can be done in: ways.
The right side of this result also makes sense for , (there is just one way of choosing nothing), and for , since .
Exercise
How many 4-letter words(meaning a set where order of elements plays role) we can make with where letters can't repeat?
Solution:
We need to find -letter words, which means that we can include only (4 in our case) elements from our group of (7 in our case) without repetitions, where the order counts, for that we can use this formula Where,
- is the number of all elements,
- is the number of allowed elements from all
In Sage for this we can define a function, as follows:
Let's see how we can double-check our answer with the practical experiment.
Exercise
We have physics books and math books to put on a shelf with 6 slots.
In how many ways can we put the books on the shelf, if the first two slots needs to be filled with physics books, and the next four with math books (order plays role)?
Solution:
We can include only physics books from , and math books from 6, the order counts, so we can use formula for both subjects and add the results
Exercise
We have physics books and math books to put on a shelf with slots. In how many ways can we put the books on the shelf (order plays role)?
Solution:
We can only put 4 books into shelf from 11, the order counts, so we can use formula for both subjects and add the results
-Combinations (without repetitions)
Consider a set with n elements. A -combination of the elements of is a selection of elements of , , when order does not matter.
For , the number of possible results of a subsequential choosing of our elements, is (a -permutation).
We obtain the same -tuple in distinct orders. Hence the number of -combinations is If , the same formula is still true, since , and there is just one way to select all elements.
Exercise
How many 4-letter sets(meaning a regular set, where order of elements doesn't play role) we can make with ABCDEFG, where letters can't repeat?
Solution:
We need to find -letter sets, that means that we can include only (4 in our case) elements from our group of (7 in our case) without repetitions, where the order of elements doesn't count, for that we can use this formula Where,
- is the number of all elements,
- is the number of allowed elements from all
Basically, what we've changed is that we divided the order our (represented by k!) from our -permutations formula
Or we can use already defined function in SAGE called
We can prove this with sets
Exercise
If a coin is tossed seven times, in how many ways can it fall heads and tails?
Solution:
Suppose we have 7 spots to put the coins on.
If we choose any spots for tails, the other will automatically be tails. So we can use formula, where from 7 we choose 2:
But we can also go from the other way, where from 7 spots we choose 5 spots for heads and 2 tails would be set automatically:
Exercise
The government consists of people: from green party, from red party, and from blue party.
In how many ways could a person committee be selected if it contain's red, blue, and green?
Solution:
We need to get 2 people from 15 red, 4 people from 30 green and 6 from 55 blue.
So we can use formula, for each party, and then multiply the results, as all three combinations are independent from each other and can be mixed
-Permutations (with repeatitions)
Let be a set with distinct elements. We wish to select elements, from with repetition permitted.
This is called a -permutation with repetition.
Since the first selection can be done in ways, and similarly the second can also be done in ways etc.
The total number of -permutations with repetitions is . Hence
Exercise
Consider that we have an car plate, which consists of digits. How many plates can be created?
Solution:
When we're dealing with the repeated permutations we can use the following formula Where,
- number of elements,
- number of wanted elements
We have digits (number of elements ) and we want to create car plates with digits (number of wanted elements )
Exercise
Imagine you have a coin and you're throwing it times. What is the number of possible outcomes?
Solution:
Applying our formula , where 2 is number of elements () and 10 wanted elements ()
-Combinations (with repeatitions)
If we are interested in a choice of elements without taking care of order, we speak of -combinations with repetitions.
At first sight, it does not seem to be easy to determine the number.
We reduce the problem to another problem we have already solved, namely combinations without repetitions:
The number of k-combinations with repetitions from elements equals for every and
Exercise
From types of beer (consider infinite amount of each), one of which is dark, you are putting of them on the table.
Determine the number of combination of beers you can put on the table.
Solution:
When we're dealing with the repeated permutations, we can use the following formula Where,
- number of types of elements,
- number of wanted elements.
Applying to our task we have 5 types of beer (5 types of elements) and 10 bottles on the table (10 wanted elements)
Exercise (continuation)
From types of beer (consider infinite amount each), one of which is dark, you are putting of them on the table.
Determine the number of combination of beers if you must include at least one dark beer.
Solution:
As we have already selected one dark beer, we can still put 9 more beers of 5 types.
We can use our formula, where our and
2.4. Classical & conditional probability
Probability theory is the study of random events and the likelihood of their occurrence.
It has wide-ranging applications in fields such as statistics, engineering, physics, and finance.
With the help of Sage, we can perform various calculations and simulations to gain a better understanding of probability concepts and solve complex problems.
Exercise (rolling a die)
Suppose we roll a fair six-sided die. What is the probability of rolling a 3?
Solution:
First, we define a probability space for the experiment of rolling a die, which consists of the set of possible outcomes {1, 2, 3, 4, 5, 6}, each of which has equal probability:
To calculate the probability of rolling a 3, we can use the following command in SAGE:
This indicates that the probability of rolling a 3 is 1/6, which is consistent with our intuition.
Exercise (flipping a coin)
Suppose we flip a fair coin twice. What is the probability of getting exactly one head?
Solution:
We can define a probability space for this experiment as follows: {HH, HT, TH, TT}, where H represents heads and T represents tails.
There are two possible outcomes with only one head: HT and TH. To calculate the probability of getting exactly one head, we can use the following code in Sage:
Exercise
What is the probability that when rolling two dice the sum is 7, if we know that neither of the rolls resulted in a 2?
Solution:
Let be the event that neither of the rolls results into 2, and let be the event “sum is 7”.
The set of all possible outcomes is again denoted by . Thus:
.
The number 7 can appear as a sum in four ways if there is no 2 ((1,6), (3,4), (4,3), (6,1)), that is, . Thus .
We can also run the simulation to estimate the resulting probability:
Exercise
Michaela has two mailboxes, one at gmail.com and the other at hotmail.com.
Her username is the same at both servers, but the passwords are different.
She does not remember which password corresponds to which server.
When typing in the password for accessing his mailbox, she makes a typo with probability 5%
(that is, if she tries to type in a specific password, she types what she intended with probability 95%).
At the server hotmail.com, Michaela typed in the username and a password, but the server told her that something is wrong.
What is the probability that she chose the correct password but just mistyped?
(Assume that the username is always typed correctly and that making a typo cannot turn wrong password into a good one.)
Solution:
Let be the event that Michaela typed in a wrong password at hotmail.com. This event is the union of two disjoint events:
: she wanted to type in the correct password and mistyped,
: he wanted to type in the wrong password (the one from gmail.com) and either mistyped it or not.
We are looking for a conditional probability which, according to the formula for conditional probability, is:
where we have used since and are disjoint.
We just need to determine the probabilities and .
The event is the intersection of two independent events: Michaela wanted to type in a correct password and Michaela mistyped.
According to the problem statement, the probability of the first event is 1/2 and the probability of the second event is 1/20.
In total (we multiply the probabiliies, since the events are independent).
Further we have (directly from the problem statement) . In total . We can now evaluate
Geometric probability (optional)
The method of geometric probability can be used in the case that the given sample space consists of some region of a line, region, space (where we can determine (respectively) length, area, volume, etc).
We assume that the probability, is equal to the ratio of the area of the subregion to the area of the sample space.
Exercise
From Edinburgh Waverley station trains depart every hour (in the direction to Aberdeen).
From Aberdeen to Edinburgh they also depart every hour.
Assume that the trains move between these two stations with a uniform speed 72 km/h and are 100 meters long.
The trip takes 2 hrs in either direction.
The trains meet each other somewhere along the route. After visiting an Edinburgh pub, John, who lives in Aberdeen,
takes the train home and falls asleep at the departure.
During the trip from Edinburgh to Aberdeen he wakes up and randomly sticks his head out of the train for five seconds, on the side of the train where the trains travel in the opposite direction.
What is the probability that he loses his head? (We are assuming that there are no other trains involved.)
Solution:
The mutual speed of the oncoming trains is
fourty metres per second, the oncoming train passes John’s window for
two and a half seconds. During John’s trip two trains pass by John’s window in the opposite direction.
Any overlap of the 2.5 seconds of the passing time interval with the 5 second time interval when John’s head might be sticking out is fatal.
Thus, for each train, the space of “favourable” outcomes is an interval of length 7.5 seconds somewhere in the sample space.
For two trains, it is double this amount.
The sample space of all outcomes is the interval .
Thus the probability of losing the head is:
Exercise
In a certain country, a bus departs from town A to town B once a day at a random time between 8 a.m. and 8 p.m.
Once a day in the same time interval another bus departs in the opposite direction.
The trip in either direction takes 5 hours. What is the probability that the buses meet, assuming they use the same route?
Solution:
The sample space is a square ( hours for each bus).
If we denote the time of the departure of the buses as and respectively, then they meet on the trail if and only if .
This inequality determines the region in the square of “favourable events”. Let's plot it:
This is a complement to the union of two (red) right-angled isosceles triangles with legs of length . Their total area is , so the area of the “favourable part” is . The probability is .
Exercise
A rod of length two meters is randomly divided into three parts. Determine the probability that at least one part is at most 20 cm long.
Solution:
Random division of a rod into three parts is given by two points of the cut, and (we first cut the rod in the distance from the origin, we do not move it and again cut it in the distance from the origin). The sample space is a square with side 2 m.
If we place the square so that its two sides lie on axes in the plane, then the condition that at least one part is at most 20 cm determines in the square a subregion :
Let's plot how this area looks like:
We are interested in the ratio of the blue area to the total area of the square. Let's calculate its approximate value:
Using some simple geometry we can determine that the side of the red triangles is . Knowing this, we can calculate the area of two red triangles exactly as . The answer to the problem will be the ratio of the blue area to the total area of the square:
Exercise
Two meter-long pole is randomly divided into three pieces.
Determine the probability that a triangle can be built of the pieces.
Solution:
Exercise (Alice & Bob)
Alice and Bob play the following game. First, Alice tosses four coins. After that, Bob tosses five coins.
Bob wins if she gets strictly more heads than Alice.
What is the probability that Bob wins?
Solution:
With given constraint, there are only possible outcomes in the game.
We can generate all possible outcomes of 9 tosses and count cases where Alice wins.
2.5. Plane Geometry
Let us now discuss basic tasks from Plane Geometry.
Points, lines and basic operations
Exercise
Find the length of the line segment joining the points (-1, 2) and (3, -4).
Solution:
We can use the distance formula to find the length of the line segment:
Substituting the coordinates of the two points, we get:
Relative position of lines
Once we have the equations of the two lines, we can set them equal to each other to find the point of intersection.
If the two lines are not parallel, they will intersect at a single point.
Given two lines, the intersection point is the point at which the two lines cross each other. In slope-intercept form, we can write the equation of each line using the slope-intercept form, y = mx + b, where m is the slope and b is the y-intercept (the value of y when x is zero).
Exercise
Find the intersection point of the lines:
Solution:
We can use the previous function, to find the intersection:
Here is a simpler way to understand the relative possition of two lines in the plane, just by solving the induced system:
Exercise (intersection point of 2 lines)
Find the intersection point of the lines given by the equations:
Solution:
Distance between two lines
The distance between the two parallel lines is the absolute value of the difference between their y-intercepts divided by the square root of 1 plus the square of their common slope.
Therefore the formula for the distance between two parallel lines in slope-intercept form is:
Exercise (distance between lines)
Find the distance between the lines:
Solution:
Exercise
Perpendicular lines.
Two lines are perpendicular if and only if their slopes are negative reciprocals of each other. That is, m1 * m2 = -1
Exercise (intersection of parametric lines)
Determine the intersection of the lines
Solution:
Exercise (slope of a line)
Find which of the below is the parametric equation of the line having slope and passes through the point :
Solution:
Given a line with slope its direction vector is given by .
Hence, if the slope is a rational, i.e., for some , then .
It follows that the right answer is and , which represent the same line.
It is interesting to present the figure of the lines in Sage, all together in one plot, with different colours and thickness/style, in order to be able to visualize them.
To do so, since the lines are given in parametric form we can use the command . We present the cell here:
Exercise (Sage interactive environment)
Create a Sage interactive cell that allows the user to use two sliders and then plot the line on .
Solution:
A Sage cell doing this operation has the form given below:
Exercise
Find a parametric equation for a line in given by the equations
Solution:
To find a parametric equation for the line in R3, we need to first find a vector that lies on the line and a direction vector for the line. We can do this by solving the system of equations:
This tells us that the line is given by the parametric equations:
x = 5/3t - 1/3s + 4/3 y = t z = s
where t and s are arbitrary parameters.
Exercise (area of triangle)
Find the area of the triangle with vertices at the points , AND , using the Heron’s formula:
Solution:
On should first compute the side lengths:
It follows that the area equals 6. Here is a verification
Exercise (barycenter)
If the vertices of A triangle are , and , the coordinates of the barycenter can be calculated using the following formula: This formula essentially finds the average of the coordinates of the vertices.
Calculate the barycenter of a triangle with vertices , and .
Solution:
And here is the illustration:
Exercise (orthocenter)
The orthocenter of a triangle is one of its notable points, defined as the point where the three altitudes of the triangle intersect. An altitude is a line segment from a vertex perpendicular to the opposite side (or the line that extends that side).
Find the orthocenter of a triangle defined by the vertices , and .
Moreover, plot the triangle and the orthocenter.
Solution:
First we compute the orthocenter, that we denote by : Here how it goes:
To obtain the illustration is easy:
Exercise
Determine whether or not the points [0, 2, 1], [−1, 2, 0], [−2, 5, 2] and [0, 5, 4] in all lie in the same plane.
Solution:
To determine whether or not the given points lie in the same plane, we can check whether they are linearly dependent.
If the points are linearly dependent, then they all lie in the same plane.
Exercise for practice:
Determine whether or not the points [2, 2, 1], [−1, 2, 2], [−2, 4, 1] and [0, 1, 3] in all lie in the same plane.
Exercise
Find the distance between the point [1, 2, -1, 3] and the subspace U defined by the equations
Solution:
To find the distance between a point and a subspace, we need to find the projection of the point onto the subspace and then calculate the distance between the original point and the projected point.
2.6. Relations & Mappings
In this paragraph we will devote some space to describe how one can treat via SageMath relations and mappings.
Let us begin with relations. A relation can be represented as a set of ordered pairs:
Exercise
Give the domain and the codomain of the relation
between the sets and . Is the relation a mapping?
Solution:
To check if a relation is a mapping, we need to ensure that each element in the domain is connected to exactly one element in the codomain. Domain and codomain can be found like this:
Exercise
Determine for each of the following relations over the set whether it is an ordering and whether it is complete:
Solution:
Exercise
Give all the elements in if
Solution:
Exercise
Write down all the relations over a two-element set , which are symmetric but are neither reflexive nor transitive.
Solution:
Exercise
Consider the set of numbers that have three digits in the ternary notation and a relation such that two numbers are in the relation whenever they
a) begin with the same two digits in this notation,
b) end with the same two digits in this notation.
Write down the corresponding equivalence classes.
Solution:
Define function needed for the part (a) of this exercise. It should check if given strings have the same two first characters. Then call equivalence_classes with your function
2.7. Difference equations
In this final section we will treat difference equations, also known as recurrences equations.
A homogeneous linear difference equation (or homogeneous linear recurrence) of order k is given by the expression the right hand side can be non-zero - in this case we have a nonhomogeneous linear difference equation:
This is the general solution with two parameters . We can find a solution for some initial conditions like this:
Exercise
Solve the linear difference equation: , with initial conditions .
Solution:
Exercise
Solve the nonlinear difference equation: , with initial conditions .
Solution:
Exercise
Find the formula for Fibonacci numbers. Check that with Sage.
Solution:
Remark
It can be useful to present a code in Sage which will return the first terms of the Fibonacci sequence for a cerntain positive integer .
We can do this by defining first a function as below (see also the last section of Chapter 1).
Or we can use the function that Sage provides, and allows us to list Fibonacci terms , when runs to a certain region for , as follows:
Let us also mention how we can add Fibonacci terms:
Exercise
Apply the command to the nonlinear difference equation: , with initial conditions .
Next, print the first 10 terms of resulting formula.