Python and Mathematics (1)
Python and Mathematics (1)
1 INTRODUCTION TO PROGRAMMING
[1]: int
[2]: type('90')
[2]: str
1
Python and Mathematics by Donnie M. Kasyoki
Variable A variable is a name that stores a value. In order to be able to store values and
reuse them in our program, we need to give these values names that can be memorised by
the programmer. There are some basic rules that govern the naming of these variables. A
variable name should not:-
Start with a digit. A variable name should always start with a letter or underscore for
some reason. May include digits if the user chooses to do so. For instance 1name, name,
namedate, etc are not valid variables while name, name1, _name are all valid.
Include special characters like @, #, $, %, , &, *, (, etc. The only character permitted is
the underscore.
Include spaces Use an underscore of capitalization of rst letter of the subsequent names
if you want to a variable with multiple names. For instance rst name is not valid, instead
you can write rstName, rst_name, etc.
Although some naming may not give rise to errors, it doesn't mean it is a good practice.
In python we have several key words that are well preserved for the language and have a
meaning in the language. For example the word `print' is preserved for giving output. We
will come across most of these keywords but we may list a few. They include: print, for, if,
in, from, import, list, set, try, except, dict, etc. If a variable is named after these keywords
then it overwrites its functions and you wont be able to use the functionality of the keyword
in that particular program.
Example If we rename print and give is a value, say 10, then printing will result into an
error as swown below.
[3]: print = 10
print('Hello World!')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[34], line 2
1 print = 10
----> 2 print('Hello World!')
[4]: firstName = 'Donnie'#firstName if the variable that stores the str value
,→'Donnie'
Statement A statement refers to a single line of code that instructs the computer how to
perform a specic task. Some examples of statements that we will encounter include: print
statement, assignment statement, if statements, etc.
2
Python and Mathematics by Donnie M. Kasyoki
Hello World!
Assignment operators are used to assign values to variables. They include: =, +=, -=, /=,
*=, **=, etc. An equal sign preceeded by an arithmetic operator is used for reassignment
which means the variable must have existed before reassigning it. These reassignment op-
erators are used just to avoid repeting the specic variable name. We will consider some
examples below.
Comparison operators are used to compare two values. E.g. == for comparing equality, !=
for checking non-equality, > for greater than, < for less than, <= for less than or equal to,
>= for greater than or equal to.
Logical operators are used to combine conditional statements. E.g. and, or, not.
There other types of operators that you may want to research on.
[6]: #Arithmetic
print(25 % 7) #Gives the remainder when 25 is divided by 7. Used to test
,→for divisibility.
4
3
[7]: #Assinment
n = 10; h = 'Hello' #assigns values to variables
n += 5 #Equivalent to n = n + 5
print(n)
15
3
Python and Mathematics by Donnie M. Kasyoki
[8]: #Comparison
print(10 == 10) #this is True
print(10 < 10) #this is False
print(10 <= 10) #this is True
True
False
True
[9]: #Logical
print(10 == 10 or 10 < 10) #Since one of them is True, the whole
,→statement is True
print(10 > 10 or 10 < 10) #is False. None of the statements is True
print(10 == 10 and 10 < 10) #is False. and requires both to be True.
True
False
False
1.1.2 Expressions
An expression is a combination of operarators and operands. Operands could be values or
variables.
Order of operation Arithmetic operators in python just like in mathematics have dier-
ent order of precedence. PEMDAS is a mathematical accronym that is used to summarize
these precedences. PEMDAS stands for Parenthesis, Exponentiation, Multiplication, Divi-
sion, Addition and Subtraction. Multiplication and division have the same precedence and
addition and subtraction as well. So the one that comes rst precedes in the operation.
print(3+4-5 == (3+4)-5)
print(4/5*7 == (4/5)*7)
print(4*5/6 == (4*5)/6)
print(5-8/2**3-(1-3)) #=5-8/2**3-(-2)=5-8/(2**3)+2=5-8/8+2=5-(8/
,→8)+2=5-1+2 = 4+2 = 6
True
True
True
4
Python and Mathematics by Donnie M. Kasyoki
True
6.0
Comments When writing codes, it is wise to write short comments as a guide to the user
or even yourself as you work on the code. The comments may be explaining variables or
functionalities of sections of codes. Comments in python start with a # symbol. We can
also write a descriprion of what the program does by writing a much longer comment. Then
comments begin and end with tripple quotation marks when using other python editors. For
jupyter you may want to set the cell to `markdown' rather than `code'. Comments do not
aect the code and are not part of the output.
Hello World!
2 Debugging
For some reason errors in a computer program are called bugs. Therefore, the process in
which the programmer identies and corrects these errors is referred to as debugging.
It is therefore very useful to understand the error messages that python shows when it
encounters them. We start by looking at some of these common errors that may arise in a
program.
Type error As the name suggests, this error occurs when the user does an operation
that is not permitted by a certain type of value. We have already gotten this error when
5
Python and Mathematics by Donnie M. Kasyoki
discussing variables. The message was that the type int is not callable. The reason for that
is because int is not a function therefore cannot be called with the parenthesis. Also using
* on a oat and a str will result in the same error. There are many ways in which one can
get these errors.
[13]: .8 * '.7'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[36], line 1
----> 1 .8 * '.7'
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[36], line 2
1 name = "Donnie Munyao"
----> 2 print(Name)
Indentation error This error will occur mostly because of inconsistency spacing behind a
statements or expressions. When writing functions (def statements), if, else, elif statements,
class denitions require that the second line be indented and thus missing indent will result
in this type of error.
6
Python and Mathematics by Donnie M. Kasyoki
[15]: n = 10
m = 11
print(n*m)
Index error This error occurs when dealing with lists. The items in a list can be called
using an index. The rst item is assigned index 0, the second is index 1, etc. If a list has 5
items, then that means index 5 does not exist and therefore accessing it will result to this
error.
Example Let L be the list L = [1,2,5,0,6]. To access the rst element we call L[0], so
calling L[5] will result in index error.
[16]: L = L = [1,2,5,0,6]
print(L[5])
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[7], line 2
1 L = L = [1,2,5,0,6]
----> 2 print(L[5])
Key error This occurs when dealing with dictionaries. In dictionaries, we use keys rather
than indices to refer to items. For example, the dictionary d dened as d = {`name': `Ken',
`gender':`M', `age': 20} has keys `name', `gender', and `age'. Calling any other value or
misspelling a key will result into key error.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[9], line 2
7
Python and Mathematics by Donnie M. Kasyoki
KeyError: 'Name'
FLOWS
Example Write a program to calculate the area of a triangle with base 10 units. and
height 20 units.
[18]: '''
Calculating the area of a triangle
'''
base = 10
height = 20
area = 1/2*base*height
print(f"Area: {area} sq. units")
Variables from the user We can obtain values from the user of the program, we will
therefore use the input function to obtain these data. It is useful to give some direction to
the user.
Example Write a program to calculate the area of a square whose side is provided by the
user.
8
Python and Mathematics by Donnie M. Kasyoki
Importing modules or from modules We can borrow some functions or values that
are already dened in installed modules. The most common modules that we will look at
include: math, numpy, sympy, scipy, etc. There are ways that are used to import these
modules into our programs.
The major ways include:
Importing the module
Importing all the elements of the module
Importing specic function(s) and value(s) from the modules
Example Write a program to calculate the area of a circle whose radius is provided by the
user.
Example Write a program to calculate the volume of a cylinder whose dimensions are
provided by the user.
Exercise
9
Python and Mathematics by Donnie M. Kasyoki
4 CONDITIONAL FLOW
We solve problems that involve some conditions. We are going to incorporate if, elif and else
statements in this section. The if and elif are followed by a boolean expression.
4.1 if statements
Example Write a program that prints the absolute value of a number x input by the user
given that (
x, if x ≥ 0
|x| =
−x, if x < 0
Enter a number: -3
|-3| = 3
Example
[22]: m = 10
if m >= 10: #True
m += 15 # m is now 25
if m > 20: #True
m += 30 #m is now 55
if m > 50: #True
print('Over 50') # Printed
m -= 40 #m is updated to 15
print(m) #prints the value of m = 15
Over 50
15
10
Python and Mathematics by Donnie M. Kasyoki
Example We repeat the above program using if and subsequent elif statements.
[23]: m = 10
if m >= 10: #True
m += 15 # m is now 25
elif m > 20: #Not checked
m += 30 #m not updated
elif m > 50: #Not checked
print('Over 50') # Not printed
m -= 40 #m is not updated
print(m) #prints the value of m = 25
25
Example Write a program to grade a mark entered by the user (between 0-100) following
the grading system given below:
A = 80 ≤ mark ≤ 100
B = 65 ≤ mark < 80
C = 50 ≤ mark < 65
D = 40 ≤ mark < 50
E = 0 ≤ mark < 40
Enter a mark: 68
B
11
Python and Mathematics by Donnie M. Kasyoki
Example Rewrite a program that prints the absolute value of a number x input by the
user.
Enter a number: -3
|-3| = 3
Example Write a program to calculate the real roots of a quadratic polynomial ax2 +bx+c,
where a, b, c are input by the user.
Example Write a program that checks whether a number n provided bu the user is divisible
by 2, 3, 5 or none. If it is visible by only one, two, or all of them, inform that user.
12
Python and Mathematics by Donnie M. Kasyoki
Enter an integer n: 90
90 is divisible by 2, 3 and 5.
13
Python and Mathematics by Donnie M. Kasyoki
range(k, n, r) gives a range of integers starting with k, then k+r, k+2r and ending at k+mr
< n.
Example Write a program that prints the following sequence of numbers in that order: 0,
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
Example Write a program to evaluate obtain the sum of the rst 100 natural number.
That is
100
X
s= n
n=1
5050
Example Write a program that uses a `for' loop to calculate the factorial of a positive
integer n provided by the user.
print(factorial)
Enter an integer n: 6
720
Exercise
14
Python and Mathematics by Donnie M. Kasyoki
A condition to break I this case the we will need to use a count variable that will
determine when to break. The count variable must be incremented after every iteration so
be sure not to forget that. Anything that can be done with a `for' loop can be done using a
`while' loop.
Example Write a program that prints the following sequence of numbers in that order: 0,
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
[31]: count = 0
while not count > 20:
if count == 20:
print(count)
else:
print(count, end = ', ')
count += 2
Example Write a program to evaluate obtain the sum of the rst 100 natural number.
That is
100
X
s= n
n=1
[32]: count = 1
s = 0
while count < 101:
s += count
count += 1
print(s)
5050
Example Write a program that uses a `while' loop to calculate the factorial of a positive
integer n provided by the user.
Enter an integer n: 6
720
15
Python and Mathematics by Donnie M. Kasyoki
`while' for validation Validation is the process of ensuring that the data one is using is
useful. In the case above for instance, the user may input a oat instead and that complecates
things resulting to semantic error. These are errors that cannot be detected easily since they
are not really bugs. The program runs normally. However, the output is not correct.
In the above case of calculating the factorial of a number n, we should force the user to input
an integer by using the `isdigit()' function and `while' loop.
[34]: number = input('Enter an integer n: ') #Use the input to get a str value
while not number.isdigit(): #Check if the entry contains all digits
number = input('Invalid entry. Enter a positive integer: ')
number = int(number) #Change from str to int type
factorial = 1 #initiate a product
count = 2
while count < number+1:
factorial *= count
count += 1
print(factorial)
Enter an integer n: -5
Invalid entry. Enter a positive integer: 5.0
Invalid entry. Enter a positive integer: 6
720
The division algorithm to nd gcd of two numbers Let a and b be positive integers.
The gcd(a, b) is the greatest common divisor of the two numbers. This can be obtained
using division algorithm.
If a < b, swap the values so a > b.
Dene r = a%b. If r = 0, stop the process and print b as the gcd.
If r != 0, redine a and b by setting a = b and b = r.
Repeat the same process until you obtain r = 0.
Example Write a program to calculate the gcd of two integers a and b provided by the
user. Ensure that they are both integers.
while not (a.isdigit() and b.isdigit()): #Check if the entry contains all
,→digits
16
Python and Mathematics by Donnie M. Kasyoki
a, b = b, a #Swapping ##step 1
while True:
r = a%b #defining r
if r == 0:
break#If r =0 we stop
else:
a, b = b, r #Redefining a and b ##Step 3
print(f'gcd({c}, {d}): {b}')
Exacise
6.1 Lists
List is another type of value. Elements of a list are enclosed in a pair of square brackets.
One may also choose to dene a list using the inbuilt `list' function. A list can take any
type of value as an item including lists themselves. The function `len' gives the number of
elements in a list.
Index of a list We access an item of a list using an index. The rst element of the list is
index 0, the next is 1, etc. We can also use reverse indexing that starts at index -1 which is
the last, -2 is the second last, etc.
Example
[36]: A = [] # L is an empty list
B = [90, 50, 'Hello', [9, 0, 1], 5]
print(f'Number of elements in B: {len(B)}')
print(f'The 1st item in list B: {B[0]}')
print(f'The second last item in list B: {B[-2]}')
print(f'The second item in the second last item of list B: {B[-2][1]}')
print(f"The fifth character of 'Hello' which is index 2 of B: {B[2][4]}")
Number of elements in B: 5
The 1st item in list B: 90
The second last item in list B: [9, 0, 1]
The second item in the second last item of list B: 0
The fifth character of 'Hello' which is index 2 of B: o
Sublists We can form sublists from the main lists. We will obtain these sublists using
index notations. For instance, the sublist ending at a certain position, the sublist begining
17
Python and Mathematics by Donnie M. Kasyoki
at a certain index, or sublist starting at a certain index and ending at a certain position.
Example Form a list L = [5, 3, 5, 6, 7, 10, 34, 56, 32, 12, 3, 4].
Print the rst ve items in the list.
Print the last six items in the list.
Print the items from index 4 to index 8 in the list.
[5, 3, 5, 6, 7]
[34, 56, 32, 12, 3, 4]
[7, 10, 34, 56, 32]
Append, overwrite, remove and delete a sublist Appending an item in a given list
adds a new item at the end of a list. To overwrite an item in the list, we simply assign the
the list index to the new value. The `remove' function is set to remove a specic item in the
list and removes the rst one that appears in the list. For instance, if a list contains more
that one 5's in a certain list, `remove(5)' will remove the one that has the smallest index.
To delete a sublist, all we have to do is assign the sublist to an empty list.
Example Use the list created above to answer the following questions:
Print the list.
Append 9 to the list.
Replace the item in index 10 with 10.
Remove three from the list.
Delete items starting from index 4 to index 8.
Print the new list.
18
Python and Mathematics by Donnie M. Kasyoki
Sort and shue Sorting a list requires a list of all numeral values or all string values.
Sorting an all strings list is done alphabetically or the reverse alphabetically. Numbers' lists
can also be done ascending and descending order.
To shue a list will recquire the shue function from the random module.
Example Sort the list in the above example in both ascending and descending order. Print
both sorted lists. Shue twice printing each time.
Exercise
6.2 Dictionaries
Dictionaries work more or less the same as lists but we use keys instead of indices. Items of
a dictionary are called using specic keys. ints, oats, str, bool, tuple can be used as Keys.
Lists, sets cannot be used as keys in a dictionary.
One can create a key by directly assigning it to a value. Unlike the keys, the value can be
any type of value.
Example Create a list of 1000 random integers between 1 and 100. Create and print a
dictionary that summarizes the grades using the grading system below:
A = 80 ≤ mark ≤ 100
B = 65 ≤ mark < 80
C = 50 ≤ mark < 65
D = 40 ≤ mark < 50
E = 0 ≤ mark < 40
19
Python and Mathematics by Donnie M. Kasyoki
[40]: from random import randint as rint #The function to get random integers
L = [] #initialize a list
for i in range(1000):
L.append(rint(1,100))
grades = []
for l in L:
if l >= 80:
grades.append('A')
elif l >= 65:
grades.append('B')
elif l >= 50:
grades.append('C')
elif l >= 40:
grades.append('D')
else:
grades.append('E')
gradesDic = {} #Initialize an empty dictionary.
for grade in grades:
if grade in gradesDic: #If the key exists,
gradesDic[grade] += 1 #Add one to the value.
else:
gradesDic[grade] = 1 #Create the key and enter the value as 1
print(f'grades = {gradesDic}')
print(f"A = {gradesDic['A']}") # The 'A's only
grades = {'A': 201, 'B': 155, 'E': 399, 'D': 83, 'C': 162}
A = 201
Exercise
6.3 Arrays
We are going to import several functions from numpy including `array' function. `zeros'
function is used to create an zero array of a specied dimension determined by the argument.
The `array' function takes a list and converts to an array. Let's look at a n-dimensional array
of size n × 1.
Example
Write a zero array of dimension 6. Overwrite the array by generating random integers
between 1 and 10 and placing at each index of the array to chnage it to a nonzero array.
20
Python and Mathematics by Donnie M. Kasyoki
for i in range(len(z)):
z[i] = rint(1,10)
print(f'z after overwiting: {z}')
arange and linspace functions The `arange' and `linspace' functions are used basically
for the same job only that their arguments defer by functionality.
We can use `arange' to create an array of numbers equidistant from the previous number. If
h is the common dierence from one number to the next, then h will take the third argument.
The starting number takes the rst argument and
Example Create an array of numbers between 0, 2 with a distance of 0.2 from a number
to the next. Use both `arange' and `linspace'.
arange array: [0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6 1.8 2. ]
linspace array: [0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6 1.8 2. ]
Exercise
7 Functions
We have already handled some inbuilt functions and gotten other functions from modules.
Some of these inbuilt functions include, `list' used to create lists, `len' for checking the size
of a list or dimension of an array, etc. Some of the functions from math module for instance
are `sqrt' for square root, `factorial' for factorial, etc.
In this subsection we will mainly focus on writing our own functions that we can use in our
program(s). We will introduce new keywords like `def' and `return'. We prefer returning
rather than printing when writing functions expecially maths functions because our interest
21
Python and Mathematics by Donnie M. Kasyoki
is sometimes getting the value rather than printing it. We can reuse the returned value to
perform operations but we cannot use it if we just print.
We can write a function that takes zero arguments or one that takes one or more arguments.
We will only focus on the ones that take at least one argument and a denite number of
arguments.
When calling a function, one can use positional arguments or key arguments. For positional
arguments one needs to know the position of the specic parameter as dened in a function.
For instance if the `def' statement is def function(x, y) then one must know what x and y
are and their positions and roles as per the denition. For key arguments one needs to know
the parameters used as arguments if it is x and y like in our case then one needs to have
that information. Order doesn't matter when dealing with key arguments. Let's look at the
following examples.
Example Write a function that returns the area of a circle of radius r. Where r is the
argument. Use the function dened to calculate the area of a circle whose radius is 10 units.
Example Write a function that returns the volume of a cylinder of radius r and height h.
Use the function to calculate the volume of a cylinder of radius 10 units and height 5 units.
[44]: def volume_cylinder(r, h): ##Parameters used are r and h so one must use
,→r and h for key arguments.
#positional arguments
print(f'Volume of a cylinder of radius 10 and height 5:
,→{volume_cylinder(10, 5)} cubic units.')
#key arguments
print(f'Volume of a cylinder of radius 10 and height 5:
,→{volume_cylinder(h = 5, r = 10)} cubic units.')
22
Python and Mathematics by Donnie M. Kasyoki
Example Write a function `sqr' to approximate the square root of a number a using
Newtons iteration method shown below:
We start with an approximate number, say y = a/2 (doesn't hav to be that). Find a new
approximate
y2 − a
ynew = yold − old
2yold
and compare with the previous approximate. If they are not the same nd another new
approximate using the same formula and compare. Do the same until you get equality of
the two approximates. The last approximate is the approximate square root of a.
return y_new
print(f'sqrt(64) = {sqr(64)}')
sqrt(64) = 8.0
Exercise Write a function gcd(a,b) that takes two arguments (positive integers) and re-
turns their gcd using division algorithm describes previously.
23
Python and Mathematics by Donnie M. Kasyoki
print(f'6! = {factorial(6)}')
6! = 720
Write a recurcive function seq(n) that returns the nth term of the sequence. Use the function
to nd the 10th term of the sequence.
Exercise Write a recursive function b(n) that returns the nth term of the Fibonaci se-
quence dened by:
F1 = 1, F2 = 1, Fn = Fn−1 + Fn−2 , n > 2.
Print the 20th term of the sequence
Write another function bRatio(n) that returns the ratio Fn
Fn−1
,n > 1.
Write a function bSum(n) that returns the sum of the rst n terms of the Fibonacci se-
quence.
8 CALCULUS IN PYTHON
In this chapter we will look at some basic elements of calculus and how we can use python
to solve some basic problems. We will look at limits, derivatives, integrals of functions.
24
Python and Mathematics by Donnie M. Kasyoki
f = (x-1)/(x**2-1)
lim = limit(f, x, 1)
print(lim)
1/2
x4 + 3x − 4
lim .
x→∞ x3 − x2
x2 + 3x − 4
lim−
x→1 |x2 − 1|
25
Python and Mathematics by Donnie M. Kasyoki
x2 + 3x − 4
lim
x→∞ x2 − 1
Use sympy to evaluate
x2 + 3x − 4
lim−
x→1 |x2 − 1|
Use sympy to evaluate
x2 + 3x − 4
lim+
x→1 |x2 − 1|
8.2 Derivatives
We are going to look at how we can nd derivatives both ordinary and partial derivatives.
Although the only dierence is the number of symbols we import from `sympy.abc'. In most
cases if the solution does not look simplied, it is recommended to use the `simplify' method
which is an attribute of any function dened symbolically. The `di' function is also an
attribute hence no need of importing it.
Example Use sympy to nd the derivative of the function f (x) = x2 +3x−4
x2 −1
.
Example Use sympy to nd the third derivative of the function f (t) = 3t · e2t dt.
12 · (2t + 3) e2t
26
Python and Mathematics by Donnie M. Kasyoki
[54]: #w.r.t t
from sympy import cos
from sympy.abc import t, x
f = 2*x*exp(2*t)-cos(t*x)
display(f.diff(t))
8.4 Integrals
Just like working with derivatives, we need to dene our functions with the necessary symbols
for integration. We will look at both indenite and denite integrals. We do a list of all the
examples below:
log (x2 + 1)
x atan (x) −
2
Example
R2
Use sympy to evaluate the following deinite integral 0
√ 1
4−2x
dx
27
Python and Mathematics by Donnie M. Kasyoki
Here we are going to look at factorization problems, roots of polynomials, solutions of si-
multaneous equations, and some matrix operations. All these will be done using the sympy
module as well.
a3 − a2 b − ab2 + b3
(a − b)2 (a + b)
a3 − 4a2 − 16a + 64
(a − 4)2 (a + 4)
{-1/2: 1, 1/3: 1, 0: 1}
28
Python and Mathematics by Donnie M. Kasyoki
x+y+z =6
3x + 2y + z = 10
x + 2y + z = 8
{x: 1, y: 2, z: 3}
c+d−e=0
2c − d − e = −1
The system does not have a unique solution. Therefore we will nd solution for two of the
variables.
9.4 Matrices
9.4.1 Determinants and inverses of invertible matrices
Example Write the following matrix, nd the determinant and its inverse.
1 0 −2
A = 0 3 1
1 −1 2
29
Python and Mathematics by Donnie M. Kasyoki
det(A) = 13
7 2 6
13 13 13
1 4 1
− 13
13 13
3 1 3
− 13 13 13
det(A) = {2: 2, 1: 1}
[(1,
1,
[Matrix([
[-2],
[ 1],
[ 0]])]),
(2,
2,
[Matrix([
[-1],
[ 1],
[ 0]]),
Matrix([
[-1],
[ 0],
[ 1]])])]
The set of eigenvectors is not always that pretty. Most of the times it looks very messy.
30
Python and Mathematics by Donnie M. Kasyoki
9.4.3 Diagonalization
Diagonalization does not always work on matrices. Especially when a matrix has an eigen
value whose multiplicity is greater than one and the number of independent eigenvectors
corresponding to such eigenvalue does not match the multiplicity.
The `diagonalize' function returns a tuple (P, D) where P is an invertible matrix and D is a
diagonal matrix such that A = P −1 DP , where A is the matrix in question.
Example Diagonalize matrix A and print the diagonal matrix D and nonsingular matrix
P such that A = P −1 DP :
0 −2 −2
A = 1 3 1
0 0 2
EQUATIONS
[66]: from sympy import Function, Eq, sin #importing the required functions.
from sympy.abc import x #import symbol x.
y = Function('y') #setting y as a function
de = Eq(y(x).diff(x,x)+2*y(x).diff(x)+y(x), x**2-sin(x))
31
Python and Mathematics by Donnie M. Kasyoki
display(de)
d d2
y(x) + 2 y(x) + 2 y(x) = x2 − sin (x)
dx dx
[67]: from sympy import Function, Eq, sin, cos, exp #importing the required
,→functions.
d
(ex + sin (y(x))) y(x) = −ey(x) + cos (x)
dx
Now that we can write the dierential equations, we can now solve them.
y ′′ − 5y ′ + 6y = x2 − 3x.
x2 2x 13
y(x) = C1 e2x + C2 e3x + − −
6 9 54
32
Python and Mathematics by Donnie M. Kasyoki
display(sol)
1
y(x) = log −
C1 − log (x) + Ci (x)
Initial Value Problem Initial conditions are written as a dictionary as part of the optional
arguments in dsolve function.
dy
= −2y, y(0) = 2
dx
y(x) = 2e−2x
10.1.1 Example
Solve the IVP below using dsolve:
33
Python and Mathematics by Donnie M. Kasyoki
line at each point. The smaller the steps the close we get to the actual solution as will be
demostrated in subsequent examples. We use the following formulars to obtain values of y
at every step. h is the step size.
import pylab as pl
pl.plot(x, y, label = 'Euler', color = 'green')
pl.plot(x, z, label = 'Exact', linewidth = 2, linestyle = '--')
pl.xlabel('$x$-axis')
pl.ylabel('$y$-axis')
pl.legend()
pl.show()
34
Python and Mathematics by Donnie M. Kasyoki
Example Use Euler's method to plot the solution of the IVP for 0 ≤ x ≤ 1 using Euler's
method.
dy
= 2y, y(0) = 2
dx
Use h = .01. In the same plot, plot the function y = 2e2x .
35
Python and Mathematics by Donnie M. Kasyoki
y[j] = y[j-1]+h*f[j-1]
f[j] = 2*y[j] #f(x, y) = 2y = dy/dx
z = 2*exp(2*x)
pl.plot(x, y, label = 'Euler', linewidth = 2, linestyle = '--')
pl.plot(x, z, color = 'green', label = '$y = 2e^{2x}$')
pl.xlabel('$x$-axis')
pl.ylabel('$y$-axis')
pl.legend()
pl.savefig('Euler.pdf')
36
Python and Mathematics by Donnie M. Kasyoki
k1 = hf (xn , yn )
h k1
k2 = hf xn + , yn +
2 2
h k2
k3 = hf xn + , yn +
2 2
k4 = hf (xn + h, yn + k3 )
1
yn+1 = yn + (k1 + 2k2 + 2k3 + k4 ) .
6
pl.xlabel('$x$')
pl.ylabel('$y(x)$')
pl.title("Solution by 4th order Runge-Kutta")
37
Python and Mathematics by Donnie M. Kasyoki
pl.legend();
38
Python and Mathematics by Donnie M. Kasyoki
39
Python and Mathematics by Donnie M. Kasyoki
40
Python and Mathematics by Donnie M. Kasyoki
Example Use scipy module to plot the solution of the IVP for 0 ≤ x ≤ 1 using 1001
points.
dy
= 2y, y(0) = 2.
dx
In the same graph, plot the function y = 2e2x .
x0 = 0
xn = 1
x = linspace(x0, xn, 1001)
y0 = 2 #initial condition
y = odeint(de, y0, x)
z = 2*exp(2*x)
41
Python and Mathematics by Donnie M. Kasyoki
Higher order IVPs For higher order initial value problems we need to reduce them to
a system of rst order IVPs. Then we create an array of this system and a tuple of initial
values before doing the numerical solution. Let's start with a case of second order ODE.
Condider the initial value problem
d2 y
= f (x, y, y ′ ), y(x0 ) = y0 , y ′ (x0 ) = y0′ .
dx2
To solve this we create a new variable say z = y ′ which implies that $ y'_0 = z_0, z' =
y' '$. So now we have a system of two rst order IVPs
z ′ = (f (x, y, z)
y ′ = z, z(x0 ) = z0 , y(x0 ) = y0
42
Python and Mathematics by Donnie M. Kasyoki
Example Using scipy and pylab plot the solution for 0 ≤ x ≤ 2 (use 1001 points) of the
IVP
7
y ′′ + 3y ′ + 2y = x2 , y(0) = , y ′ (0) = −1.
4
In the same graph, plot
x2 3x 7 1 −x 1 −2x
y= − + + e − e
2 2 4 2 2
43
Python and Mathematics by Donnie M. Kasyoki
Exercise.
1. Solve the IVP below using dsolve:
display(sol)
44
Python and Mathematics by Donnie M. Kasyoki
3. Plot the two solutions in one graph showing the dierence of the two plots.
plt.legend()
plt.savefig('scipy 3rd order.pdf')
45
Python and Mathematics by Donnie M. Kasyoki
Example Write a program to plot the graph showing Susceptible, Infected and Recovered
for a whole year given that
dS
= −βSI
dt
dI
= βSI − γI
dt
dR
= γI
dt
given that at time (days) t = 0, S = 1 − 10−5 , I = 1 − 10−5 , β = 0.8, γ = 0.1
46
Python and Mathematics by Donnie M. Kasyoki
47
Python and Mathematics by Donnie M. Kasyoki
Exercise Write a program to plot the graph showing Susceptible, Exposed, Infected and
Recovered for a whole year given that
dS
= −βSI
dt
dI
= βSI − γE
dt
dE
= γE − σI
dt
dR
= σI
dt
given that at time (days) t = 0, S = 1 − 10−5 , I = 1 − 10−5 , β = 0.8, γ = 0.1, σ = 0.2
48