100% found this document useful (1 vote)
284 views

Mathematics in Python

This document provides an overview of using Python for mathematics and statistics. It discusses the Python standard library modules for basic math functions like sin(), log(), and pow(). It also introduces the NumPy library for more advanced mathematical functions and operations on arrays. The document gives examples of calculating mathematical expressions and using statistics functions from these modules to find the mean, median, variance and standard deviation of datasets.

Uploaded by

Tarek Wakim
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
284 views

Mathematics in Python

This document provides an overview of using Python for mathematics and statistics. It discusses the Python standard library modules for basic math functions like sin(), log(), and pow(). It also introduces the NumPy library for more advanced mathematical functions and operations on arrays. The document gives examples of calculating mathematical expressions and using statistics functions from these modules to find the mean, median, variance and standard deviation of datasets.

Uploaded by

Tarek Wakim
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

https://www.halvorsen.

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

Variable Explorer window


https://www.anaconda.com
Code Editor window

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

The math module has all the basic math


functions you need, such as:
• Trigonometric functions: sin(x), cos(x), etc.
• Logarithmic functions: log(), log10(), etc.
• Statistics: mean(), stdev(), etc.
• Constants like pi, e, inf, nan, etc.
math Module
If we need only the sin() function, we can do like this: from math import sin

If we need many functions, we can do like this: x = 3.14


y = sin(x)
from math import *
If we need a few functions, we can do like this:
x = pi from math import sin, cos
y = sin(x)
print(y) x = 3.14
y = sin(x) We can also do like this:
y = cos(x) print(y) import math
print(y) x = 3.14
y = cos(x) y = math.sin(x)
… print(y) print(y)
Basic Math Functions
Some basic math functions in Some basic Examples: import math as mt
Python Standard Library:
x = 3

• 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

f = 3*mt.pow(x,2) + mt.sqrt(mt.pow(x,2) + mt.pow(y,2)) + mt.exp(mt.log(x))

print(f)

The answer becomes 𝑓(2,2) = 16.83


Mathematical Expressions
Let's create a function that calculates the following mathematical expression:

𝑓(𝑥, 𝑦) = 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)

As you see, NumPy also have also similar functions y = np.sin(x)


(e.g., sim(), cos(), etc.) as those who is part of the print(y)
math library, but they are more powerful
Mathematical Expressions
Let's create the following mathematical expression in Python using NumPy:

𝑓(𝑥, 𝑦) = 3𝑥 ! + 𝑥 ! + 𝑦 ! + 𝑒 "#(%) 𝑓 2,2 =?

Python Code: Previously we used math in the Python Standard Library


import numpy as np

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]

Put them in ascending order:

data = [-1.0, 2.5, 3.25, 5.75, 11]

If even numbers in the dataset: The Median is the value in the middle
data = [-1.0, 11, 2.5, 3.25]

Put them in ascending order: The Median will be:


data = [-1.0, 2.5, 3.25, 11]
(2.5 + 3.25)/2 = 2.875
Statistics import statistics as st

data = [-1.0, 11, 2.5, 3.25, 5.75]

Example: #Mean or Average


m = st.mean(data)
Statistics using the statistics module in print(m)
Python Standard Library:
# Standard Deviation
st_dev = st.stdev(data)
print(st_dev)

# 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 = []

for x in range(0, 10):


xdata.append(x)
y = mt.sin(x)
ydata.append(y)

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 = []

for i in range(0, N):


x = x + 0.1
xdata.append(x)
y = mt.sin(x)
ydata.append(y) The problem with using the Trigonometric functions in the
the Math module from the Python Standard Library is that
plt.plot(xdata, ydata) they don't handle an array as input.
plt.show()
Trigonometric Functions
Using NumPy: The Trigonometric Functions in the
NumPy library can handle arrays as
import numpy as np input arguments. No For Loop needed!
import matplotlib.pyplot as plt

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)

plt.plot(x, y1, x, y2)


plt.legend(["sin(x)", "cos(x)"])
plt.show()
Trigonometric Functions
Converting to degrees (x-axis):
import numpy as np Here I have created my own Function r2d(r)
import matplotlib.pyplot as plt
You could have used math.degrees(x)
def r2d(r):
d = r * (180/np.pi)
return d

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:

𝑝 𝑥 = 𝑝! 𝑥 " + 𝑝# 𝑥 "$! + ⋯ + 𝑝" 𝑥 + 𝑝"%!

where 𝑝! , 𝑝# , 𝑝& , … are the coefficients of the polynomial.

