error and error handling - 國立臺灣大學d00922011/matlab/281/20170419.pdf · repetitions if a...

28
Error and Error Handling You can issue an error if you do not allow the callee for some situations. 1 1 >> error('This is an error.'); Also, you can use a try-catch statement to handle errors. 1 try 2 % normal execution code 3 catch e % can be left blank 4 % error handling section 5 end 1 In other words, you can decide if the action can be performed. Zheng-Liang Lu 103 / 130

Upload: vothien

Post on 19-May-2019

228 views

Category:

Documents


0 download

TRANSCRIPT

Error and Error Handling

� You can issue an error if you do not allow the callee for somesituations.1

1 >> error('This is an error.');

� Also, you can use a try-catch statement to handle errors.

1 try2 % normal execution code3 catch e % can be left blank4 % error handling section5 end

1In other words, you can decide if the action can be performed.Zheng-Liang Lu 103 / 130

Example: Combinations

� For all nonnegative integers n ≥ k ,(nk

)is given by(

n

k

)=

n!

k!(n − k)!.

� Note that factorial(n) returns n!.

1 clear; clc;2

3 n = input('n = ? ');4 k = input('k = ? ');5 y = factorial(n) / (factorial(k) * factorial(n - k))6 disp('End of program.');

Zheng-Liang Lu 104 / 130

� Try n = 2, k = 5.

� factorial(−3) is not allowed!

� So your program stops in Line 5, and terminates abnormally.

� The reason is that Line 5 produces an error and the programis not designed to handle it.

� Then Matlab takes over and kills this program.

1 ...2 try3 y = factorial(n) / (factorial(k) * ...

factorial(n - k))4 catch e5 disp(['Error: ' e.message]);6 end7 disp('End of program.');

Zheng-Liang Lu 105 / 130

Exercise: Divided by Zero

� Write a program which calculates x/y for any two realnumbers x , y .

� The program restricts the user to do division by zero.

� Note that we don’t use this error-handling mechanism fornormal executions in regard to the performance!

1 ... % assume x = 1 any y = 02 if y == 03 error('Divided by zero!');4 else5 ans = x / y;6 end7 ...

Zheng-Liang Lu 106 / 130

Repetitions

� If a group of instructions is potentially repeated, you shouldwrap those in a repetition structure.

� Repetition structures are often called loops.

� All loops consist of 3 parts:� Define a loop variable which determines whether or not to

terminate the loop, based on a criterion.� Find a way to change the above variable each time through the

loop.2

� Organize the loop body which contains the repeated pattern.

2If not, then may be an infinite loop, that is, a loop never stops.Zheng-Liang Lu 107 / 130

� You should know how to discover the repeated pattern.

� Matlab provides two different types: the for loops and thewhile loops.

� Use for loops if you know the number of iterations.� Otherwise, use while loops.

Zheng-Liang Lu 108 / 130

for Loops

� A for loop is the easiest choice when you know how manytimes you need to repeat the loop.

1 for loopVar = someArray2 % body3 end

� Particularly, we often use for loops to manipulate arrays!

Zheng-Liang Lu 109 / 130

Zheng-Liang Lu 110 / 130

Example

1 for i = 1 : 102 disp(i);3 end

� Can you show the odd integers from 1 to 9?

1 for student = {'Arthur', 'Alice'}2 disp(cell2mat(student));3 % remember to take things out of cells4 end

� Clearly, Matlab has for-each loops, which is an enhanced onecompared to the naive one in C.

� Note that we use the function cell2mat so that a stringstored in the cell can be extracted as a string.

Zheng-Liang Lu 111 / 130

Example: Find Maximum (Revisited)

1 clear; clc;2

3 x = [4 9 7 2 -1 6 3]; % input list4 max = x(1);5 for i = 2 : 76 if max < x(i)7 max = x(i);8 end9 end

10 max

� Can you find the location of the maximum element?

� Try to find the minimum element and its location.

Zheng-Liang Lu 112 / 130

Example: Running Sum

� Write a program which calculates the sum of array elements.

1 clear; clc;2

3 x = 1 : 1 : 100;4 s = 0;5 for i = 1 : length(x)6 s = s + x(i); % running sum7 end8 s

� Use length(x) instead of 100 in Line 5.

� Then the loop will do as many times as the number ofelements in x .

Zheng-Liang Lu 113 / 130

Exercise: Estimating π by Monte Carlo Simulation3

� Write a program which estimates π by generating a certainnumber of sample points (x , y) and calculating

π̂ = 4× m

n,

