Presentation is loading. Please wait.

Presentation is loading. Please wait.

Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Similar presentations


Presentation on theme: "Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part."— Presentation transcript:

1 Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.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: p=35f7440cdc9b4ab6bc38d380d9b3c4aa&pi=0 Numeriska beräkningar i Naturvetenskap och Teknik

2 Part A, Technical aspects and the use of MATLAB 1.Short history. Why machine based computing? 2.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 Numeriska beräkningar i Naturvetenskap och Teknik

3 Why compute using machines and numerical methods? 1. 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 3. 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. Numeriska beräkningar i Naturvetenskap och Teknik

4 Wilhelm Shickard: 1592 – 1635 From Tuebingen, Germany. Designed mechanical calculator for addition of six figure numbers. Some issues remain unclear. Limited future influence. Reconstructed. Numeriska beräkningar i Naturvetenskap och Teknik 1623

5 1670 Numeriska beräkningar i Naturvetenskap och Teknik Blaise Pascal: Invented the so called ”Pascaline” around The purpose was to simplify his father’s work as tax collector in Rouen, France. The machine could add and multiply. Subtractions was complicated and time consuming. 1645

6 Gottfried Leibniz: Constructed in 1670 the first machine that could do all the four basic algebraic operations Numeriska beräkningar i Naturvetenskap och Teknik

7 Charles Xavier Thomas de Colmar: 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 Numeriska beräkningar i Naturvetenskap och Teknik

8 Charles Babbage: 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. Numeriska beräkningar i Naturvetenskap och Teknik

9 Georg and Edvard Scheutz: and Numeriska beräkningar i Naturvetenskap och Teknik

10 Alan Turing: 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. Konrad Zuse: Constructed in 1941 the first programmable computer based on telephone relays partly financed by ”Deutsche Versuchsanstalt fur Luftfarth” Numeriska beräkningar i Naturvetenskap och Teknik

11 John von Neumann: 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. Numeriska beräkningar i Naturvetenskap och Teknik Johnny vN Morgenstern

12 John von Neumann: 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”. Numeriska beräkningar i Naturvetenskap och Teknik Oppie Feynman Ulam CU ALU INOUT MEM CP U

13 SOME BASIC CONCEPTS Numeriska beräkningar i Naturvetenskap och Teknik

14 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. Numeriska beräkningar i Naturvetenskap och Teknik

15 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. Numeriska beräkningar i Naturvetenskap och Teknik

16 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. Numeriska beräkningar i Naturvetenskap och Teknik

17 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. Numeriska beräkningar i Naturvetenskap och Teknik

18 Interpreted and compiled programming languages Source code Machine code Compiler Interpreter Performed once Produces an executable file Performed every time program runs BASIC, different scripting languages (Perl, Ruby) FORTRAN, C, C++ Produces executable code line-by-line Rel. slow Quick Java: byte code compiler + Virtual machine -> machine code => Portability (compile once run everywhere) MATLAB Numeriska beräkningar i Naturvetenskap och Teknik

19 MATLAB as calculator: >> 2 * 2 ans = 4 >> ans*2 ans =8 The latest answer stored in ans >> pi ans = Command window i MATLAB Numeriska beräkningar i Naturvetenskap och Teknik

20 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. Numeriska beräkningar i Naturvetenskap och Teknik

21 Look at the trivial example >> A=1 A = 1 >> B=2 B = 2 >> C=A*B C = 2 Numeriska beräkningar i Naturvetenskap och Teknik

22 Och jämför med: >> m=1 m = 1 >> a=2 a = 2 >> F=m*a F = 2 >> Numeriska beräkningar i Naturvetenskap och Teknik

23 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. Numeriska beräkningar i Naturvetenskap och Teknik

24 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: >> A=1.234 A = A is a decimal number (a floting point number or a float) Numeriska beräkningar i Naturvetenskap och Teknik

25 Variables >> b=[1;2;3] b = b is a vector >> B= [1 2 3; 4 5 6;7 8 9] B= B is a matrix Matrices can have more than two dimensions Numeriska beräkningar i Naturvetenskap och Teknik

26 Variables One can also write >> b(1)=1 b =1 >>b(2) =2 b=1 2 >>b(3) =3 b=1 2 3 Good in programs… Numeriska beräkningar i Naturvetenskap och Teknik

27 Variables In the same way >> A(1,1)=1 A = 1 >> A(1,2) = 2 A = 1 2 >>A(2,1) = 3 A = >>A(2,2) = 4 A = Add index for more dimensions. One can add matrices to matrices… and matrices to matrices of higher dimension… Numeriska beräkningar i Naturvetenskap och Teknik

28 Special vectors >>a=1:10 ans= >>a=0:0.1:1 ans= 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(i:j) sub vector of elements i till j x(i:k:j) sub vector of elements i to j at step k x([i1.... ip]) sub vector of given elements Numeriska beräkningar i Naturvetenskap och Teknik

29 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 Numeriska beräkningar i Naturvetenskap och Teknik

30 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. Numeriska beräkningar i Naturvetenskap och Teknik

