0% found this document useful (0 votes)
4 views

Ch02_Programming_s

The document discusses numerical methods in programming, emphasizing the importance of using both available software and developing custom code. It covers structured programming, including algorithms, flowcharts, pseudocode, and logical representations such as sequence, selection, and repetition. Additionally, it introduces modular programming, programming errors, and various software tools like Excel and MATLAB for numerical analysis.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Ch02_Programming_s

The document discusses numerical methods in programming, emphasizing the importance of using both available software and developing custom code. It covers structured programming, including algorithms, flowcharts, pseudocode, and logical representations such as sequence, selection, and repetition. Additionally, it introduces modular programming, programming errors, and various software tools like Excel and MATLAB for numerical analysis.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

MAK 310

NUMERICAL METHODS
CHAPTER 2 – PROGRAMMING AND SOFTWARE

1
PACKAGES AND PROGRAMMING
Objective is how to use the computer as a tool to obtain numerical solutions to a given
engineering model.

There are two ways in using computers:


1) Use available software and their built-in functions.
2) Develop macros or code files to extend the software capability.

 Engineers should not be tool limited.


 It is important that they should be able to do both!
 Hence, they should learn to write programs and develop ways to solve their problems.

2
STRUCTURED PROGRAMMING
Algorithm: It is a form of step-by-step instructions to perform a specific task.

Structured programming: Set of rules that prescribe good style habits for the programmer
to code algorithms.

• Well-structured algorithms are


• easily sharable,
• easy to debug and test,
• requires a shorter time to develop, test, and update.

• Algorithms are represented by two approaches:


• flowchart
• Pseudocode
• These structures help the resulting computer code be clearer and easier to follow.
3
FLOWCHART
• A flowchart is a visual or graphical representation of an algorithm.
• The flowchart employs a series of blocks and arrows, each of which represents a
particular operation or step in the algorithm.

Flowchart Example

4
PSEUDOCODE
• A pseudocode uses code-like statements instead of the graphical symbols of the
flowchart.
• Some common conventions for the pseudocode :
• Keywords such as IF, DO, INPUT, etc., are capitalized.
• Conditions, processing steps, and tasks are in lowercase.
• Processing steps are indented.
• Keywords form a “sandwich” around the steps to visually define the extent of each
control structure.

Pseudocode Example
In this course, Pseudocode will be the main tool for
communicating algorithms.

5
LOGICAL REPRESENTATION - SEQUENCE
In an algorithm, there are mainly three logical representations:
• sequence
• selection
• repetition
Sequence: Shows that the computer code is to be implemented one instruction at a time
(i.e., step-by-step procedure).
• The structure can be expressed generically as a flowchart or as pseudocode.

6
LOGICAL REPRESENTATION - SELECTION
Selection: Splits the program’s flow into branches based on the outcome of a logical
condition.
Four ways for selection:
1) The single-alternative decision (IF/THEN):
• It allows for a detour in the program flow if a logical condition is
true.
• If it is false, nothing happens, and the program moves directly to the
next statement following the ENDIF.

2) The double-alternative decision (IF/THEN/ELSE):


• behaves in the same manner for a true condition.
• However, if the condition is false, the program implements the
code between the ELSE and the ENDIF.

7
SELECTION – Continued

3) Multiple alternative decision (IF/THEN/ELSEIF):


• ELSE clause of an IF/THEN/ELSE contains another IF/THEN.
• For such cases, the ELSE and the IF can be combined in
the IF/THEN/ELSEIF structure.
• At the end of the chain of conditions, if all the conditions
have tested false, an optional ELSE block can be included.

4) CASE structure (SELECT or SWITCH)


• Rather than testing individual conditions, the branching
is based on the value of a single test expression.
• Depending on its value, different blocks of code will be
implemented.
• An optional block can be implemented if the expression
takes on none of the prescribed values (CASE ELSE).
8
LOGICAL REPRESENTATION - REPETITION
Repetition: Instructions are implemented repeatedly.
Two ways of repetition:
1) Decision loop (DOEXIT LOOP):
• Also called a break loop (or midtest loop).
• It repeats until a logical condition is true.
• Pretest loop: The first block is not included, i.e., the logical test is
performed before anything occurs.
• Posttest loop: The second block is omitted.
• DOEXIT loop was introduced by Fortran 90 and used in Excel/VBA
• In MATLAB and C, WHILE structure is used instead of DOEXIT.

2) Count-controlled loop (DOFOR LOOP)


• The break loop in DOEXIT loop is called a logical loop because it
terminates on a logical condition.
• In contrast, a count-controlled or DOFOR loop performs a specified
number of repetitions, or iterations.
9
WRITING A PSEUDOCODE

10
EXAMPLE - SOLUTION
Pseudocode for the Example: An Improved Pseudocode:

Issues with the algorithm:

11
PSEUDOCODE FOR PARACHUTIST PROBLEM (self study)
Recall that, given an initial condition for time and velocity, the problem involved
iteratively solving the formula (Euler’s method)
where
Simple Pseudocode: Improved Pseudocode:

This algorithm will work only if the


computation interval is evenly divisible by
the time step.
To cover such cases, a decision loop can be
substituted in place of the shaded area in
the previous pseudocode.

12
MODULAR PROGRAMMING
Modular programming: The approach of dividing computer programs into small
subprograms, or modules, that can be developed and tested separately.

