Policy/grading • • • • • • • • • • • If the door is closed please do not enter to the class. Door will be opened again after ~10 min for you to come in. If you arrive later, please do not disturb just wait for the next class. Grading: laboratory work: %20, midterms: 22.5% (each), final: 35% computer skills: each students is assumed to be at least familiar with the pc, and mostly used engineering tools/software. Octave will be used throughout the course. Attendance: compulsory (80% show-up in attendance records), FA letter will be assigned to those who have less than 80%. Textbook: by Steven C. Chapra and Raymond Canale: Numerical Methods for Engineers, McGraw-Hill. Laboratory: Lab session will involve programming of OCTAVE code. The subject of the session will be related with the theory covered in the classroom. We will try to assign each lab session with a clearly stated task. After completing the lab session, students will have written a piece of computer code that performs the assigned task. Lab performance of each student will be evaluated on a weekly basis. The students’ performance will be marked depending on: the level of attention, the level of effort, and the level of success displayed by the student during the lab session. Those activities that result with an UNSATISFACTORY performance are WEB SURFING, CHATTING, or exchanging EMAILS with other students. (If, the student continues these activities after a warning, he/she will be DISMISSED OFF that lab session, will be MARKED OFF the attendance sheet. The lab marks will be added up at the end of the semester, and will contribute to the students' overall cumulative as indicated on the above table. Up to four homework assignments will be assigned throughout the semester. Some assignments may receive a higher credit relative to others depending on the level of complexity of the expected work. It is strongly recommended to take the lab sessions seriously throughout the semester as they will also be crucial in understanding the practical aspects of the subject matter and obtaining a good grade. 1 Part 1 Chapter 1 Mathematical Modeling, Numerical Methods, and Problem Solving 2 A Simple Mathematical Model • A mathematical model can be broadly defined as a formulation or equation that expresses the essential features of a physical system or process in mathematical terms. • Mathematical Models can be represented by a functional relationship between dependent variables, independent variables, parameters, and forcing functions. 4 Model Function independent Dependent forcing f , parameters, variable variables functions • Dependent variable - a characteristic that usually reflects the behavior or state of the system • Independent variables - dimensions, such as time and space, along which the system’s behavior is being determined • Parameters - constants reflective of the system’s properties or composition • Forcing functions - external influences acting upon the system 5 A simple Mathematical Model Problem of a falling object in air: FD cd v 2 Fg= Force of gravity FD=Drag force m=mass v(t)= Velocity of the object cd= Drag coefficient m Fg mg Newton’s 2nd law: Fnet Fg FD ma m mg cd v 2 m c dv g d v2 dt m dv dt dv dt (Equation of motion) v v(t ) An Ordinary Differential Equation (ODE) Need to solve for v(t) 6 Analytical Solution: cd 2 dv g v dt m Initial condition: The object is initially at rest (using Calculus) v v(t ) t0 ; v0 Dependent variable - velocity v Independent variables - time t Parameters - mass m, drag coefficient cd Forcing function - gravitational acceleration g gcd gm tanh t cd m Terminal velocity t t (s) v (m/s) 0 0 2 18.7292 4 33.1118 6 42.0762 8 46.9575 10 49.4214 12 50.6175 51.6938 7 Numerical Solution: cd 2 dv g v dt m Reformulate the problem so that it can be solved by arithmetic operations dv v lim dt t 0 t dv v v(ti 1 ) v(ti ) dt t ti 1 ti v(ti 1 ) v(ti ) c g d v(ti ) 2 ti 1 ti m Finite Difference Approximation (from Calculus) (Since t is finite, we put in the equation) ti= initial time v(ti)= velocity at initial time ti+1= later time v(ti+1)= velocity at later time t=difference in time v=difference in velocity 8 • To solve the problem using a numerical method, note that the time rate of change of velocity can be approximated as: dv v vti1 vti dt t ti1 ti 9 (rearrange) cd v(ti 1 ) v(ti ) g v(ti ) 2 ti 1 ti m Recursion relation ODE transformed into an algebraic equation. can find new v(ti+1) at ti+1 from old v(ti) at ti using arithmetic operations. still need to have initial conditions from the physics of the problem (t=0 ; v=0) (given). t (s) v (m/s) 0 0 2 19.6200 4 36.4137 6 46.2983 8 50.1802 10 51.3123 12 51.6008 51.6938 (for t=2 s) v Terminal velocity (numerical solution) (analytical solution) 10 t Bases for Numerical Models • Conservation laws provide the foundation for many model functions. change= increase - decrease • Different fields of engineering and science apply these laws to different paradigms within the field. • Among these laws are: Conservation of mass Conservation of momentum Conservation of charge Conservation of energy 11 12 Summary of Numerical Methods • The book is divided into five categories of numerical methods: 13 • • • Mathematical models are always needed in solving engineering problems. Many times, these mathematical models are derived from engineering and science principles (Newton’s 2nd Law for instance), while at other times the models may be obtained from experimental data. Mathematical models generally result in need of using mathematical procedures that include but are not limited to (A) differentiation, (B) nonlinear equations, (C) simultaneous linear equations, (D) curve fitting by interpolation or regression, (E) integration, (F) differential equations (G) optimization These mathematical procedures may be suitable to be solved exactly as you must have experienced in the series of calculus courses you have taken, but in most cases, the procedures can be solved approximately using numerical methods. Since there is an approximation, errors always arise during calculations 14 Lab related 15 Computer Programming It is the comprehensive process of (problem algorithm coding executables) Algorithms: An algorithm is the step-by-step procedure for calculations. It is a finite list of well-defined instruction for calculting a function. Can be expressed in many ways: flowcharts, pseudocodes, etc. Programming lanuguages express algorithms so that they can be executed by a computer. 16 Flowcharts: A flowchart is a type of diagram that represents an algorithm. Steps are shown by boxes of various kinds. The order of the flow is shown by arrows. Monopoly flowchart 17 Flowchart Symbols Terminal Start and End of a program Flowlines Flow of the logic Process Calculations or data manıpulations Input/Output Input or output of data and information Decision Comparison, question, or decision that determines alternative paths to be followed. On-page connector marks where the flow ends at one spot on a page and continues at another spot. Off-page connector Marks where the algorithms ends on one page and continues at another 18 A simple addition algorithm The same algorithm using a flowchart using natural language Start Step 1: Start the calculation Step 2: Input a value for A Step 3: Input a value for B Step 4: Add A to B and call the answer C Step 5: Output the value for C Step 6: End the calculation Input A Input B Add A and B Call the result C Output C end 19 Flowchart example for calculating factorial N (N!) 20 Pseudocodes: Pseudocode is a higher-level method for describing an algorithm. It uses the structural convention of a programming language but is intended for human reading rather than machine reading. It is easier for people to understand than a programming code. It is environment-independent description of the key principles of an algorithm. It omits the details not essential for human understanding of the algorithm (such as variable declarations). It can also advantage of natural language. It is commonly used in textbooks and scientific publications. No standard for pseudocode syntax exists. 21 Example 1: Example 2: 22 Flowchart Pseudocode 23 Structured programming: It is an aim of improving the clarity, quality, and development time of a computer program by making extensive use of subroutines, block structures, for and while loops. Use of “goto” statements is discouraged, which could lead to a “spaghetti code” (which is often hard to follow and maintain). Programs are composed of simple, hierarchical flow structures. Many languages support and encourage structural programming. Modular programming: A kind of structural programming that the act of designing and writing programs (modules) as interactions among functions that each perform a single-well defined function. Top-down design. Coupling among modules are minimal. 24 Octave/Matlab Fundamentals Command window: to enter commands and data. Graphics window: to plot graphics. Edit window: create and edit M-files. Command window: Can be operated just like a calculator >> 55-16 ans= 39 Define a scalar value >> a=4 a= 4 Assignments can be suppressed by semicolon (;) >> a=4; (just stored in memory w/o displaying) 25 Can type several commands on the same line by seperating them with comas or semicolons. If you use semicolon, they are not displayed. >> a=4, A=6; x=1; a= 4 (MATLAB treats names case-sensitive , i.e. a is not same as A in above example) Can assign complex values as MATLAB handles complex arithmetic automatically: >> x=2+i*4 x= 2.0000 + 4.0000i Predefined variables: 26 >> pi If you desire more precision >> format long >> pi ans= 3.14159265358979 To return to four decimal version >> format short Arrays, vectors, matrices: An array is a collection of values represented by a single variable name. Matrcies are two-dimensional arrays. In MATLAB every value is a matrix: a scalar: 1x1 matrix a row vector: 1xn matrix A column vector: nx1 matrix 27 Square brackets ( [ ] ) are used to define an array in command mode. >> a= [ 1 2 3 4 5] a= 1 2 3 4 5 is a 1x5 row vector. In practive, a vector is usually meant to be a column vector. So, column vectors are more practical. We can define them by the transpose operator (‘) >> b = [ 2 4 6 8 10]’ b= 2 4 6 8 10 28 A matrix of values can be assigned as follows: >> A = [1 2 3 ; 4 5 6; 7 8 9] A= 1 2 3 4 5 6 7 8 9 Alternatively “Enter” key can be used at the end of each row to define A: >> A =[ 1 2 3 4 5 6 7 8 9 ]; (strike Enter key after 3 and 6) To see the list of all variables at any session: >> who Your variables are: A a ans b x 29 If you want more detail: >> whos Name Size Bytes Class A 3x3 72 double array a 1x5 40 double array ans 1x1 8 double array b 5x1 40 double array x 1x1 16 double array (complex) Grand total is 21 elements using 176 bytes To see an individual element in an array: >> b(4) ans= 8 >> A(2,3) ans= 6 30 Some predefined matrices are very useful. >> E= zeros(2,3) E= 0 0 0 0 >> u=ones(1,3) 0 0 u= 1 1 1 Colon (:) operator is very useful to generating arrays: >> t=1:5 t= 1 2 3 4 5 If you want increment other than 1, then you type: >> t= 1:0.5:3 t= 1.0000 1.5000 2.000 2.500 31 3.0000 Negative increments can also be defined: >> t= 10: -1: 5 t= 10 9 8 7 6 5 Colon (:) can also be used to select individual rows: >> A (2,:) ans= 4 5 6 returns the second row of the matrix. We can also use colon (:) to extract a series of elements from an array >> t(2:4) ans= 9 8 7 Second through fourth elements are returned. 32 Mathematical Operations: The common operators, in order of priority ^ Exponentiation - Negation * / Multiplication and Division \ Left division (in matrix algebra) + - Addition and Subtraction >> y = pi/4; >> y ^ 2.45 ans= 0.5533 To override the priorities use paranthesis: >> y = (-4) ^ 2 y = 16 33 The real superiority of MATLAB comes in to carry out vector/matrix operation Inner product (dot product) of two vectors: >> a*b ans= 110 Multiply vector with matrices >> a = [ 1 2 3]; >> a*A ans= 30 36 42 Multiply matrices >> A*A ans= 30 36 66 81 102 126 42 96 150 A^2 will return the same result. 34 If the inner dimensions are not matched, you get an error message: >> A*a ??? Error using ==> mtimes Inner matrix dimensions must agree. MATLAB normall treat simple arithmetic operations in vector/matrix operations. You can also do an element-by-element operation. To do that you put a dot (.) in front of the arithmetic operator. >> A .^ 2 ans= 1 16 49 4 25 64 9 36 81 35 Built-in Functions: MATLAB is very rich in predefined functions (e.g., sqrt, abs, sin, cos, acos, round, ceil, floor, sum, sort, min, max, mean,…) For a list of elementary functions: >> help elfun They operate directly on matrix quantities. >> log (A) ans= 0 1.3863 1.9456 0.6931 1.6094 2.0794 1.0986 1.7918 2.1972 36 Graphics: Consider plotting time-versus-velocity for the falling object in air. The solution to the problem was: v(t ) gcd gm tanh t cd m First need to define the time array: >> t=[0:2:20]’; This will define time (t) as 0,2,4..20. Total number of elements: >> length(t) ans= 11 Assign values to the parameters: >> g = 9.81 ; m = 68.1 ; cd=0.25 ; Now calculate (v): >> v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t); 37 To plot t versus t: >> plot(t,v) A graph appears in a graphics window. You can add many properties to the graph. For example >> title ‘A falling object in air’ >> xlabel ‘t in second’ >> ylabel ‘v in meter per second’ >> grid If you want to see data points on the plot: >> plot (t,v,’o’) If you want to see both lines and points on the same plot >> plot(t,v) >> hold on >> plot (t,v,’o’) >> hold off 38 Programming with Matlab M-files: We use the editor window to generate M-files. M-files contain a series of statements that can be run all at once. Files are stored with extension .m M-files can be script files or function files. Many built-in functions are all given in the form of M-files. 39 Script files: merely a series of Matlab commands that are saved on a file. They can be executed by typing the filename in the command window. Consider plotting the v(t) of the falling object problem. A script file can be typed in the editor window as follows: t=[0:2:20]’; g = 9.81 ; m = 68.1 ; cd=0.25 ; v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t); plot(t,v) title ‘A falling object in air’ Xlabel ‘t in second’ Ylabel ‘v in meter per second’ grid 40 This script can be saved as an “.m” file and be executed at once in Function files: M-files that start with the word function. Unlike script files they can accept input arguments and return outputs. They must be stored as “functionname.m”. Consider writing a function freefall.m for the falling body problem: function v = freefall(t,m,cd) % Inputs % t(nx1) = time (nx1) in second % m = mass of the object (kg) % cd = drag coefficient (kg/m) % Output % v(nx1) = downward velocity (m/s) g = 9.81 ; % acceleration of gravity v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t); return 41 Structured programming in Matlab: Simplest M-file instructions are performed sequentially. Program statements are executed line by line at the top of the file and moving down to the end. To allow non-sequential paths we use - Decisions (for branching of flow) Relational operators - if structure - if…else structure - if…elseif structure - switch structure - Loops (repetitions) - for … end structure == Equal ~= Not equal < Less than > Greater than <= Less than or equal to >= Greater than or equal to - while structure - while … break structure 42 Excel It is a spreadsheet application. Uses a grid of cells arranged in numbered rows and letter-named columns for data manipulations. Maximum of 1048K rows , and 16K columns. (version 12.0). It features calculations, graphing, pivot tables, etc. A wide variety of graphing tools, e.g. plotting, charting, histograms, etc. A wide variety of simple built-in functions for statistical, financial, and engineering calcualtions. It is embeded programming language (Visual Basic for Applications, VBA). Easy way to generate VBA files by macro recording. File formats: archive) .xlsx: Excel workbbok w/o macro (a ZIP compressed 43
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )