Title: Ber
1Numeriska beräkningar i Naturvetenskap och Teknik
- Material
- Grading sheet
- Micromanaged schedule
- Literature list
- Reading list and lecture content
- Matlab introduction exercises
- Project 1
- Part 1 Air resistance
- Part 2 Planetary motion
- Part 3 Advanced exercises
- 7. Numerical methods lit. extracts
- 8. Mechanics lit. extracts
- Address to e-book linked at web site
- http//www.springerlink.com/content/w8302n/?
- p35f7440cdc9b4ab6bc38d380d9b3c4aa
pi0
2Numeriska beräkningar i Naturvetenskap och Teknik
- Part A, Technical aspects and the use of MATLAB
-
- Short history. Why machine based computing?
- Programming
- 3. Demonstration of basics
-
Part B, Numerical Methods 1. Numerical solution
of differential equations 2. Numerical solution
of algebraic equations 3. Fitting models to data
4. Adaptation to problem in physics planetary
motion
3Numeriska beräkningar i Naturvetenskap och Teknik
- Why compute using machines and numerical methods?
- Work saving for extensive and trivial
calculations - 2. Reproducible results, minimizes errors due to
- the human factor. However, new
possibilities - or mistakes arise programming errors
- Equation solving including algebraic equations
but - above all differential equations that lack
solution - in closed form, i.e. that have no analytical
- solution.
- 4. Monte Carlo simulations of stochastic
processes -
Points 3 and 4 are the main reasons computers are
vital in modern physics.
4Numeriska beräkningar i Naturvetenskap och Teknik
Wilhelm Shickard 1592 1635 From Tuebingen,
Germany. Designed mechanical calculator for
addition of six figure numbers. Some issues
remain unclear. Limited future influence.
Reconstructed.
1623
5Numeriska beräkningar i Naturvetenskap och Teknik
1645
Blaise Pascal 1623-1662 Invented the so called
Pascaline around 1645. The purpose was to
simplify his fathers work as tax collector in
Rouen, France. The machine could add and
multiply. Subtractions was complicated and time
consuming.
1670
6Numeriska beräkningar i Naturvetenskap och Teknik
Gottfried Leibniz 1646-1716 Constructed in
1670 the first machine that could do all the four
basic algebraic operations.
1670
7Numeriska beräkningar i Naturvetenskap och Teknik
Charles Xavier Thomas de Colmar 1785-1870.
Based on Leibniz design de Colmar constructs
the first commercially successful mechanical
calculator, the arithometer. Ca 1500 are made
for use by the French civil service.
1820
1670
8Numeriska beräkningar i Naturvetenskap och Teknik
Charles Babbage 1791-1871 Designed the first
programmable calculator (difference engine)
with the purpose to reduce the number of errors
in mathematical tables. Later designed a
mechanical computer, the analytical
engine. Neither machine finished during
his lifetime.
Ada Countess of Lovelace Known as the first
programmer. Wrote program to calculate the
so-called Bernoulli numbers using Babbages
analytical engine.
9Numeriska beräkningar i Naturvetenskap och Teknik
Georg and Edvard Scheutz 1785-1873 and 1821-1881
10Numeriska beräkningar i Naturvetenskap och Teknik
Alan Turing 1912-1954 Computer science pioneer.
Formalized the algorithm concept and introduced,
in 1936, the theoretical background of
computers with the Turing machine, defined by
a set of instructions, storage space etc.
Today a machine of this kind is called a
finite-state machine.
1936
Konrad Zuse 1910-1995 Constructed in 1941 the
first programmable computer based on telephone
relays partly financed by Deutsche
Versuchsanstalt fur Luftfarth.
11Numeriska beräkningar i Naturvetenskap och Teknik
Morgenstern
John von Neumann 1903-1957 Born in Budapest.
PhD in math and chemical engineer Immigrated to
the US and became citizen in 1938 One of the
first faculty members at IAS, Princeton together
with Einstein, Gödel, Weyl. Made significant
contributions in - Mathematics - Physics -
Economic theory - Computer science etc
Original work on computing at Princeton in
relation to ballistic calculations,
later simulations for thermonuclear explosions.
Johnny vN
12Numeriska beräkningar i Naturvetenskap och Teknik
Oppie
John von Neumann 1903-1957 Wrote, in 1945, The
first draft report on the EDVAC EDVAC
(Electronic Discrete Variable Automatic
Computer) was the successor of ENIAC (the
Electronic Numerical Integrator and Calculator)
which in turn was the first large scale
programmable digital computer (vacuum tube
based). EDVAC, in contrast to ENIAC, could be
reprogrammed without physical recabling as the
program and data were in memory. This kind of
machine, which stores program and data in the
same memory unit is the dominating
computer architecture today and goes under the
name von Neumann architecture.
Ulam
Feynman
CU
CPU
IN
OUT
ALU
MEM
13Numeriska beräkningar i Naturvetenskap och Teknik
SOME BASIC CONCEPTS
14Numeriska beräkningar i Naturvetenskap och Teknik
CPU and instruction set
Every instruction that the processor (CPU) can
execute corresponds to a code, i.e. a number
stored electronically in the memory of the
machine. ----------------------------------------
--------------------- Typical instructions
contain a so-called opcode that corresponds to a
command, and one or several operands that the
opcode uses as arguments. -----------------------
-------------------------------------- All
instructions are operations on binary numbers in
the computer memory. ----------------------------
--------------------------------- A processor has
a limited number of instructions it can perform.
These make up the processors instruction set.
15Numeriska beräkningar i Naturvetenskap och Teknik
A typical sequence to add two numbers, a and b,
could be based on instructions such as Load and
Add etc 1. Load a in register 1 in
memory
2. Load b in register 2 in memory
3. Add register 1 to register 2
4. Store register 2 in the position of b in
memory This means that programming became a
complex problem in itself. Using machine code is
both time consuming and prone to programming
errors. -----------------------------------------
------------------- Still, this was the way the
first computers were programmed and it is still
in use under certain circumstances.
16Numeriska beräkningar i Naturvetenskap och Teknik
Low level and high level programming
In low level programming one uses a programming
language which is close to the instruction set of
the processor. One such method goes under the
name assembler programming. ---------------------
----------------------------------------- In this
case instructions such as addition, subtraction,
bit shifts, register access etc are coded using
mnemonics. These are translated by a program to
the numbers that correspond to a certain
instruction in the set, i.e. to machine code.
-------------------------------------------------
------------- Mnemonics can e.g be DEC B,
(decrease content of register B), ADD A,B (add
reg A to reg B) etc.
17Numeriska beräkningar i Naturvetenskap och Teknik
Low level and high level programming
For the most part modern programmering is done in
high level programming languages whose syntaxes
are such that they are close to our ordinary
language. Several high level languages have been
developed over the years. Some well known ones
are FORTRAN (Formula translation) COBOL (Common
business language) ADA (in honor of Lady
Lovelace) LISP (List processing language) PASCAL
(in honor of Blaise P), C (it developped from
B) SIMULA (a commonly used training language,
weird) C (Object oriented extension of
C) -----------------------------------------------
--------------- All these contain similar
structures but have slightly different syntaxes.
18Numeriska beräkningar i Naturvetenskap och Teknik
Interpreted and compiled programming languages
Performed every time program runs
Source code
Performed once
Compiler
Interpreter
Produces an executable file
Produces executable code line-by-line
Quick
Machine code
Machine code
Rel. slow
FORTRAN, C, C
BASIC, different scripting languages (Perl, Ruby)
MATLAB
Java byte code compiler Virtual machine -gt
machine code gt Portability (compile once run
everywhere)
19Numeriska beräkningar i Naturvetenskap och Teknik
MATLAB as calculator gtgt 2 2 ans 4 gtgt
ans2 ans 8 The latest answer stored in
ans gtgt pi ans 3.14159265358793
Command window i MATLAB
20Numeriska beräkningar i Naturvetenskap och Teknik
Variable Entity introduced in order to store
numerical values In classical physics it can be
time, acceleration, position etc...
-------------------------------------------------
------- It is a very GOOD idea to give names to
variables that connect to their use.
-------------------------------------------------
------- For physics problems, it is good to use
notation given by the standard physics notation
for the quantity. This is very helpful when
programming under all circumstances.
21Numeriska beräkningar i Naturvetenskap och Teknik
Look at the trivial example gtgt A1 A
1 gtgt B2 B 2 gtgt CAB C 2
22Numeriska beräkningar i Naturvetenskap och Teknik
Och jämför med gtgt m1 m 1 gtgt a2 a
2 gtgt Fma F 2 gtgt
23Numeriska beräkningar i Naturvetenskap och Teknik
Variables Variables can be of different types.
Depending on type the computer will store the
variable using a different number of
bits. --------------------------------------------
-------------- Types can be 1. Integers of
different lengths, 8, 16, 32, 64 bits etc 2.
Floating point numbers of different lengths, i.e.
decimal numbers with different
precision 3. Vectors/matrices 4. Strings
etc... -------------------------------------------
--------------- Normally such a program begins
with a declaration sequence.
24Numeriska beräkningar i Naturvetenskap och Teknik
Variables In MATLAB which, like BASIC, is an
interpreted language one does not have to declare
the type of the variable (integer, float, string
etc), the interpreter decides about the type from
the assignment gtgt A1.234 A 1.2340 A
is a decimal number (a floting point number or a
float)
25Numeriska beräkningar i Naturvetenskap och Teknik
Variables gtgt b123 b 1 2
3 b is a vector gtgt B 1 2 3 4 5 67 8 9 B
1 2 3 4 5 6
7 8 9 B is a
matrix Matrices can have more than two
dimensions
26Numeriska beräkningar i Naturvetenskap och Teknik
Variables One can also write gtgt b(1)1 b
1 gtgtb(2) 2 b1 2 gtgtb(3) 3 b1 2 3 Good
in programs
27Numeriska beräkningar i Naturvetenskap och Teknik
Variables In the same way gtgt A(1,1)1 A 1 gtgt
A(1,2) 2 A 1 2 gtgtA(2,1) 3 A 1
2 3 0 gtgtA(2,2) 4 A 1 2 3
4
Add index for more dimensions. One can add
matrices to matrices and matrices to matrices of
higher dimension
28Numeriska beräkningar i Naturvetenskap och Teknik
Special vectors gtgta110 ans 1 2 3 4 5 6 7 8 9
10 gtgta00.11 ans 0 0.1 0.2 0.3 0.4 0.5 0.6
0.7 0.8 0.9 Other linspace(a,b) one hundred
evenly distributed elements between a and
b linspace(a,b,n) n elements between a and
b Delvektorer x(i), element i x(ij) sub
vector of elements i till j x(ikj) sub vector
of elements i to j at step k x(i1 .... ip) sub
vector of given elements
29Numeriska beräkningar i Naturvetenskap och Teknik
Special matrices zeros(n) nxn zero
matris zeros(n, o, p...) n x o x p zero
matris ones(...) in the same way a matrix
with ones eye(..) unity matrix, one on the
diagonal rand(..) n x n random matrix, 0 to
1 randn(..) normal distribution of random
elements
In a compiled language the size is often given in
the declaration
30Numeriska beräkningar i Naturvetenskap och Teknik
Precision The internal precision in a MATLAB
calculation is given by the fact that numbers are
stored as doubles. In a 32 bit machine a
double is stored as sign exponent
mantissa in 64 bits Which gives approximately 16
figures precision.
31Numeriska beräkningar i Naturvetenskap och Teknik
Assignments Note that an assignment is not the
same as an equation! gtgtx 1 x1 gtgtx x
1 x2 i.e. to the value in the memory
position of x (1) 1 is added giving the
result 2. gtgtworkspace -gt gives a list of all
variables
32Numeriska beräkningar i Naturvetenskap och Teknik
Two results that may indicate a failed
calculation Inf (Infinity) gtgta2 a2 gtgta/0
built in exception handler ans
inf NaN (Not a Number) gtgt 0/0 ans NaN
33Numeriska beräkningar i Naturvetenskap och Teknik
Assignments operators The standard operators
can be used as expected addition
subtraction - multiplication division
/ exponent ------------------------------
--------------------------- Same order of
priority as usual gtgta23-12 a4 gtgta2(3-1)2 a
8
34Numeriska beräkningar i Naturvetenskap och Teknik
Assignments operators A matrix multiplied by a
scalar gtgtA1 2 3 1 2 3 1 2 3 gtgtc
2 gtgtBcA B 2 4 6 2 4
6 2 4 6 but
35Numeriska beräkningar i Naturvetenskap och Teknik
Assignments operators Elementwise
multiplication with . gtgt A.B 2 8
18 2 8 18 2 8
18 Similarly elementwise division ./
36Numeriska beräkningar i Naturvetenskap och Teknik
Assignments operators Usual matrix
multiplication, number of rows of A equal to the
nr of columns in B gtgt AB 12 24
36 12 24 36 12 24
36 Other functions Transpose A Inverse
inv(A) Determinant det(A)
37Numeriska beräkningar i Naturvetenskap och Teknik
Assignment operators Scalar and vector
products gtgta 1 2 3 gtgtb 1 2 3 gtgtc
dot(a,b) ans 14 gtgtcross(a,b) ans
0
38Numeriska beräkningar i Naturvetenskap och Teknik
- Why programs?
- Problems that require repeated calculations with
- different input data for a new set of output
data - 2. Complicated problems solved by complicated
computations - e.g. differential or integral equations
- 3. Today also vital for control systems often
defined as - finite state machines airplanes, cars,
workshop and - production machinery
39Numeriska beräkningar i Naturvetenskap och Teknik
- To think about before and while you program
- Define the general problem
- Look for the structure of the problem and divide
it into sub problems - 3. Select method
- 4. Analyze input and output data. What goes into
the pgm and what comes out? -
- If necessary make flow chart
- Debug while writing. Never write from A to Z and
expect it to work. - Document continuously, use comments in the
program as well as notes
40Numeriska beräkningar i Naturvetenskap och Teknik
Errors mainly of two types 1. Syntax errors
Typos (mis-spellings of commands),
misunderstanding syntax or limited knowledge of
syntax. These errors are discovered by the
compiler and an error message is given. An
experienced programmer learn which mistakes
correspond to a certain error message and solves
such a problem quickly. --------------------------
------------------------------- 2. Run time
errors Design error in the program. Can lead to
an incorrect resultat but also to program
crash. Often caused by a limited analysis of how
a complete set of input data is processed in a
program algorithm. Dangerous error. Solution,
write short pieces of code before testing and
debug often!
41Numeriska beräkningar i Naturvetenskap och Teknik
Building blocks 1. Statement sequences
Simple statements, e.g. assignments that
follow each other 2. Alternative flow
paths Depending on a specific condition
different statements are executed. E.g. if the
requested precision has been reached the
calculation is ended and the result presented.
3. Repetitions A task is performed several
times until a condition is fulfilled. As an
example when 10 terms are required for a given
series expansion
42Numeriska beräkningar i Naturvetenskap och Teknik
How to define a condition?
43Numeriska beräkningar i Naturvetenskap och Teknik
Logical expressions Expressions with an answer
of type true or false, represented by 1 or
0 a1b2, ab false,
, , lt lt
gt (not
equal to) MATLAB specific any(arg) any element
all(arg) all elements
44Numeriska beräkningar i Naturvetenskap och Teknik
Flow paths If-statements if logical
expression if a1
statements disp(a) endif
end Can be expanded
with else if logical expression if
a1 statements disp(a) else
else
satsgrupper
disp(b) endif
end
45Numeriska beräkningar i Naturvetenskap och Teknik
Alt. If logical
expression
statement
elseif logical expression
statement
elseif logical expression
statement .... else
statement end
46Numeriska beräkningar i Naturvetenskap och Teknik
Switch statements switch variable
switch a case value1 case 1
statements disp (a)
case value2 case 7
statements binput(give
b) ....
case value3 case 11.7
statements c23
otherwise
otherwise
statements
aa23
end
end
47Numeriska beräkningar i Naturvetenskap och Teknik
For loop for variabel ahb for
a00.110 statements bba
end
end ----------------------------------------------
------ While loop while logiskt
uttryck while altb
statements aa0.1
end
end ----------------------------------------------
------ Loops can be written inside other loops
resulting in nested loops... Error(teckensträng),
pause, break kan be use for flow control
48Numeriska beräkningar i Naturvetenskap och Teknik
Error(tstring) exits m-file and writes
string pause waits for key press Break
can be used for flow control, exits the while
or for loop the program was executing.
49Numeriska beräkningar i Naturvetenskap och Teknik
Functions When all sub problems have been
defined for the program it is often natural to
perform some tasks using calls to the same code
sequence from a main program. This is the reason
for writing functions. Definition Function
utvar1, utvar2, utvar filnamn(invar1,
invar2, invar) comments Exemple of function
call b1, b2, b3. filnamn(a1,
a2,a3.)
50Numeriska beräkningar i Naturvetenskap och Teknik
Global variables The variables in a function
are normally local, i.e. they are set to 0 when
program leaves the function. One can define
variables to be accessible outside of the routine
to avoid zeroing them by giving the definition
global var1 var2
MAIN global x
f1 global x y z t s
f3 q t r s
f2 global x y z t
51Numeriska beräkningar i Naturvetenskap och Teknik
- Input data to a program and output data from a
program constitutes so-called i/o - INPUT DATA
- The user gives input data to the program by
answering questions put by the program - 2. Hard coding, in data given in the program as
assignments - 3. In data read from file
- OUT DATA
- Written to screen (terminal output)
- Written to file
52Numeriska beräkningar i Naturvetenskap och Teknik
Input/Output gtgt svar input(give input
value) give input value10 svar 10 gtgtsvarinpu
t(give input value) give input
valueabc svar abc Write to screen
with disp gtgtdisp(svar) abc
53Numeriska beräkningar i Naturvetenskap och Teknik
M-filer In MATLAB one may write programs or
scripts in so-called m-files using a built in
editor a debug utility. For larger programs
functions are often put in separate m-files. Open
the editor by gtgtedit
54Numeriska beräkningar i Naturvetenskap och Teknik
DEMO Calculate arctan(x) using the series
55Numeriska beräkningar i Naturvetenskap och Teknik
Read/Write to/from files 1. Save workspace
save myfile saves all variables in myfile.mat
load myfile.mat reads all variables from myfile
alt. save myfile a b c saves the variables
a, b, c 2. Formatted reading and writing fp
fopen(namn,r), opens file for reading fp
fopen(namn,w), opens file for writing
56Numeriska beräkningar i Naturvetenskap och Teknik
Read/write to from files Close file
fclose(fp) --------------------------------------
---------------- Read from file
Afscanf(fp,formatcode, dim) dim n, read n
elements to A as column vector dim inf, read
all numbers in the file to A as column vector dim
m,n, m x n element to A as m x n matrix
-------------------------------------------------
----- write to file Afprintf(fp,formatkod, A,
dim) Format codes e, E exponent form with
small/large e f, decimal form, u integer, s
string, \n ny rad
57Numeriska beräkningar i Naturvetenskap och Teknik
Input/Output Mer sofistikerad utskrift fprintf(f
ormatkod,x) Format codes a.bf decimal form, a
figures with b decimal figures, right
justified a.be exponent, small e a.bE exponent,
large E u heltal gtgta 1.1234 gtgtfprintf(the
number is 4.2f,a) The number is 1.23