• 沒有找到結果。

Example: break in Infinite Loops

N/A
N/A
Protected

Academic year: 2022

Share "Example: break in Infinite Loops"

Copied!
41
0
0

加載中.... (立即查看全文)

全文

(1)

Example: break in Infinite Loops

Write a program which calculates log10(x ) with input x : If x > 0, then output log10(x );

If x = −1, then exit the program;

Otherwise, display “Only positive numbers!” in the screen.

Besides, the program terminatesonly when x = −1.

Input: x

Output: log10(x ) if x > 0

(2)

Solution 1

1 clear all;

2 clc

3 % main

4 while 1

5 x=input('Enter a number: ');

6 if x>0

7 y=log10(x)

8 elseif x==-1

9 break;

10 else

11 disp('Invalid input. Try again.');

12 end

(3)

Solution 2

1 clear all;

2 clc

3 % main

4 x=input('Enter a number: ');

5 while x~=-1

6 if x>0

7 y=log10(x)

8 else

9 disp('Invalid input. Try again.');

10 end

11 x=input('Enter a number: ');

12 end

(4)

How many levels can one break break?

1

In nested loops,breakexits from the innermost loop only.

1 clear all;

2 clc

3 % main

4 for i=1:5

5 for j=1:i

6 if i==3

7 break;

8 end

9 fprintf('*');

10 end

(5)

Exercise: while Loop By for Loop

Redo the problem in p. 12 by replacing a whileloop by a for loop and an ifstatement.

1 clear all;

2 clc

3 % main

4 s=0;

5 for i=1:inf

6 s=s+5*iˆ2-2*i;

7 if s>1e4

8 break;

9 end

10 end

11 i

12 s

(6)

Exercise

Gauss’ teacher asked him to add up all of the numbers 1 through 100 when he was 9.

Question: P100 i =1i =?

1 clear all;

2 clc

3 x = 0;

4 for i = 1:1:100

5 x = x+i;

6 end

7 x

(7)

Figure : Carl Friedrich Gauss (1777–1855)

(8)

Extension

Let n be an arbitrary positive integer given by the user.

Let Sn be the sum of 1, 2, . . . , n.

Show S1, S2, . . . , Sn.

Hint: You may need a nested for loop of two levels.

(9)

Solution 1

1 clear; clc;

2 % main

3 n = input('Please enter an positive integer: ');

4 y = zeros(1,n); % initialize an zero array of n ...

elements

5 for i = 1:n

6 for j = 1:i

7 y(i) = y(i)+j;

8 end

9 end

(10)

Solution 2

1 clear; clc;

2 % main

3 n = input('Please enter an positive integer: ');

4 y = zeros(n,1); % init a zero array of n elements

5 x = 0; % init to zero

6 y(1) = 1;

7 for i = 2:1:n

8 y(i) = y(i-1) + i;

9 end

(11)

Analysis of Algorithms In Nutshell

First, the algorithms for the same problem are supposed to be correct.

Then wecompare these algorithms.

The first question is, Which one is more efficient? (Why?) In algorithm analysis, we focus on the growth rateof the running time or space requirement as a function of the input size n, denoted by f (n).

(12)

O-notation

In math, O-notation describes the limiting behaviorof a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions.

Definition (O-notation) f (x ) = O(g (x )) as x → ∞ if and only if there is a positive constant c and a real number x0 such that

|f (x)| ≤ c|g (x)| ∀x ≥ x0. (1)

(13)

For example, 8n2− 3n + 4 ∈ O(n2).

(14)

O-notation is used to classify algorithms by how they respond to changes in input size.2

Time Complexity Space Complexity

In short, O-notation describes theasymptotic3 upper bound of the algorithm.

That is, the worst case we can expect.

(15)

Growth Rates for Fundamental Functions

4

(16)

Solution 1 vs Solution 2

Time Complexity

Solution 1 runs in O(n2) while Solution 2 runs in O(n).

So, we can say that Solution 2 ismore efficient5than Solution 1.

Space Complexity

Solution 1 and Solution 2 both have O(n).

(17)

Closed-Form Formulae

It’s well-known that Pn

i =1i = n(n + 1)

2 .

Moreover, it is also known that Pn