We will use the Polynomial Module in the NumPy Package.

https://numpy.org/doc/stable/reference/routines.polynomials.polynomial.html
Polynomials
Given the following polynomial:
𝑝 𝑥 = −5.45𝑥 + + 3.2𝑥 ! + 8𝑥 + 5.6

We need to rewrite it like this in Python:


𝑝 𝑥 = 5.6 + 8𝑥 + 3.2𝑥 ! + 0𝑥 , −5.45𝑥 +

import numpy.polynomial.polynomial as poly

p = [5.6, 8, 3.2, 0, -5.45]

r = poly.polyroots(p)
𝑝 𝑥 = 0 → 𝑥 =?
print(r)
Polynomials
Given the following polynomial:
𝑝 𝑥 = −2.1𝑥 + + 2𝑥 , + 5𝑥 + 11

We need to rewrite it like this in Python:


𝑝 𝑥 = 11 + 5𝑥 + 0𝑥 ! + 2𝑥 , − 2.1𝑥 +

import numpy.polynomial.polynomial as poly

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)

r = poly.polyroots(p) Let's find the polynomial 𝑝(𝑥) =


print(r) 𝑝' (𝑥) C 𝑝! (𝑥) using Python

x = 2 And let's find the roots of the


px = poly.polyval(x, p) polynomial
print(px) 𝑝 𝑥 =0
Polynomial Fitting import numpy as np
import numpy.polynomial.polynomial as poly
Find a Polynomial that best fits the following import matplotlib.pyplot as plt
function:
xstart = 0
𝑦 = sin(𝑥) xstop = 2*np.pi
increment = 0.1
Try with different order of the polynom
x = np.arange(xstart,xstop,increment)
N = 3 y = np.sin(x)

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

[ 0.01223516 0.87014661 0.27985151 -0.39981223 0.08841641 -0.0056342 ]

𝑝 𝑥 = 0.01 + 0.87𝑥 + 0.28𝑥 ! − 0.4𝑥 " + 0.09𝑥 # − 0.006𝑥 $

[-0.18215486 1.88791463 -0.87536931 0.09309684]


𝑝 𝑥 = −0.18 + 1.88𝑥 − 0.88𝑥 ! + 0.09𝑥 ,
Complex Numbers
A complex number is defined like this: 𝑧 = 𝑎 + 𝑗𝑏
Where 𝑎 is called the real part of 𝑧 and 𝑏 is called the imaginary part of 𝑧, i.e.:

𝑅𝑒(𝑧) = 𝑎, 𝐼𝑚(𝑧) = 𝑏

The imaginary 𝑗 is defined as:

𝑗 = −1

In Python you define a complex number like this:

z = 3 + 2j
Complex Numbers – Polar Form
Complex numbers can also be expressed on exponential/polar form:

𝑧 = 𝑟𝑒 '(
Where: 𝑟= 𝑧 = 𝑎! +𝑏 !
𝑏
𝜃 = 𝑎𝑡𝑎𝑛
𝑎

Note that 𝑎 = 𝑟 cos 𝜃 and 𝑏 = 𝑟 sin 𝜃


Complex Numbers
a = 5 + 3j
Given the following complex b = 1 - 1j
numbers: c = a + b
𝑎 = 5 + 3𝑗 print(c)
𝑏 = 1 − 1𝑗 d = a - b
print(d)
In Python we can define the complex e = a * b
numbers and perform basic print(e)
operations (+, -, *, /) like this:
f = a / b
print(f)
Complex Numbers
import cmath
In addition, there exists several
x = 2
Complex Number Functions in y = -3
Python. We use the cmath library:
cmath.phase(x) # converting x and y into complex number
cmath.polar(x) z = complex(x,y)
cmath.rect(r, phi) print(z.real)
cmath.exp(x) print(z.imag)
cmath.log10(x)
cmath.sqrt(x) print(z.conjugate())
cmath.acos(x)
cmath.asin(x) # converting to polar form
cmath.atan(x) w = cmath.polar(z)
cmath.cos(x) print (w)
cmath.sin(x)
cmath.tan(x) # converting to to rectangular form
w = cmath.rect(2,3)
https://docs.python.org/3/library/cmath.html print (w)
Advanced Mathematics
• Linear Algebra
• Complex Numbers
• Differential Equations
• Interpolation
• Curve Fitting
• Least Square Method
• Numerical Differentiation
• Numerical Integration
• Optimization
Additional Python Resources

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

You might also like