Mathematics In Python - Halvorsen.blog

Transcription

https://www.halvorsen.blogMathematics inPythonHans-Petter Halvorsen

Free Textbook with lots of Practical amming/python/

Additional Python ramming/python/

Mathematics in Python Python is a powerful tool for mathematicalcalculations Python Standard Library– math Module– statistics Module NumPy Library

Contents Python Standard Library and Basic MathFunctions NumPy Library Statistics Trigonometric Functions Polynomials Complex Numbers

Python Editors Python IDLESpyder (Anaconda distribution)PyCharmVisual Studio CodeVisual StudioJupyter Notebook

Spyder (Anaconda distribution)Run Program buttonVariable Explorer windowCode Editor windowhttps://www.anaconda.comConsole window

Calculations in PythonWe can use variables in a calculation like this:𝑦(π‘₯) 2π‘₯ 4 a 2 b 4𝑦(3) ?𝑦(5) ? x 3 y a*x b print(y) x 5 y a*x b print(y)𝑦(π‘₯) π‘Žπ‘₯ 𝑏

Python Standard Library Python allows you to split your program into modulesthat can be reused in other Python programs. It comeswith a large collection of standard modules that youcan use as the basis of your programs. The Python Standard Library consists of differentmodules for handling file I/O, basic mathematics, etc. You don't need to install the modules in the PythonStandard Library separately, but you need to importantthem when you want to use some of these modules orsome of the functions within these modules.

math ModulePython Standard LibraryThe math module has all the basic mathfunctions 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 ModuleIf we need only the sin() function, we can do like this:If we need many functions, we can do like this:from math import *x piy sin(x)print(y)y cos(x)print(y) from math import sinx 3.14y sin(x)If we need a few functions, we can do like this:from math import sin, cosx 3.14y sin(x)print(y)y cos(x)print(y)We can also do like this:import mathx 3.14y math.sin(x)print(y)

Basic Math FunctionsSome basic math functions inPython Standard Library: Some basic Examples: import math as math. sqrt(x) https://docs.python.org/3/library/math.htmlx 3y mt.exp(x)print(y)y mt.log(x)print(y)y mt.log10(x)print(y)n 2y mt.pow(x,n)print(y)

Mathematical ExpressionsLet's create the following mathematical expression in Python:𝑓(π‘₯, 𝑦) 3π‘₯ ! Python Code:π‘₯ ! 𝑦 ! 𝑒 "#(%)𝑓 2,2 ?import math as mtx 2y 2f 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 ExpressionsLet's create a function that calculates the following mathematical expression:𝑓(π‘₯, 𝑦) 3π‘₯ ! π‘₯ ! 𝑦 ! 𝑒 "#(%)Python Code:import math as mtdef 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 fx 2y 2f func ex(x,y)print(f)

NumPy The Python Standard Library consists basic Mathfunctions, for fore advanced Math functions, youtypically want to use the NumPy Library If you don’t have Python yet and want thesimplest way to get started, you can use theAnaconda Distribution - it includes Python,NumPy, and other commonly used packages forscientific computing and data science. Or use β€œpip install numpyβ€œhttps://numpy.org

NumPyBasic NumPy Example:import numpy as npIn this example we use both the math module in thePython Standard Library and the NumPy library:import math as mtimport numpy as npx 3y np.sin(x)print(y)As you see, NumPy also have also similar functions(e.g., sim(), cos(), etc.) as those who is part of themath library, but they are more powerfulx 3y mt.sin(x)print(y)y np.sin(x)print(y)

Mathematical ExpressionsLet's create the following mathematical expression in Python using NumPy:𝑓(π‘₯, 𝑦) 3π‘₯ ! Python Code:π‘₯ ! 𝑦 ! 𝑒 "#(%)𝑓 2,2 ?Previously we used math in the Python Standard Libraryimport numpy as npdef 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 fx 2y 2f func ex(x,y)print(f)The answer becomes 𝑓(2,2) 16.83

