Mathematics In Python - Halvorsen.blog

3y ago
82 Views
6 Downloads
6.68 MB
41 Pages
Last View : 17d ago
Last Download : 6m ago
Upload by : Warren Adams
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 different modules for handling file I/O, basic mathematics, etc.

Related Documents:

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

Python Programming - This is a textbook in Python Programming with lots of Practical Examples and Exercises. You will learn the necessary foundation for basic programming with focus on Python. Python for Science and Engineering - This is a textbook in Python Programming with lots of Examples, Exercises, and Practical Applications

Mike Driscoll has been programming with Python for more than a decade. He has been writing about Python on his blog, The Mouse vs. The Python, for many years. Mike is the author of several Python books including Python 101, Python Interviews, and ReportLab: PDF Processing with Python. You can find Mike on Twitter or GitHub via his handle .

Mike Driscoll has been programming with Python for more than a decade. He has been writing about Python on his blog, The Mouse vs. The Python, for many years. Mike is the author of several Python books including Python 101, Python Interviews, and ReportLab: PDF Processing with Python. You can find Mike on Twitter or GitHub via his handle .

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.