i =1i2= n(n + 1)(2n + 1)

6 , and

Pn

i =1i3= (n(n + 1) 2 )2. How about Pn

i =1ik for anyreal numberk?

(18)

Why Numerical Methods?

Numerical methods open a window for many complicated problems, even if thecorrectness of the numerical solution remains a big problem itself.

Simulation techniques significantly reduce the cost both in industry and science.

Note that the problems with analytic solutions are rare.

(19)

“All science is dominated by the idea of approximation.”

–Bertrand Russell (1872-1970)

“Essentially, all models are wrong, but some are useful.”

–George E. P. Box (1919-2013)

(20)

Exercise

Consider a 10-year deposit account.

You deposit 10,000 NTD in the beginning of each year6. Assume that the annual compounding interest rate is r = 10%.

Determine the compound amount at the end of 10 years.

The answer is175, 311.670611NTD.

(21)
(22)

Solution 1

1 clear all;

2 clc;

3 % main

4 format long g

5 s=1e4;

6 r=0.1; % Annual interest rate

7 for i=1:1:10

8 if i~=10

9 s=1e4+s*(1+r);

10 else

11 s=s*(1+r)

12 end

13 end

(23)

Solution 2

1 clear all;

2 clc;

3 % main

4 format long g

5 s=0;

6 r=0.1;

7 i=1;

8 while (i<=10)

9 s=s+(1+r)ˆi;

10 i=i+1;

11 end

12 s=1e4*s

Time complexity: O(n) Space complexity: O(1)

(24)

Solution 3

1 clear all;

2 clc;

3 % main

4 format long g

5 x=1e4;

6 r=0.1;

7 n=10;

8 s=x*(1+r)*((1+r)ˆn-1)/r

Time complexity: O(1) (Why?) Space complexity: O(1)

(25)

Extension: Floating Interest Rate

Instead of constant interest rate, the floating interest rates are given by

r = 0.1 : −0.01 : 0.01.

Then determine the compound amount of the previous example.

125, 743.635988833NTD

(26)

Solution

1 clear all;

2 clc;

3 % main

4 format long g

5 s=1e4;

6 r=0.1:-0.01:0.01; % Annual interest rate

7 for i=1:1:10

8 if i==10

9 s=s*(1+r(i))

10 else

11 s=1e4+s*(1+r(i));

12 end

(27)

Always Positive Interest Rate?

Draghi Unveils Historic Measures Against Deflation Threat (Jun 6, 2014 12:07 AM GMT+0800)

The ECB today cut its deposit rate tominus 0.1percent, becoming the first major central bank to take one of its main rates negative.

ECB降息市場反應激烈 歐元貶破1.3美元 (2014.09.05 04:13 am)

“. . .銀行存放央行的存款利率從負0.1%降至負0.2%. . .”

(28)

For Your Reference

10 Programming Tips For Beginners

If your code doesn’t work, don’t take it personally.

Google is your helper.

Reading error messages.

Why and what you declaring?

Construct your problem as per behavior.

Take a print of the statements!

Small issues can create bigger issues.

Switch off the monitor.

Writing code must be thefinalstep in finding solution to a problem and not the first.

The computer will do what you instruct it to do, in the order

(29)

Vectorization

7

MATLAB is optimized for array operations.

The built-in MATLAB functions such as sqrt(x) and exp(x) automatically operate on array argumentsto produce anarray result with the same size as the array argument x .

1 >> t=linspace(0,pi,5)

2 >> y=sin(t)

3

4 y =

5

6 0 0.7071 1.0000 0.7071 0.0000

(30)

Advantages

Appearance: Vectorized mathematical code appears more like the mathematical expressions found in textbooks, making the code easier to understand.

Less error prone: Without loops, vectorized code is often shorter.

Fewer lines of code mean fewer opportunities to introduce programming errors.

Performance: Vectorized code often runs much fasterthan the corresponding code containing loops.

(31)

Performance Analysis In Real Time

In addition to the theoretical analysis of algorithms8, programmers can also use a timerto measure performance.

Note that the results may differ depending on the difference of run-time environments.

Make sure that you benchmark the algorithms on the same conditions.

Once you identify which functions are consuming the most time, you can determine why you are calling them.