• In standard high-level languages such as Fortran 90 or C, the primary programming


element used to represent each module is the procedure.

• Two types of procedures:


• Functions: usually returns a single result
• Subroutines: usually returns several results

13
MODULAR PROGRAMMING EXAMPLE
Falling Parachutist: Euler Method in general: Using Modular Pseudocode of Euler
method for Parachutist Problem:
New value = old value + slope × step size Calling the Euler function to calculate
y = yi + dydt × h the output:

INPUT dt, ti, tf, yi


Pseudocode specific to Modular Pseudocode which can y = Euler(dt, ti, tf, yi)
Parachutist Problem: be used in any Euler problem
where y is the velocity (v) for
parachutist problem.

Slope for parachutist problem is defined


as another function:

FUNCTION dy (t, y)
g = 9.81
cd = 12.5
m = 68.1
dydt = g-(cd/m)*v
END dy
14
PROGRAMMING ERRORS
Syntax errors: Miswriting the commands. The code will not compile.
Run-time error: Program will compile, but stops running at some point. (e.g. due to
division by zero.)
Logical error: Program will compile and run, but the result is wrong.

A program is said to have a bug if it either contains a mistake that ends up with errors
or it does not function in the way it is intended to.

Debugging is the process of finding the root cause, workarounds and possible fixes
for bugs.

15
EXCEL®
• Excel is the spreadsheet produced by Microsoft, Inc.
• Spreadsheets are a special type of mathematical software that allow the user to
enter and perform calculations on rows and columns of data.
• Excel has some built-in numerical capabilities, including equation solving, curve
fitting, and optimization.
• It also has several visualization tools, such as graphs and three-dimensional
surface plots, that serve as valuable adjuncts for numerical analysis.
• It also includes Visual Basic (VBA) as a macro language that can be used to
implement numerical calculations.

Example Excel • We will not learn Excel in


spreadsheet for this course.
the parachutist • You can read Chapter 2.4
in your book to further
problem.
learn about Excel.

16
MATLAB®
• MATLAB is the software product of The MathWorks, Inc.,
• It was co-founded by the numerical analysts Cleve Moler and John N. Little.
• MATLAB was originally developed as a matrix laboratory.
• To this day, the major element of MATLAB is still the matrix.
• To the matrix manipulations, MATLAB has added a variety of numerical
functions, symbolic computations, and visualization tools.
• A MATLAB code can be directly written to MATLAB Command Window:

Example MATLAB • We will use MATLAB in this course.


code for the • Hence, you should read Chapter
parachutist 2.5 in your book to further learn
problem: about MATLAB.

• But the codes in MATLAB Command Window cannot be saved.


17
MATLAB M-FILE
• To save the written codes in a file, the code is written into an M-File.
• The extension of the saved M-file is “.m”.
• User inputs can be asked by the M-file through the Command Window.

Example – Parachutist problem: Ask the mass as a user input:

When you run this M-file, the Command Window the following prompt will show:

The user can then enter a value like 100, and the result will be displayed as

18
MATLAB CODE VS. PSEUDOCODE

19
MATLAB CODE FOR PARACHUTIST EXAMPLE (self study)
EXERCISE: Create an M-file in MATLAB by typing the following code and run it to get results.
g=9.81;
m=input('mass (kg): '); Once you save this as .m file and run the .m
cd=12.5; file in MATLAB,
ti=0; The following prompt should appear in the
tf=2;
vi=0; Command Window:
dt=0.1;
t = ti;
v = vi;
h = dt;
while (1) Type the value as 100 and you will have the
if t + dt > tf result as
h = tf - t;
end
dvdt = g - (cd/m) * v;
v = v + dvdt * h;
t = t + h;
if t >= tf, break, end
end
disp('velocity (m/s):')
disp(v)
20
MATLAB FUNCTION FOR EULER METHOD (self study)
Recall the Pseudocode for the EXERCISE: Write a MATLAB Then, write the following
Euler Method we defined before. function for the Euler method: commands to the
function yy = euler(dt,ti,tf,yi)
Command Window and
t = ti; get results:
y = yi;
h = dt; >> ti=0;
while (1)
if t + dt > tf
>> tf=2.;
h = tf - t; >> vi=0;
end >> dt=0.1;
dydt = dy(t, y); >>
y = y + dydt * h;
t = t + h;
euler(dt,ti,tf,vi,m,cd)
if t >= tf, break, end
end The answer will be
yy = y; displayed as
Save this function as “euler.m”.
Also Recall the Pseudocode for
the slope of parachutist problem: Write the slope function
and save as “dy.m”:
FUNCTION dy (t, y)
function dydt = dy(t, y)
g = 9.81, cd = 12.5, m = 68.1
g = 9.81; cd = 12.5; m = 68.1;
dydt = g-(cd/m)*v
dydt = g - (cd/m) * y;
END dy
21
OTHER LANGUAGES AND LIBRARIES
• Python
• Fortran
• C++
• Mathcad
• etc.

• In this course, our approach will be to provide you with well-structured procedures written as
pseudocode.

• This collection of algorithms then constitutes a numerical library that can be accessed to perform
specific numerical tasks in a range of software tools and programming languages.

• Our main programming software for demonstration will be MATLAB.

22

You might also like