where m is the number of points falling in the region of thequarter circle shown in the next page, n is the total number ofpoints, and π̂ is the estimate of π.

3Monte Carlo was a “code word” used in World War II to describesampling-based methods for neutron scattering computations associated withManhattan project.

Zheng-Liang Lu 114 / 130

Zheng-Liang Lu 115 / 130

1 clear; clc;2

3 n = 1e5;4 m = 0;5 for i = 1 : n6 x = rand(1);7 y = rand(1);8 if x ˆ 2 + y ˆ 2 < 19 m = m + 1;

10 end11 end12 estimated pi = 4 * m / n

� π̂ → π as n→∞ by the law of large numbers (LLN).4

� Try to vectorize this program.

4Seehttp://web.stanford.edu/class/cme308/OldWebsite/notes/chap3.pdf.

Zheng-Liang Lu 116 / 130

More Exercises

� Write a program to estimate√

5 by Monte Carlo.

� Write a program to estimate∫ 10 xdx by Monte Carlo.

� Write a program to estimate the call price of European optionby Monte Carlo.

Zheng-Liang Lu 117 / 130

while Loops

� The while loops are preferred when you need to keep repeatingthe instructions until a continuation criterion is not met.

1 while criterion2 % body3 end

� Note that before entering the while loop, the criterion will bechecked.

� Also note that the if statement is similar to the while loopexcept that the if statement executes only once.

Zheng-Liang Lu 118 / 130

Zheng-Liang Lu 119 / 130

Example: Compounding

� Let x be the initial amount of some investment, and r be theannual interest rate.

� Write a program which calculates the holding years n so thatthis investment doubles it value.

Zheng-Liang Lu 120 / 130

Solution

� In this case, we don’t know how many iterations we needbefore the loop.

1 clear; clc;2

3 curr = 100;4 goal = 2 * curr;5 r = 0.01;6 n = 0;7

8 while curr < goal9 curr = curr * (1 + r);

10 n = n + 1;11 end12 n

� Note that the criterion is to continue the loop.

Zheng-Liang Lu 121 / 130

Infinite Loops

1 while true2 disp('Press ctrl+c to stop me!!!');3 end

� Note that your program can terminate the program bypressing ctrl+c.

Zheng-Liang Lu 122 / 130

More Exercises

� Let a > b be two any positive integers.

� Write a program which calculates the remainder of a dividedby b.

� Do not use mod(a, b).

� Write a program which determines the greatest commondivisor (GCD) of a and b.

� Do not use gcd(a, b).

Zheng-Liang Lu 123 / 130

Numerical Example: Bisection Method for Root-finding

Zheng-Liang Lu 124 / 130

Problem Formulation

Input

- Consider f (x) = x3 − x − 2

- Initial search interval [a, b] for any real numbers a < b

- Error tolerance ε = 1e9

Output

- r̂ which approximates the exact solution r

� Note that a and b will be updated iteratively.

Zheng-Liang Lu 125 / 130

Solution

1 clear; clc;2

3 a = 0; b = 2; eps = 1e-9;4 iter = 0; % the number of iterations5

6 while b - a > eps7

8 c = (a + b) / 2;9 fa = a * a * a - a - 2;

10 fc = c * c * c - c - 2;11

12 if fa * fc < 013 b = c;14 else15 a = c;16 end17

Zheng-Liang Lu 126 / 130

18 iter = iter + 1;19 end20 r = c

Zheng-Liang Lu 127 / 130

−1 −0.5 0 0.5 1 1.5 2−3

−2

−1

0

1

2

3

4

c = 1.52137970691547

Zheng-Liang Lu 128 / 130

Remarks

� Note that this algorithm works well only with the premise thatthe behavior of the function in [a, b] is mild.

� Approximate solutions may be significantly influenced by theinitial interval [a, b].5

� Note that f (r) ≈ 0 but not equal to exactly 0. (Why?)

5You may try another algorithm for the root finding problem, say theNewton-Raphson method.

Zheng-Liang Lu 129 / 130

Exercise: Square Roots6

� Using the aforesaid bisection algorithm, write a function whichdetermines

√n for all n ∈ R+.

� It is easy to see that√n = x is equivalent to x2 − n = 0.

� So√n is the positive root of x2 − n = 0, which is the input of

the bisection algorithm.

� Trivially, a = 0.

� b = n if n > 1; b = 1, otherwise.

6Also see http://www.codeproject.com/Articles/69941/

Best-Square-Root-Method-Algorithm-Function-Precisi.Zheng-Liang Lu 130 / 130