Then, look for ways tominimizetheir use and thus improve performance.

(32)

Example: tic-toc

tic starts a stopwatch timer.

toc reads the elapsed time from the stopwatch timer started by tic. (Try.)

Pros: More precise, ≈ 10−6 second.

Cons: Returns values only in second;

1 >> tic % Please wait for a second.

2 >> toc

3

4 Elapsed time is 2.279756 seconds.

(33)

Tips To Improve Performance

(Preallocate arrays) Repeatedlyresizingarrays often requires MATLAB to spend extra time looking for larger contiguous blocks of memory, and then moving the array into those blocks.

(Vectorize your code) Take advantage of the full functionality of MATLAB.

Element-by-element operationsdo help increase the performance.

(Exploit functions) Construct separate functions from the larger chunks of code.

Use functions instead of scripts because they are generally faster.

(Avoid overloading built-in functions) Overloading may negatively affect performance.

(34)

Example: Dynamic Allocation Is Poor

1 clear all;

2 clc

3 % main

4 tic

5 i=1;

6 for t=0:.01:100

7 y(i)=sin(t); % dynamic allocation of array y

8 i=i+1;

9 end

10 toc

11

12 clear y;

13 tic

(35)

1 Elapsed time is 0.069676 seconds.

2 Elapsed time is 0.000312 seconds.

This speedup9 is around 223.3.

Note that this number may be different computer by computer.

(36)

Element-By-Element Operations

Note that A. ∗ B is notequivalent to the inner product of A and B.

(37)

Example: Vectorization

1 clear all;

2 clc

3 % main

4

5 order=0:1:4;

6 t1=zeros(length(order),1);

7 t2=zeros(length(order),1);

8 t3=zeros(length(order),1);

9

10 for j=1:1:length(order)

11

12 tic

13 for i=0:1:10ˆorder(j)

14 y(i+1)=iˆ2; % dynamic allocation of array y

15 end

16 t1(j)=toc;

17

(38)

19 array len=length(0:1:10ˆorder(j));

20 y=zeros(array len,1); % preallocation of ...

array y

21 i=1;

22 tic

23 for i=0:1:10ˆorder(j)

24 y(i+1)=iˆ2;

25 end

26 t2(j)=toc;

27

28 clear y;

29 t=0:1:10ˆorder(j);

30 tic

31 y=t.ˆ2; % vectorization

32 t3(j)=toc;

(39)

37 ylabel('Speedup');

38 xlabel('Array Size');

39 figure(2),plot(order,log10(t1./t2),'b*:',...

40 order,log10(t1./t3),'r*:',order,log10(t2./t3),'g*:');

41 legend(['t1/t2';'t1/t3';'t2/t3']);

42 ylabel('Speedup (Log Scale)');

43 xlabel('Array Size (Log Scale)');

(40)

500 1000 1500 2000 2500 3000 3500

Speedup

t1/t2 t1/t3 t2/t3

(41)

0 0.5 1 1.5 2 2.5 3 3.5 4

−0.5 0 0.5 1 1.5 2 2.5 3 3.5 4

Array Size (Log Scale)

Speedup (Log Scale)

t1/t2 t1/t3 t2/t3

參考文獻

相關文件

In this report, formats were specified for single, double, and extended precisions, and these standards are generally followed by microcomputer manufactures using

Robinson Crusoe is an Englishman from the 1) t_______ of York in the seventeenth century, the youngest son of a merchant of German origin. This trip is financially successful,

fostering independent application of reading strategies Strategy 7: Provide opportunities for students to track, reflect on, and share their learning progress (destination). •

Now, nearly all of the current flows through wire S since it has a much lower resistance than the light bulb. The light bulb does not glow because the current flowing through it

An algorithm is called stable if it satisfies the property that small changes in the initial data produce correspondingly small changes in the final results. (初始資料的微小變動

Students were required to compare in the formulation stage as the case teacher asked them to look at additional mathematical relationships, whilst they were required to compare in

In the revised secondary mathematics curriculum, further applications of mathematical knowledge in more complex real-life situations, which require students to integrate their

(ii) “The dismissal of any teacher who is employed in the school – (a) to occupy a teacher post in the establishment of staff provided for in the code of aid for primary