Python Programming-113-140
Python Programming-113-140
Jupyter Notebook
The Jupyter Notebook is an open-source web application that allows you to cre-
ate and share documents that contain live code, equations, visualizations and
text.
The Notebook has support for over 40 programming languages, including Python.
Web:
http://jupyter.org
Wikipedia:
https://en.wikipedia.org/wiki/ProjectJ upyter
110
22.1 JupyterHub
JupyterHub is a multi-user version of the notebook designed for companies,
classrooms and research labs [17].
Web:
http://jupyter.org/hub
The good thing about Microsoft Azure Notebooks is that you have the infras-
tructure and everything up and running ready for you to use. You can use it
for free as well.
Web:
https://notebooks.azure.com
[End of Example]
111
Figure 22.3: Azure Notebook Project Notebooks
112
Part V
113
Chapter 23
Mathematics in Python
If you are looking for similar using MATLAB, please take a look at these re-
sources:
https://www.halvorsen.blog/documents/programming/matlab/
In this chapter we will focus on the math module that is part of the Python
Standard Library.
The math module has all the basic math functions you need, such as: Trigono-
metric functions: sin(x), cos(x), etc. Logarithmic functions: log(), log10(), etc.
Constants like pi, e, inf, nan, etc. etc.
114
1 from math im por t s i n , c o s
2
3 x = 3.14
4 y = sin (x)
5 print (y)
6
7 y = cos (x)
8 print (y)
[End of Example]
There are advantages and disadvantages with the different approaches. In your
program you may need to use functions from many different modules or pack-
ages. If you import the whole module instead of just the function(s) you need
you use more of the computer memory.
Very often we also need to import and use multiple libraries where the different
libraries have some functions with the same name but different use.
Other useful modules in the Python Standard Library are statistics (where
you have functions like mean(), stdev(), etc.)
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/
115
23.1.1 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
[End of Exercise]
ln (ax2 + bx + c) − sin(ax2 + bx + c)
f (x) = (23.2)
4πx2 + cos(x − 2)(ax2 + bx + c)
Tip! You should split the expressions into different parts, such as:
poly = ax2 + bx + c
num = . . .
den = . . .
f = ...
This makes the expression simpler to read and understand, and you minimize
the risk of making an error while typing the expression in Python.
When you got the correct answer try to change to, e.g., a = 2, b = 8, c = 6
Find f (9)
[End of Exercise]
116
Figure 23.1: Right-angled triangle
c2 = a2 + b2 (23.3)
1 def pythagoras (a , b)
2 ...
3 ...
4 return c
[End of Exercise]
E = mc2 (23.4)
Calculate how much of the mass on the sun is used to create this energy per day.
How many years will it take to convert all the mass of the sun completely? Do
we need to worry if the sun will be used up in our generation or the next? justify
the answer.
117
[End of Exercise]
[End of Exercise]
23.2 Statistics
23.2.1 Introduction to Statistics
Mean or average:
The mean is the sum of the data divided by the number of data points. It is
commonly called “the average”,
Mean:
N
1 X 2.2 + 4.5 + 6.2 + 3.6 + 2.6 19.1
x̄ = xi = = = 3.82 (23.6)
N i=1 5 5
118
[End of Example]
Variance:
N
1 X
var(x) = (xi − x̄)2 (23.7)
N i=1
Standard deviation:
The standard deviation is a measure of the spread of the values in a dataset
or the value of a random variable. It is defined as the square root of the variance.
v
u N
√ u1 X
std(x) = σ = var = t (xi − x̄)2 (23.8)
N i=1
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/
1 im po rt s t a t i s t i c s a s s t
2
3 data = [ − 1 . 0 , 2 . 5 , 3 . 2 5 , 5 . 7 5 ]
4
5 #Mean o r Average
6 m = s t . mean ( data )
7 p r i n t (m)
8
9 # Standard D e v i a t i o n
10 s t d e v = s t . s t d e v ( data )
119
11 print ( st dev )
12
13 # Median
14 med = s t . median ( data )
15 p r i n t ( med )
16
17 # Variance
18 v a r = s t . v a r i a n c e ( data )
19 p r i n t ( var )
Listing 23.1: Statistics functions in Python
[End of Example]
IMPORTANT: Do not name your file ”statistics.py” since the import will be
confused and throw the errors of the library not existing and the mean function
not existing.
You can also use the NumPy Library. NumPy is the fundamental package for
scientific computing with Python.
Below you find some examples how to use some of the statistics functions in
NumPy:
1 im po rt numpy a s np
2
3 data = [ − 1 . 0 , 2 . 5 , 3 . 2 5 , 5 . 7 5 ]
4
5 #Mean o r Average
6 m = np . mean ( data )
7 p r i n t (m)
8
9 # Standard D e v i a t i o n
10 s t d e v = np . s t d ( data )
11 print ( st dev )
12
13 # Median
14 med = np . median ( data )
15 p r i n t ( med )
16
17 # Minimum Value
18 minv = np . min ( data )
19 p r i n t ( minv )
20
21 # Maxumum Value
22 maxv = np . max( data )
23 p r i n t ( maxv )
Listing 23.2: Statistics using the NumPy Library
120
[End of Example]
Create your own Statistics Module in Python (e.g., ”mystatistics.py) and then
create a Python Script (e.g., ”testmystatistics.py) where you test these func-
tions.
You should at least implement functions for mean, variance, standard deviation,
minimum and maximum.
[End of Exercise]
Note! Most of the trigonometric functions require that the angle is expressed in
radians.
Example 23.3.1. Trigonometric Functions in Math module
1 im po rt math a s mt
2
3 x = 2∗mt . p i
4
5 y = mt . s i n ( x )
6 print (y)
7
8 y = mt . c o s ( x )
9 print (y)
10
11 y = mt . tan ( x )
12 print (y)
Listing 23.3: Trigonometric Functions in Math module
Here we have used the Math module in the Python Standard Library.
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/index.html
121
[End of Example]
1 im po rt math a s mt
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 xdata = [ ]
5 ydata = [ ]
6
7 f o r x in range (0 , 10) :
8 xdata . append ( x )
9 y = mt . s i n ( x )
10 ydata . append ( y )
11
12 p l t . p l o t ( xdata , ydata )
13 p l t . show ( )
Listing 23.4: Plotting Trigonometric Functions
In the example we have plotted sin(x), we can easily extend the program to plot
cos(x), etc.
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/index.html
[End of Example]
We will use the NumPy library instead because they handle arrays, in addition
to all the handy functionality in the NumPy library.
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 xstart = 0
5 x s t o p = 2∗ np . p i
6 increment = 0.1
7
8 x = np . a r a n g e ( x s t a r t , xstop , i n c r e m e n t )
9
10 y = np . s i n ( x )
122
11 plt . plot (x , y)
12 plt . t i t l e ( ’ y=s i n ( x ) ’ )
13 plt . xlabel ( ’x ’ )
14 plt . ylabel ( ’y ’ )
15 plt . grid ()
16 plt . a x i s ( [ 0 , 2∗ np . pi , −1, 1 ] )
17 plt . show ( )
18
19 y = np . c o s ( x )
20 plt . plot (x , y)
21 p l t . t i t l e ( ’ y=c o s ( x ) ’ )
22 plt . xlabel ( ’x ’ )
23 plt . ylabel ( ’y ’ )
24 plt . grid ()
25 p l t . a x i s ( [ 0 , 2∗ np . pi , −1, 1 ] )
26 p l t . show ( )
27
28 y = np . tan ( x )
29 plt . plot (x , y)
30 p l t . t i t l e ( ’ y=tan ( x ) ’ )
31 plt . xlabel ( ’x ’ )
32 plt . ylabel ( ’y ’ )
33 plt . grid ()
34 p l t . a x i s ( [ 0 , 2∗ np . pi , −1, 1 ] )
35 p l t . show ( )
Listing 23.5: Trigonometric Functions using NumPy
[End of Example]
We have that:
123
These functions should be saved in one Python file .py.
[End of Exercise]
Create a function that finds the angle A (in degrees) based on input arguments
(a,c), (b,c) and (a,b) respectively.
Use, e.g., a third input “type” to define the different types above.
Use you previous function r2d() to make sure the output of your function is in
degrees and not in radians.
a a
sin(A) = → A = arcsin( ) (23.12)
c c
b b
cos(A) = → A = arccos( ) (23.13)
c c
a a
tan(A) = → A = arctan( ) (23.14)
b b
c2 = a2 + b2 (23.15)
1 >>> a=5
2 >>> b=8
3 >>> c = s q r t ( a ∗∗2 + b ∗ ∗ 2 )
4
5 >>> A = r i g h t t r i a n g l e ( a , c , ’ s i n ’ )
6 A =
7 32.0054
8
9 >>> A = r i g h t t r i a n g l e ( b , c , ’ c o s ’ )
10 A =
11 32.0054
12 >>> A = r i g h t t r i a n g l e ( a , b , ’ tan ’ )
13 A =
14 32.0054
We also see that the answer in this case is the same, which is expected.
124
[End of Exercise]
[End of Exercise]
Plot sin(θ) and cos(θ) for 0 ≤ θ ≤ 2π in the same plot (both in the same plot
and in 2 different subplots).
Make sure to add labels and a legend and use different line styles and colors for
the plots.
[End of Exercise]
23.4 Polynomials
A polynomial is expressed as:
Web:
https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.polynomials.polynomial.html
Other Resources:
125
126
127
Part VI
Resources
128
Chapter 24
Python Resources
SciPy Library:
https://www.scipy.org
Matplotlib Library:
https://matplotlib.org
129
Visual studio Code:
https://code.visualstudio.com
Visual Studio:
https://visualstudio.microsoft.com
PyCharm:
https://www.jetbrains.com/pycharm/
Wing:
https://wingware.com
Jupyter Notebook:
http://jupyter.org
130
Bibliography
131
[18] python.org, “The python standard library -
https://docs.python.org/3/library/,” 2018.
132
Part VII
Solutions to Exercises
133
Start using Python
Create a Script in Python (.py file) where you plot the solution x(t) in the time
interval:
0 ≤ t ≤ 25
Add Grid, and proper Title and Axis Labels to the plot.
Python Script:
1 im po rt math a s mt
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5
6 # Model P a r a m e t e r s
7 T = 5
8 a = −1/T
9
10 # Simulation Parameters
11 x0 = 1
12 t = 0
13
14 tstart = 0
134
15 t s t o p = 25
16
17 increment = 1
18
19 x = []
20 x = np . z e r o s ( t s t o p +1)
21
22 t = np . a r a n g e ( t s t a r t , t s t o p +1 , i n c r e m e n t )
23
24
25 # Define the Function
26 f o r k in range ( tstop ) :
27 x [ k ] = mt . exp ( a ∗ t [ k ] ) ∗ x0
28
29
30 # Plot the Simulation Results
31 plt . plot (t , x)
32 p l t . t i t l e ( ’ S i m u l a t i o n o f Dynamic System ’ )
33 plt . xlabel ( ’ t ’ )
34 plt . ylabel ( ’x ’ )
35 plt . grid ()
36 p l t . a x i s ( [ 0 , 25 , 0 , 1 ] )
37 p l t . show ( )
[End of Exercise]
135
Python Programming
c Hans-Petter Halvorsen
ISBN:978-82-691106-4-7
136
Python Programming