31 Assignments Note that an assignment is not the same as an equation! >>x = 1 x=1 >>x = x +1 x=2 i.e. to the value in the memory position of x (=1) 1 is added giving the result 2. >>workspace -> gives a list of all variables Numeriska beräkningar i Naturvetenskap och Teknik

32 Two results that may indicate a failed calculation Inf (Infinity) >>a=2 a=2 >>a/0 built in ‘exception handler’ ans = inf NaN (Not a Number) >> 0/0 ans = NaN Numeriska beräkningar i Naturvetenskap och Teknik

33 Assignments & operators: The standard operators can be used as expected: addition + subtraction - multiplication * division / exponent ^ Same order of priority as usual >>a=2*3-1*2 a=4 >>a=2*(3-1)*2 a=8 Numeriska beräkningar i Naturvetenskap och Teknik

34 Assignments & operators A matrix multiplied by a scalar: >>A=[1 2 3; 1 2 3; 1 2 3]; >>c = 2; >>B=c*A B= but… Numeriska beräkningar i Naturvetenskap och Teknik

35 Assignments & operators: Elementwise multiplication with.* >> A.*B Similarly elementwise division./ Numeriska beräkningar i Naturvetenskap och Teknik

36 Assignments & operators: Usual matrix multiplication, number of rows of A equal to the nr of columns in B: >> A*B Other functions: Transpose: A’ Inverse: inv(A) Determinant: det(A) Numeriska beräkningar i Naturvetenskap och Teknik

37 Assignment & operators Scalar and vector products: >>a = [1 2 3]; >>b = [1 2 3]; >>c = dot(a,b) ans = 14 >>cross(a,b) ans = 0 Numeriska beräkningar i Naturvetenskap och Teknik

38 Why programs? 1.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 Numeriska beräkningar i Naturvetenskap och Teknik

39 To think about before and while you program 1.Define the general problem 2.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? 5.If necessary make flow chart 6.Debug while writing. Never write from A to Z and expect it to work. 7.Document continuously, use comments in the program as well as notes Numeriska beräkningar i Naturvetenskap och Teknik

40 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 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! Numeriska beräkningar i Naturvetenskap och Teknik

41 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 Numeriska beräkningar i Naturvetenskap och Teknik

42 How to define a condition? Numeriska beräkningar i Naturvetenskap och Teknik

43 Logical expressions: Expressions with an answer of type true or false, represented by 1 or 0 a=1;b=2, a==b false, &, |, ~ < <= == >= ~= (not equal to) MATLAB specific any(arg) any element = all(arg) all elements = Numeriska beräkningar i Naturvetenskap och Teknik

44 Flow paths If-statements if logical expression if a~=1 statements disp(a) endif end Can be expanded with else: if logical expression if a==1 statements disp(a) else else satsgrupper disp(b) endif end Numeriska beräkningar i Naturvetenskap och Teknik

45 Alt. If logical expression statement elseif logical expression statement elseif logical expression statement.... else statement end Numeriska beräkningar i Naturvetenskap och Teknik

46 Switch statements switch variable switch a case value1 case {1} statements disp (a) case value2 case {7} statements b=input(’give b’).... case value3 case {11.7} statements c=23 otherwise otherwise statements a=a+23 end end Numeriska beräkningar i Naturvetenskap och Teknik

47 For loop: for variabel = a:h:bfor a=0:0.1:10 statements b=b+a end While loop: while logiskt uttryck while a

48 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. Numeriska beräkningar i Naturvetenskap och Teknik

49 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….) Numeriska beräkningar i Naturvetenskap och Teknik

50 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 f2 global x y z t f3 q t r s Numeriska beräkningar i Naturvetenskap och Teknik

51 Input data to a program and output data from a program constitutes so-called i/o INPUT DATA 1.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 1.Written to screen (terminal output) 2.Written to file Numeriska beräkningar i Naturvetenskap och Teknik

52 Input/Output >> svar = input(‘give input value:’) give input value:10 svar= 10 >>svar=input(‘give input value:’) give input value:’abc’ svar= abc Write to screen with disp >>disp(svar) abc Numeriska beräkningar i Naturvetenskap och Teknik

53 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 >>edit Numeriska beräkningar i Naturvetenskap och Teknik

54 DEMO Calculate arctan(x) using the series: Numeriska beräkningar i Naturvetenskap och Teknik

55 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 Numeriska beräkningar i Naturvetenskap och Teknik

56 Read/write to from files Close file: fclose(fp) Read from file: A=fscanf(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: A=fprintf(fp,formatkod, A, dim) Format codes %e, %E exponent form with small/large e %f, decimal form, %u integer, %s string, \n ny rad Numeriska beräkningar i Naturvetenskap och Teknik

57 Input/Output Mer sofistikerad utskrift: fprintf(formatkod,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 >>a = ; >>fprintf(‘the number is %4.2f’,a) The number is 1.23 Numeriska beräkningar i Naturvetenskap och Teknik


Download ppt "Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part."

Similar presentations


Ads by Google