Introduction to Python Practical 1

Similar documents
Introduction to MATLAB Practical 1

AMS 27L LAB #2 Winter 2009

Chapter 1 Introduction to MATLAB

1 Introduction to Matlab

PART 1 PROGRAMMING WITH MATHLAB

Matlab Tutorial. Get familiar with MATLAB by using tutorials and demos found in MATLAB. You can click Start MATLAB Demos to start the help screen.

Introduction to MATLAB

Matlab Introduction. Scalar Variables and Arithmetic Operators

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

A Guide to Using Some Basic MATLAB Functions

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

MATLAB/Octave Tutorial

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

A Brief Introduction to MATLAB

Introduction to Matlab

Introduction to Matlab

Introduction to Engineering gii

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

To start using Matlab, you only need be concerned with the command window for now.

Introduction to MATLAB

Dr Richard Greenaway

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

Datenanalyse (PHY231) Herbstsemester 2017

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

1. Register an account on: using your Oxford address

Laboratory 1 Octave Tutorial

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

MATLAB Guide to Fibonacci Numbers

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

Introduction to MatLab. Introduction to MatLab K. Craig 1

Introduction to MATLAB LAB 1

MATLAB SUMMARY FOR MATH2070/2970

2.0 MATLAB Fundamentals

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

Introduction to Matlab

Matlab Tutorial: Basics

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

Objectives. 1 Running, and Interface Layout. 2 Toolboxes, Documentation and Tutorials. 3 Basic Calculations. PS 12a Laboratory 1 Spring 2014

Introduction to Matlab

Stokes Modelling Workshop

Summer 2009 REU: Introduction to Matlab

Physics 326G Winter Class 2. In this class you will learn how to define and work with arrays or vectors.

Chapter 2. MATLAB Fundamentals

MatLab Just a beginning

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

What is Matlab? The command line Variables Operators Functions

ELEN E3084: Signals and Systems Lab Lab II: Introduction to Matlab (Part II) and Elementary Signals

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

A very brief Matlab introduction

A/D Converter. Sampling. Figure 1.1: Block Diagram of a DSP System

Homework 1 Description CmpE 362 Spring Instructor : Fatih Alagoz Teaching Assistant : Yekta Said Can Due: 3 March, 23:59, sharp

How to learn MATLAB? Some predefined variables

Introduction to GNU-Octave

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

LAB 1: Introduction to MATLAB Summer 2011

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

ERTH3021 Exploration and Mining Geophysics

Computational Programming with Python

Quick MATLAB Syntax Guide

Mathematical Operations with Arrays and Matrices

EE 350. Continuous-Time Linear Systems. Recitation 1. 1

EEE161 Applied Electromagnetics Laboratory 1

Dr Richard Greenaway

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

A Tutorial on Matlab Ch. 3 Programming in Matlab

An Introduction to MATLAB II

Lab 1 Intro to MATLAB and FreeMat

Basic stuff -- assignments, arithmetic and functions

AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

Introduction to Matlab. By: Hossein Hamooni Fall 2014

Introduction to Matlab

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Introduction to Matlab

MAT 275 Laboratory 1 Introduction to MATLAB

Programming in Mathematics. Mili I. Shah

Identity Matrix: >> eye(3) ans = Matrix of Ones: >> ones(2,3) ans =

Ebooks Chemical Engineering

EGR 111 Introduction to MATLAB

Math 2250 MATLAB TUTORIAL Fall 2005

INTRODUCTION TO MATLAB

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

Introduction to MATLAB

An Introduction to Numerical Methods

An Introductory Tutorial on Matlab

Mechanical Engineering Department Second Year (2015)

Computer Programming in MATLAB

Statistical Data Analysis: Python Tutorial

Introduction to Matlab to Accompany Linear Algebra. Douglas Hundley Department of Mathematics and Statistics Whitman College

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

Transcription:

Introduction to Python Practical 1 Daniel Carrera & Brian Thorsbro October 2017 1 Introduction I believe that the best way to learn programming is hands on, and I tried to design this practical that way. No prior knowledge of Python is assumed, but you must already have it installed. By installing the anaconda package that can be downloaded for free python will be installed as well. Please install version 3.6 (or newer). Different tools are installed by anaconda, and the Spyder tool is what I find the most useful for small python scripts. Installation website: https://www.anaconda.com/download/ 2 Whirlwind tour of Python 2.1 Python as a calculator Locate the Spyder program and run it. After the program starts, you will be presented with a command shell, default in the bottom right corner, where you enter python instructions. In the rest of this tutorial, any line that starts with >> denotes the python command shell, which normally looks a bit like In [nnn]:. For example: >> 2 + 3 5 At the simplest level you can use python as a scientific calculator. Enter the following code and see what it does. 1

