Python
1
Python 1 Python Python is high-level programming language for - - PowerPoint PPT Presentation
Python 1 Python Python is high-level programming language for general-purpose programming. Supports multiple programming paradigms, including object-oriented , imperative , functional programming, and procedural styles. Original
1
functional programming, and procedural styles.
complier.
versions (3.6.2 latest). “3.*” is not backward-compatible. Take a look at this https://docs.python.org/3/whatsnew/3.0.html
platforms.
environment for scientific computations.
2
https://www.python.org/downloads/, https://www.scipy.org/install.html, http://www.sympy.org/en/download.html
Canopy (https://www.enthought.com/products/canopy/).
Just type “python” in the command line.
3
REPL https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop )
should be noted:
particular variable.
the last command.
get fractional number either dividend or divisor should be fractional number as well (5.0/2=2.5 or 5/2.5=2.5).
(https://en.wikipedia.org/wiki/IPython)
4
modules.
various modules implementing basic mathematical functions.
package_alias.module_name if alias was specified.
module_name defined in the package package_name. Module could be then accessed without specifying package name. Also note that you can use wildcards for module_name to import multiple modules with a single command.
5
https://docs.scipy.org/doc/numpy/reference/routines.math.html
6
want the function to accept, and then say what you want to do with those arguments. For example,
def g(x): … return x*x*x >>> g(2) 8 >>> g(2*3) 216
function definition coming.
your text properly, the point being that indentations are very important. We put in two leading spaces to indent the contents of our function definition, then told the function to “return” the cube of the argument.
Thus, x represents the number where we want to evaluate the function, and the result of the evaluation is what appears on the return line.
Instead return keyword is used to pass results to calling function.
7
in MATLAB) use lambda expressions. The syntax is as follows:
<varibalename> = lambda <x1>,<x2>,…,<xn>: <expression>
x**2 + 2*x*y + 3*y**2
defined in your session from function definition (body). In MATLAB we can easily get the value of some session variable or modify it. But that is a bad practice, so it’s a good thing that Python prevents you from doing this.
8
explicitly.
variable is of a given type use isinstance(variable_name, type_name).
instance (object) of these classes.
are: int (integer), long (integer with unlimited precision), float (double precision floating point number), complex (complex number), str (string), bool (boolean).
between types explicitly.
https://docs.scipy.org/doc/numpy/user/basics.types.html
9
truly useful in mathematics, and as it happens, it can.
>>> v=array([1,2,3]) >>> u=array([-1,-2,-3]) >>> u+v array([0, 0, 0]) >>> u*v array([-1, -4, -9])
https://docs.scipy.org/doc/numpy/reference/routines.linalg.html
10
mathematician’s point of view: it does not know about matrix multiplication.
>>> v=matrix([1,2,3]) >>> u=matrix([-1,-2,-3]) >>> v matrix([[1, 2, 3]]) >>> v.T matrix([[1], [2], [3]]) >>> u*v.T matrix([[-14]]) >>> u.T*v matrix([[-1, -2, -3], [-2, -4, -6], [-3, -6, -9]])
array strcture, not matrix. So, if you want to use any of them your choice may be array, not matrix.
11
http://pages.cs.wisc.edu/~bahls/cs302/PrimitiveVsReference.html and this http://www.python-course.eu/passing_arguments.php
12
similar:
if <condition_0>:
__Commands to be executed if <condition_0> is true
elif <condition_1>:
__Commands to be executed if <condition_1> is true
… elif <condition_N>:
__Commands to be executed if <condition_N> is true
Else:
__Commands to be executed if non of the <condition_0>, … , <condition_N> are true
indentations (red underscore (_) denotes a whitespace here)
13
Meaning Math Symbol Python Symbols Less than < < Greater than > > Less than or equal ≤ <= Greater than or equal ≥ >= Equals = == Not equal ≠ != Meaning Python Symbols Logical AND and Logical OR
Logical NOT not
14
for <iterator> in <range>:
__Commands to be executed for every value from the <range>. Current value is accessed using <iterator> variable.
as in MATLAB.
indentations (red underscore (_) denotes a whitespace here).
giving the user the ability to define both the iteration step and halting condition, Python’s for statement iterates over the items of any sequence (a list or a string), in the
15
commands are executed until given condition is true.
while <condition>:
__ Commands to be executed while <condition> is true.
code is done with indentations (red underscore (_) denotes a whitespace here).
16
script files. Then all the commands could be executed at once by calling that script.
command “python filename.py”, e.g. “python dosomething.py”.
“execflie(‘filename’)”. Note that filename can be either a relative path (relative to your current working directory, where you were right before starting Python)
done in current session. For example, if you imported NumPy in current interactive shell session, you need to have another import statement in your script in order to use NumPy functions, since Python doesn’t know what was happening in your session when it starts executing your script.
17
be “.py”) and define some functions (can be multiple functions) there using the syntax we learned.
functions are stored.
execute import myfuns as mf if you saved your functions in “myfuns.py”.
modules, e.g. mf.g(10) should be used to call function f defined in your “myfuns.py”, if you imported your file using the command from the above example.
easiest way is to store your function in the your current working directory. That’s where Python goes first to find your file. The other options could be found here https://docs.python.org/2/tutorial/modules.html#the-module-search-path
you should reload your module manually with reload(mf) command.
18
delimiter is a colon (:) and the indentation of the code itself.
so on. Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords. This means that whitespace is significant, and must be consistent. Every line of the particular block should have exactly the same indentation. It doesn't matter how large is it, just make sure it is the same for every line.
additional spaces. The block of the for loop is indented with 4 additional spaces.
def fib(n): 0 spaces print 'n =', n 3 spaces if n > 1: 3 spaces return n * fib(n - 1) 3+2=5 spaces else: 3 spaces print 'end of the line' 3+2=5 spaces return 1 3+2=5 spaces def foo(n): 0 spaces for i in range(10): 3 spaces print 'i = %d' % i 3+4=7 spaces
https://docs.python.org/2/tutorial/controlflow.html#intermezzo-coding-style
19
algorithm for solving equations of the form f(x)=0.
file.
try solving some equation.
algorithm using lambda expressions, e.g. f1 = lambda x: x**2-4*x+5.
f(x1) or f(x2) are less than e. If yes, it means that x1 or x2 is the root of your equation and you’re done.
functions provided by NumPy https://docs.scipy.org/doc/scipy/reference/opti mize.nonlin.html
20
any of three types of quotation marks. Once they are entered, they can be manipulated in fairly natural ways using operators that we would ordinarily consider as applying only to arithmetic.
>>> y="Yossarian said, " >>> twice='"I see everything twice!"' >>> y+twice 'Yossarian said, "I see everything twice!"' >>> twice*2 '"I see everything twice!""I see everything twice!“’
concatenate them using a + symbol: in Python, adding two strings concatenates
specified number of times. Do not try to multiply one string by another.
21
string in various ways.
>>> len(y) 16 >>> y.find('said') 10 >>> y[10] 's' >>> Y=y.replace('said','shouted') >>> Y 'Yossarian shouted, ' >>> Y.upper() 'YOSSARIAN SHOUTED, ' >>> z=Y.lower() >>> z 'yossarian shouted, ' >>> z.capitalize() 'Yossarian shouted, '
22
do formatting of that string for you, e.g. combining text and floating point numbers using given precision.
print <string> % (variable1, variable2, … , variableN)
variable1, variable2, … , variableN values in the text, e.g. print ‘My whole number is %d. My fractional number is %f’ % (i, x). Note that order of variables specified after the string matters here.
you to surround everything which comes after print command with parenthes, i.e. print(‘My whole number is %d. My fractional number is %f’ % (i, x)). So just drop the parentheses and you will get a valid commands for Python 2.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_str.html
23
find some information here https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
data.
numpy.loadtxt(filename). The function returns NumPy array variable containing the data stored in the file. More details are here https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html
https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html
data). More details are here https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html
24
argument gets its default value. Furthermore, arguments can be specified in any order by using named arguments.
slide), you would see something like this
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ‘)
when you call the function and should be provided in the specified order (fnmae first and then X) without specifying the name of the parameter.
right after equality symbol), e.g. '%.18e’ will be used for fmt parameter.
parameter and then specify value by separating the name and the value with equality sign. The order you use to specify optional parameters is arbitrary. For example, savetxt(fname, X, delimiter=‘|’, header=‘col1|col2’) or , savetxt(fname, X, header=‘col1|col2’, delimiter=‘|’) will produce the same result.
25
http://www.math.wsu.edu/students/odykhovychnyi/M300/slides/09_Python/system.dat
vector b.
this function https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html
vector for this purpose. The coordinates should be written as floating point numbers with 2 digits after in the fractional part.
same as number of equations.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html
26
Therefore, the majority of plotting commands in pyplot have Matlab analogs with similar arguments.
decorates the plot with labels, etc.
X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C = np.cos(X) S = np.sin(X) plt.plot(X, C) plt.plot(X, S) plt.show()
graph you need to provide a pair of NumPy arrays representing x-values and y-values.
plt.cla() command.
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
27
http://matplotlib.org/users/pyplot_tutorial.html#controlling-line-properties
title use plt.title(title).
http://matplotlib.org/users/pyplot_tutorial.html#working-with-multiple-figures-and-axes
lectures.org/intro/matplotlib/index.html and http://matplotlib.org/users/pyplot_tutorial.html
28
with trapezoid rule of f on [a, b] using n subintervals.
dashed line connecting values of function at the endpoints of subintervals. The points should be highlighted using some points marker.
value of n.
from scipy import integrate as intgr (val, err) = intgr.quad(f, a, b)
by trapez and the value computed by scipy.integrate.quad). Your x-axis should be the number of subintervals used.
29
section 7.10.
30
time required to approximate an integral using your trapez function.
31
section 7.8.
32
(number).
The loop should run over 60 seconds.
“Crash!”.
message “Too far!”.
33
section 7.12.
34
(http://millenniummath.org/Computation/scientific_computing.pdf)
38