Mathematical Expressions𝑓(π‘₯, 𝑦) 3π‘₯ ! π‘₯ ! 𝑦 ! 𝑒 "#(%)Let's find the values of 𝑓(π‘₯, 𝑦) for0 π‘₯ 10 and 0 𝑦 10In order to do that we can use aNested For loop:import numpy as npdef 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 fstart 0stop 11increment 1x 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 / AverageVarianceStandard DeviationMedianThe mean is the sum of the data divided by thenumber of data points. It is commonly called"the average”:(πœ‡ π‘₯Μ… The standard deviation is a measure of thespread of the values in a dataset or thevalue of a random variable. It is defined asthe square root of the variance:π‘₯' π‘₯! π‘₯( 1 : π‘₯)𝑁𝑁)*'Variance is a measure of thevariation in a data set:(π‘£π‘Žπ‘Ÿ π‘₯ 𝜎 ! (𝜎 1: π‘₯) π‘₯̅𝑁)*'1: π‘₯) π‘₯̅𝑁)*'!𝜎 ! π‘£π‘Žπ‘Ÿ π‘₯ 𝜎 π‘£π‘Žπ‘Ÿ π‘₯!

MedianGiven 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 middledata [-1.0, 11, 2.5, 3.25]Put them in ascending order:data [-1.0, 2.5, 3.25, 11]The Median will be:(2.5 3.25)/2 2.875

StatisticsExample:Statistics using the statistics module inPython Standard Library:IMPORTANT: Do not name your file"statistics.py" since the import will beconfused and throw the errors of thelibrary not existing and the mean functionnot existing.import statistics as stdata [-1.0, 11, 2.5, 3.25, 5.75]#Mean or Averagem st.mean(data)print(m)# Standard Deviationst dev st.stdev(data)print(st dev)# Medianmed st.median(data)print(med)# Variancevar st.variance(data)print(var)

Trigonometric Functions Python offers lots of Trigonometric functions,e.g., sin, cos, tan, etc. Note! Most of the trigonometric functionsrequire that the angle is expressed in radians. We can use Math module in the PythonStandard Library Or we can use the NumPy library

Trigonometric FunctionsTrigonometric functions in the Math module in the Python Standard Library:import math as mtx 2*mt.piy mt.sin(x)print(y)y mt.cos(x)print(y)y mt.tan(x)print(y)

Trigonometric FunctionsPlotting Example using a For Loop and the matplotlib library:import math as mtimport matplotlib.pyplot as pltxdata []ydata []for x in range(0, 10):xdata.append(x)y mt.sin(x)ydata.append(y)plt.plot(xdata, ydata)plt.show()

Trigonometric FunctionsImproved Plotting Example:β€œSmootherβ€œ curve:import math as mtimport matplotlib.pyplot as pltx 0N 100xdata []ydata []for i in range(0, N):x x 0.1xdata.append(x)y mt.sin(x)ydata.append(y)plt.plot(xdata, ydata)plt.show()The problem with using the Trigonometric functions in thethe Math module from the Python Standard Library is thatthey don't handle an array as input.

Trigonometric FunctionsUsing NumPy:import numpy as npimport matplotlib.pyplot as pltxstart 0xstop 2*np.piincrement 0.1x np.arange(xstart,xstop,increment)y np.sin(x)plt.plot(x, y)plt.show()The Trigonometric Functions in theNumPy library can handle arrays asinput arguments. No For Loop needed!

Trigonometric FunctionsYou can also plot multiple plots like this:import numpy as npimport matplotlib.pyplot as pltxstart 0xstop 2*np.piincrement 0.1x 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 FunctionsConverting to degrees (x-axis):import numpy as npimport matplotlib.pyplot as pltdef r2d(r):d r * (180/np.pi)return dxstart 0xstop 2*np.piincrement 0.1x 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()Here I have created my own Function r2d(r)You could have used math.degrees(x)

PolynomialsA polynomial is expressed as:𝑝 π‘₯ 𝑝! π‘₯ " 𝑝# π‘₯ " ! 𝑝" π‘₯ 𝑝"%!where 𝑝! , 𝑝# , 𝑝& , are the coefficients of the polynomial.We will use the Polynomial Module in the NumPy tines.polynomials.polynomial.html

PolynomialsGiven the following polynomial:𝑝 π‘₯ 5.45π‘₯ 3.2π‘₯ ! 8π‘₯ 5.6We need to rewrite it like this in Python:𝑝 π‘₯ 5.6 8π‘₯ 3.2π‘₯ ! 0π‘₯ , 5.45π‘₯ import numpy.polynomial.polynomial as polyp [5.6, 8, 3.2, 0, -5.45]r poly.polyroots(p)print(r)𝑝 π‘₯ 0 π‘₯ ?

PolynomialsGiven the following polynomial:𝑝 π‘₯ 2.1π‘₯ 2π‘₯ , 5π‘₯ 11We need to rewrite it like this in Python:𝑝 π‘₯ 11 5π‘₯ 0π‘₯ ! 2π‘₯ , 2.1π‘₯ import numpy.polynomial.polynomial as polyp [11, 5, 0, 2, -2.1]r poly.polyroots(p)print(r)x 2px poly.polyval(x, p)print(px)𝑝 π‘₯ 0 π‘₯ ?𝑝 2 ?

import numpy.polynomial.polynomial as polyp1 [1, 1, -1]p2 [2, 0, 0, 1]p poly.polymul(p1, p2)PolynomialsGiven the followingpolynomials:𝑝' π‘₯ 1 π‘₯ π‘₯ !𝑝! π‘₯ 2 π‘₯ ,print(p)r poly.polyroots(p)print(r)Let's find the polynomial 𝑝(π‘₯) 𝑝' (π‘₯) C 𝑝! (π‘₯) using Pythonx 2px poly.polyval(x, p)print(px)And let's find the roots of thepolynomial𝑝 π‘₯ 0

Polynomial FittingFind a Polynomial that best fits the followingfunction:𝑦 sin(π‘₯)Try with different order of the polynomN 3import numpy as npimport numpy.polynomial.polynomial as polyimport matplotlib.pyplot as pltxstart 0xstop 2*np.piincrement 0.1x np.arange(xstart,xstop,increment)y np.sin(x)plt.plot(x, y)N 3p poly.polyfit(x,y,N)print(p)y2 poly.polyval(x, p)plt.plot(x, y2)plt.show()

Polynomial FittingFind a Polynomial that best fits the following function:𝑦 sin(π‘₯)N 3N 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 NumbersA 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:𝑗 1In Python you define a complex number like this:z 3 2j

Complex Numbers – Polar FormComplex numbers can also be expressed on exponential/polar form:𝑧 π‘Ÿπ‘’ '(Where:π‘Ÿ 𝑧 πœƒ π‘Žπ‘‘π‘Žπ‘›π‘Ž! 𝑏 !π‘π‘ŽNote that π‘Ž π‘Ÿ cos πœƒ and 𝑏 π‘Ÿ sin πœƒ

Complex NumbersGiven the following complexnumbers:π‘Ž 5 3𝑗𝑏 1 1𝑗In Python we can define the complexnumbers and perform basicoperations ( , -, *, /) like this:a 5 3jb 1 - 1jc a bprint(c)d a - bprint(d)e a * bprint(e)f a / bprint(f)

Complex Numbersimport cmathIn addition, there exists severalComplex Number Functions inPython. We use the cmath library:cmath.phase(x)cmath.polar(x)cmath.rect(r, y/cmath.htmlx 2y -3# converting x and y into complex numberz ugate())# converting to polar formw cmath.polar(z)print (w)# converting to to rectangular formw cmath.rect(2,3)print (w)

Advanced Mathematics Linear AlgebraComplex NumbersDifferential EquationsInterpolationCurve FittingLeast Square MethodNumerical DifferentiationNumerical IntegrationOptimization

Additional Python ramming/python/

Hans-Petter HalvorsenUniversity of South-Eastern Norwaywww.usn.noE-mail: hans.p.halvorsen@usn.noWeb: https://www.halvorsen.blog

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 differe