>> 2 * 5 >> 2 + 3 * 5 + 1/2 >> 3**2 >> 3**3 >> 3**4 >> 4**(-1) >> 4**(1/2) You can enter arithmetic operations directly into the command window. The symbol ** denotes exponentiation (so you write 5 17 as 5**17). For mathematical functions and constants you need to load the math library, as shown in the first line in the following. >> sqrt(2) >> sqrt(4) >> sqrt(25) >> pi >> cos(pi) >> sin(pi/2) >> tan(pi/4) >> arctan(1) >> arctan(tan(0)) Note, that you can also use import numpy instead of from math import *, but then you would have to preamble all your expressions with numpy., for example numpy.sqrt(2). Some programmers considers this to be more clean code, as it shows the library usage explicitly. Also know that a math library also exists for importing the mathematical functions, but the numpy library also supplies these mathematical functions with more functionality for advanced data structures. >> exp(0) >> exp(1) >> exp(2) 2

>> e >> log(e) >> log(10) >> log(e**173) >> log(exp(173)) >> log10(e) >> log10(10) >> log10(1000) >> log10(10**189) The function exp(x) returns e x where e = 2.7183... is the base of the natural logarithm. The function log() gives the natural logarithm while log10() gives the logarithm base 10. >> 1j >> 5j >> 2 + 1j >> (-1)**0.5 >> exp(1j*pi) >> log(1j) >> sin(1j) >> sinh(1j) The syntax 3j, 5j, etc lets you write imaginary numbers safely. You must write 1j, writing just j is not sufficient. >> from math import * >> help(log10) Python has an extensive help system. Unfortunately this does not help so much with numpy library, using google is recommended. 3

2.2 Vectors and linear algebra >> u = array([1.0,2.0,3.0]) >> v = array([3.0,4.0,12.0]) >> u + v >> u - v >> u * v >> u / v >> v ** u >> 3 * u >> 3 * u - v >> dot(u,v) >> dot(v,v) >> sqrt( dot(v,v) ) >> linalg.norm(v) One way to create a vector is to enter the vector components directly inside square brackets. In this example you created row vectors u = [1, 2, 3] and v = [3, 4, 12]. You can do vector addition, subtraction, multiplication, division, exponential, scalar multiplication and dot product. Using an operator between two arrays causes the operator to be applied element by element through the arrays (which have to be of equal length). Note that these are not matrix operations. The function linalg.norm returns the norm, or the magnitude of a vector. >> u = mat([1.0,2.0,3.0]) >> v = mat([3.0,4.0,12.0]) >> u >> v >> transpose(u) >> transpose(v) >> transpose(u) * v >> u * transpose(v) The vectors u and v are in this example matrices of one dimension, and not arrays. Those the operators between them become matrix operations and for two row vectors you need to take the transpose of one of the vectors to multiply them. 4

>> v = mat([3.0,4.0,12.0]) >> w = mat([[1.0],[2.0],[3.0]]) >> w * v >> v * w You can enter a column vector directly if you double square brackets to type in the data row by row. 2.3 Conditionals >> a = 1 >> b = 2 >> if a == b: x = 2 elif a >= 3: x = 7 else: x = 0 >> x In python indentation is very important, it marks the structure. For the elif, which means else if, it has to be at the same indentation as the first if statement it belongs to. Experiment with different values of a and b and different conditions (e.g. == <= => < >). What happens if a and b are arrays? Try the following examples: >> a = array([1,2,3]) >> b = array([1,2,3]) >> a == b >> b = array([1,2,4]) >> a == b >> if any(a == b): 5

x = 2 else: x = 0 >> x >> if all(a == b): x = 2 else x = 0 >> x Experiment with different arrays (e.g. b = [3 1 2]). What do the functions any and all do? >> arange(3,11) >> arange(3,11,2) >> arange(2.5,7.5) >> arange(2.5,7.5,2) >> arange(2,7,1.5) The function arange offers different ways of constructing arrays running through a series of numbers, the third argument is the step size. >> from matplotlib.pyplot import * >> x = arange(1,10) >> y = x ** 2 >> plot(x, y) >> plot(x, cos(x)) By this point you have learnt enough python to produce many useful plots. Use x = arange(a,b,q) to create a series of X values, and use vector or array operations to produce the corresponding Y values. The plot command is very flexible and can produce a lot of nice plots. 6

