Mathematics in Python
Mathematics in Python
blog
Mathematics in
Python
Hans-Petter Halvorsen
Free Textbook with lots of Practical Examples
https://www.halvorsen.blog/documents/programming/python/
Additional Python Resources
https://www.halvorsen.blog/documents/programming/python/
Mathematics in Python
• Python is a powerful tool for mathematical
calculations
• Python Standard Library
– math Module
– statistics Module
• NumPy Library
Contents
• Python Standard Library and Basic Math
Functions
• NumPy Library
• Statistics
• Trigonometric Functions
• Polynomials
• Complex Numbers
Python Editors
• Python IDLE
• Spyder (Anaconda distribution)
• PyCharm
• Visual Studio Code
• Visual Studio
• Jupyter Notebook
• …
Spyder (Anaconda distribution)
Run Program button
Console window
Calculations in Python
We can use variables in a calculation like this:
𝑦(𝑥) = 2𝑥 + 4
> a = 2
> b = 4
𝑦(3) = ? > x = 3
> y = a*x + b 𝑦(𝑥) = 𝑎𝑥 + 𝑏
> print(y)
𝑦(5) = ? > x = 5
> y = a*x + b
> print(y)
Python Standard Library
• Python allows you to split your program into modules
that can be reused in other Python programs. It comes
with a large collection of standard modules that you
can use as the basis of your programs.
• The Python Standard Library consists of different
modules for handling file I/O, basic mathematics, etc.
• You don't need to install the modules in the Python
Standard Library separately, but you need to important
them when you want to use some of these modules or
some of the functions within these modules.
math Module
Python Standard Library
• math.exp(x) y = mt.exp(x)
• math.log(x) print(y)
• math.log10(x)
y = mt.log(x)
• math.pow(x,y) print(y)
• math. sqrt(x)
• … y = mt.log10(x)
print(y)
n = 2
y = mt.pow(x,n)
https://docs.python.org/3/library/math.html print(y)
Mathematical Expressions
Let's create the following mathematical expression in Python:
𝑓(𝑥, 𝑦) = 3𝑥 ! + 𝑥 ! + 𝑦 ! + 𝑒 "#(%)
𝑓 2,2 =?
Python Code:
import math as mt
x = 2
y = 2
print(f)
𝑓(𝑥, 𝑦) = 3𝑥 ! + 𝑥 ! + 𝑦 ! + 𝑒 "#(%)
Python Code:
import math as mt
def func_ex(x,y):
f = 3*mt.pow(x,2) + mt.sqrt(mt.pow(x,2) + mt.pow(y,2)) + mt.exp(mt.log(x))
return f
x = 2
y = 2
f = func_ex(x,y)
print(f)
NumPy
• The Python Standard Library consists basic Math
functions, for fore advanced Math functions, you
typically want to use the NumPy Library
• If you don’t have Python yet and want the
simplest way to get started, you can use the
Anaconda Distribution - it includes Python,
NumPy, and other commonly used packages for
scientific computing and data science.
• Or use “pip install numpy“ https://numpy.org
NumPy
Basic NumPy Example: In this example we use both the math module in the
import numpy as np Python Standard Library and the NumPy library:
x = 3 import math as mt
import numpy as np
y = np.sin(x)
x = 3
print(y)
y = mt.sin(x)
print(y)
def func_ex(x,y):
f = 3*np.power(x,2) + np.sqrt(np.power(x,2) + np.power(y,2)) + np.exp(np.log(x))
return f
x = 2
y = 2
f = func_ex(x,y)
print(f)
The answer becomes 𝑓(2,2) = 16.83
Mathematical Expressions
import numpy as np
𝑓(𝑥, 𝑦) = 3𝑥 ! + 𝑥 ! + 𝑦 ! + 𝑒 "#(%)
def func_ex(x,y):
f = 3*np.power(x,2) + np.sqrt(np.power(x,2) +
np.power(y,2)) + np.exp(np.log(x))
Let's find the values of 𝑓(𝑥, 𝑦) for return f
0 ≤ 𝑥 ≤ 10 and 0 ≤ 𝑦 ≤ 10
start = 0
In order to do that we can use a stop = 11
increment = 1
Nested For loop:
x_data = np.arange(start,stop,increment)
y_data = np.arange(start,stop,increment)
for x in x_data:
for y in y_data:
f = func_ex(x,y)
print(f"f({x},{y})={f}")
Statistics
• Mean / Average The mean is the sum of the data divided by the
• Variance number of data points. It is commonly called
"the average”:
• Standard Deviation (
𝑥' + 𝑥! + ⋯ + 𝑥( 1
• Median 𝜇 = 𝑥̅ =
𝑁
= : 𝑥)
𝑁
)*'
The standard deviation is a measure of the Variance is a measure of the
spread of the values in a dataset or the variation in a data set:
value of a random variable. It is defined as (
the square root of the variance: 1
𝑣𝑎𝑟 𝑥 = 𝜎 ! = : 𝑥) − 𝑥̅ !
( 𝑁
)*'
1 !
𝜎= : 𝑥) − 𝑥̅
𝑁 𝜎 ! = 𝑣𝑎𝑟 𝑥 ⇔ 𝜎 = 𝑣𝑎𝑟 𝑥
)*'
Median
Given the following dataset:
data = [-1.0, 11, 2.5, 3.25, 5.75]
If even numbers in the dataset: The Median is the value in the middle
data = [-1.0, 11, 2.5, 3.25]
# Median
IMPORTANT: Do not name your file med = st.median(data)
print(med)
"statistics.py" since the import will be
confused and throw the errors of the # Variance
library not existing and the mean function var = st.variance(data)
not existing. print(var)
Trigonometric Functions
• Python offers lots of Trigonometric functions,
e.g., sin, cos, tan, etc.
• Note! Most of the trigonometric functions
require that the angle is expressed in radians.
• We can use Math module in the Python
Standard Library
• Or we can use the NumPy library
Trigonometric Functions
Trigonometric functions in the Math module in the Python Standard Library:
import math as mt
x = 2*mt.pi
y = mt.sin(x)
print(y)
y = mt.cos(x)
print(y)
y = mt.tan(x)
print(y)
Trigonometric Functions
Plotting Example using a For Loop and the matplotlib library:
import math as mt
import matplotlib.pyplot as plt
xdata = []
ydata = []
plt.plot(xdata, ydata)
plt.show()
Trigonometric Functions
Improved Plotting Example: “Smoother“ curve:
import math as mt
import matplotlib.pyplot as plt
x = 0
N = 100
xdata = []
ydata = []
xstart = 0
xstop = 2*np.pi
increment = 0.1
x = np.arange(xstart,xstop,increment)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Trigonometric Functions
You can also plot multiple plots like this:
import numpy as np
import matplotlib.pyplot as plt
xstart = 0
xstop = 2*np.pi
increment = 0.1
x = np.arange(xstart,xstop,increment)
y1 = np.sin(x)
y2 = np.cos(x)
xstart = 0
xstop = 2*np.pi
increment = 0.1
x = np.arange(xstart,xstop,increment)
x_deg = r2d(x)
y = np.sin(x)
plt.plot(x_deg, y)
plt.xlabel("x in degrees")
plt.axis([0, 360, -1, 1])
plt.grid()
Polynomials
A polynomial is expressed as:
https://numpy.org/doc/stable/reference/routines.polynomials.polynomial.html
Polynomials
Given the following polynomial:
𝑝 𝑥 = −5.45𝑥 + + 3.2𝑥 ! + 8𝑥 + 5.6
r = poly.polyroots(p)
𝑝 𝑥 = 0 → 𝑥 =?
print(r)
Polynomials
Given the following polynomial:
𝑝 𝑥 = −2.1𝑥 + + 2𝑥 , + 5𝑥 + 11
p = [11, 5, 0, 2, -2.1]
r = poly.polyroots(p) 𝑝 𝑥 = 0 → 𝑥 =?
print(r)
x = 2
px = poly.polyval(x, p) 𝑝 2 =?
print(px)
import numpy.polynomial.polynomial as poly
Polynomials
Given the following
p1 = [1, 1, -1] polynomials:
p2 = [2, 0, 0, 1]
𝑝' 𝑥 = 1 + 𝑥 − 𝑥 !
p = poly.polymul(p1, p2)
𝑝! 𝑥 = 2 + 𝑥 ,
print(p)
plt.plot(x, y)
N = 3
p = poly.polyfit(x,y,N)
print(p)
y2 = poly.polyval(x, p)
plt.plot(x, y2)
plt.show()
Polynomial Fitting
Find a Polynomial that best fits the following function:
𝑦 = sin(𝑥)
N = 3
N = 5
𝑅𝑒(𝑧) = 𝑎, 𝐼𝑚(𝑧) = 𝑏
𝑗 = −1
z = 3 + 2j
Complex Numbers – Polar Form
Complex numbers can also be expressed on exponential/polar form:
𝑧 = 𝑟𝑒 '(
Where: 𝑟= 𝑧 = 𝑎! +𝑏 !
𝑏
𝜃 = 𝑎𝑡𝑎𝑛
𝑎
https://www.halvorsen.blog/documents/programming/python/
Hans-Petter Halvorsen
University of South-Eastern Norway
www.usn.no
E-mail: [email protected]
Web: https://www.halvorsen.blog