Enter the following code and see what it does. Use the Up arrow key to pull up previous lines so that you can save typing: >> from matplotlib.pyplot import * >> x = arange(0,2*pi,0.1) >> y = sin(x) >> plot(x,y, r ) >> plot(x,y, g ) >> plot(x,y, b ) >> plot(x,y, m ) >> plot(x,y, y ) >> plot(x,y, k ) >> plot(x,y, c ) >> plot(x,y, r- ) >> plot(x,y, ro ) >> plot(x,y, r+ ) >> plot(x,y, r* ) >> plot(x,y, rx ) >> plot(x,y, r^ ) >> plot(x,y, ro- ) >> plot(x,y, r+- ) >> plot(x,y, go- ) >> y2 = cos(x) >> plot(x,y, r,x,y2, b );legend([ Sine, Cosine ]);title( Sines and Cosines ) >> plot(x,y, r );plot(x,y2, b );xlabel( This is the X axis ) The plot function accepts an optional formatting string to define the colour, plot style and data label. You can include any number of data sets in the same plot. In this example the semicolon is used to separate commands, because the plot is reset when hitting enter. When you later make programs you can type the commands on a line each instead of using semicolon, i.e. like shown in this code snippet. from numpy import * from matplotlib.pyplot import * figure() x = arange(0,2*pi,0.1) y = sin(x) 7

y2 = cos(x) plot(x,y, r ) plot(x,y2, b ) legend([ Sine, Cosine ]) title( Sines and Cosines ) xlabel( This is the X axis ) ylabel( This is the Y axis ) Notice the usage of figure() which sets up a new clean plot. 2.4 Making python programs Click on the New File button to open the built-in python editor in Spyder. You can use the editor to write python programs. Python programs contain a sequence of python commands, allowing you to store complex operations for later use. When you save the program, the file name should have the extension.py. Enter this in the editor: """ wave.py -- An simple animation of a travelling wave. """ from numpy import * for idx in arange(1,4): print(idx) Save this file as wave.py in the current working directory. After the file is saved, Enter the following in the command window and see what it does; >> run wave.py This program should print the integers from 1 to 3. This program only contains a short for loop. A for loop allows you to repeat commands a fixed number of times as the index variable (in this case idx) steps through the values of an array. You can also run the program by hitting the green play button in the Spyder interface. 8

Replace the for loop with the one below and run the program again to see what it does: for idx in arange(1.5,3.5,0.5): print(idx) # print the idx print(idx * idx) # print the idx squared The index variable in a for loop can step through the values of any array. The program also shows comments. A comment goes from the # sign to the end of the line. Always comment your programs generously and clearly. A block comment going over several lines can be started with the """ sequence and the program ignores everything until the sequence is found again. It is a good way to exclude some code from a program without deleting it, should you want to save it. 3 Exercises It is important that you do the exercises, as they will help sharpen your skills with loops, plotting and finding help on python functions. The last problem is mainly to help you play with python. Exercise 1: The Fibonacci sequence is a series of integers, starting with 1,1, where the next value is the sum of the previous two values. The first few terms of the Fibonacci sequence are: 1,1,2,3,5,8,13,... Write a program that prints the first 50 values of the Fibonacci sequence. Exercise 2: Try to make a plot similar to the one on the next page. The plot compares the values produced by the norm function with the Gaussian distribution (in particular norm.ppf, norm.pdf, and norm.rvs). You will find the the norm functions in the scipy.stats library. Try to find help on these functions on the internet and then use the plot functions from matplotlib.pyplot to produce your plot, in particular you might find the plotting function hist useful for part of this exercise. Exercise 3: Type in the following code in a program, save it, and run it to see what it does: from mpl_toolkits.mplot3d import Axes3D from matplotlib.pyplot import * from numpy import * # Setting up the grid that is worked upon X = arange(-8, 8, 0.5) Y = arange(-8, 8, 0.5) X, Y = meshgrid(x, Y) 9

# defining the Z axis value, try make other functions! R = sqrt(x**2 + Y**2) Z = sin(r) / R # do the actual 3D plotting fig = figure() ax = fig.gca(projection= 3d ) surf = ax.plot_surface(x, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=false) ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(linearlocator(10)) ax.zaxis.set_major_formatter(formatstrformatter( %.02f )) fig.colorbar(surf, shrink=0.5, aspect=5) Advanced 3D plotting techniques exists in python. shape (a bowl, a volcano, a sombrero, etc). Try to make a plot with an interesting 10