2007/04/17 95503 統資軟體課程講義 95503 統資軟體課程講義 maple procedures...

Post on 17-Jan-2018

251 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

2007/04/17 AGENDA Anonymous procedures Procedures & data structures Procedure data structure Remember tables Recursion procedures Skills to create procedure &execution group

TRANSCRIPT

2007/04/17

9550395503 統資軟體課程講義統資軟體課程講義Maple Procedures

指導教授:蔡桂宏 博士學生 :熊承慧學號 : 95356053

2007/04/17

AGENDA• Difference• Main Topic• Execution Group Procedures• Parameter, Local, Global variables• Execution vs. Procedure• Use the Procedure• Maple function=procedure

2007/04/17

AGENDA• Anonymous procedures • Procedures & data structures• Procedure data structure• Remember tables• Recursion procedures• Skills to create procedure &execution group

2007/04/17

Difference

Underlying Idea• Maple expression~~ data structure• Maple function~~ procedureInitial Definition• Data structure~~ a collection of data• Procedure~~ a collection of instructions

2007/04/17

Main Topic

• Know the meaning of a collection of instructions• How to turn a collection of instructions into a

procedure• Know a procedure is more than a collection of

instructions• How mathematical functions can be represented

by Maple procedures• How procedures can manipulate data structures

2007/04/17

Execution Group Procedures• ex1:

Get the largest prime factor in a positive integer n> 650650; # Choose a positive integer.> ifactor( % ); # Factor it.> op( nops(%), % ); # Pick off the largest (i.e., last) factor.> op( 1, % ); # Get the base of the exponential.> op( 1, % ); # Remove the parentheses.

2007/04/17

Execution Group Procedures• 只要結果,把最後一行之前的;改成 :• 上頁是由許多不同的指令所組成的,想再使用時必須回到此指令所在處,更改 n 值,較為麻煩• 再使用 execution group 的方法就是轉換成 Procedure的型態 A. 命名 B. 改值 即可得到答案

2007/04/17

Execution Group Procedures> largest_prime := proc(n)> ifactor( n ); # Factor the input.> op( nops(%), % ); # Pick off the last factor.> op( 1, % ); # Get the base of the exponential.> op( 1, % ); # Remove the parentheses.> end;

•proc~~ end•Name it•Call the procedure•Input parameter: inside the parentheses after proc

2007/04/17

Execution Group Procedures• Calling the procedure> largest_prime( 650650 );

• With different input> seq( largest_prime(i), i=550550..550560);

PS : seq - create a sequence

Actual parameter

Print the last command

2007/04/17

Execution Group Procedures> plus := proc(x,y)> x - y;> x * y;> x + y; # This is the return value.> end;

plus( 3, 4 );

2007/04/17

Parameter, Local, Global variables> plus := proc(x,y)> local a, b; > global c;> a := x - y;> b := x * y;> c := x ^ y;> x + y; # the return value> end;

Parametervariables

localvariables

globalvariable

2007/04/17

Parameter, Local, Global variables

• local variables only "live" inside the procedure call.

• global variables inside procedure bodies are really the same as the variables we use in commands at our worksheet prompts.

2007/04/17

Parameter, Local, Global variables> plus( 2, 5 );

7> a; b; c;

a and b inside plus have no affect on the "global"

a and b

"global" variable c in our worksheet is the same

variable as the c inside plus > plus( -2, 2 );

> c;

> x; y;parameter variables are a

kind of local variable

2007/04/17

Execution vs. Procedure• ex2find the i 'th digit (from the right) of an integer• put commands in an execution group> n := 200!:> i := 50:> 10^(-i)*n: moves the decimal point to the left of the i'th digit of

> frac( % ): get the fractional part of the last result

> 10*%: moves the decimal point over to the right one place

> trunc( % ); truncates off the fractional part of the last result leaving us with just the digit we want

2007/04/17

Execution vs. Procedure• put commands into the body of a procedure> get_digit := proc(n,i)> 10^(-i)*n;> frac( % );> 10*%;> trunc( % );> end;

2007/04/17

~Command definition• frac - fractional part of a number> frac(8/3); 2/3• trunc - truncate a number to the next nearest

integer towards 0 These functions compute integer or fractional parts of

numbers. For real arguments x: For x >= 0, trunc(x) is the greatest integer less than or

equal to x. For x < 0, trunc(x) = -trunc(-x). > trunc(8/3); 2

2007/04/17

Use the Procedure

• Find the 15'th digit of 47! and the 257'th digit of 200!

> get_digit( 47!, 15 );> get_digit( 200!, 257 );• Get the expression sequence of a positive integer n’s

digits> n := 30!:> seq( get_digit(n, length(n)-i), i=0..length(n)-1 );

> { % };

2007/04/17

> plus := proc(x,y)> x+y;> end;

> plus( 5, plus(3,4) );

> plus := proc(u,v)> u + v;> end;

> evalb( proc(u,v) u+v end = proc(x,y) x+y end );

Use the Procedure

2007/04/17

~Some amazing property

• 3435~~ the sum of its digit raised to its own power > n := 3435;> L := digits( n );> add( i^i, i = L ); # Add up the digits raised to their own

power.

• 40585~~ factorians. > n := 40585;> L := digits( n );> add( i!, i = L ); # Add up the factorials of the digits of n.

2007/04/17

~Some amazing property

• digital invariant 2~~> n := 115132219018763992565095597973971522401;

> L := digits( n ); # There are 39 digits.

> add( i^nops([L]), i = L );

• digital invariant 1~~> n := 82693916578;> L := digits( n );> add( i^nops([L]), i = L ); # The power is the number of digits.

2007/04/17

Maple function=procedure

2007/04/17

Anonymous procedures

call the procedure

We can give the procedure a name

Call the procedure by its new name

2007/04/17

Anonymous proceduresConverting the procedures into execution groups

2007/04/17

Anonymous proceduresDefine ,call, and name the result in a single command

It’s still an anonymous procedure

Execution group

2007/04/17

~Command definition

• cat - concatenating expressions• The cat function is commonly used to

concatenate strings and names together. • A string is a sequence of characters that has no

value other than itself. It cannot be assigned to, and will always evaluate to itself.

• A string is written by enclosing any sequence of characters within a pair of double quote characters (" ").

2007/04/17

Procedures & data structures• Compute the average of two, three, and four numbers

2007/04/17

Procedures & data structures

• Call the procedures

2007/04/17

Procedures & data structures

• using a data structure to solve a programming problem

procedure to average any number of numbers. one input parameter, the input is a data structure

2007/04/17

Procedures & data structures

• Call the avg procedure

2007/04/17

Procedures & data structures• Input a list of lists, a list of polynomials, and

a list of sets

2007/04/17

Procedures & data structures

Rewrite the procedure using args and nargs

Call the new version of avg

args - The sequence of actual arguments

passed to a procedure

2007/04/17

Procedures & data structuresUse the args and nargs variables

Returns the actual parameter list

Counts how many parameter it was called with

2007/04/17

Procedures & data structures• Procedures work only in the way we want~ type declaration of formal parametersex: L represents a list of numbers

Type declaration is held in a “”data structure

2007/04/17

Procedures & data structures

Avg take only one input2 is not a list as we defined before

You have to input 3 numbers

correction

2007/04/17

Procedure data structure

• Procedures are another kind of data structure

Check the data type of f evaluation

Data type of f

Data type of f’s value

2007/04/17

Procedure data structure

• op shows us the definition of the procedure f

• Get the contents of the procedure data structure

2007/04/17

Procedure data structure• 8 operands in the procedure data structure

• What are the 8 operands ? Formal parameter names

Local variable names

optionsRemember table

Description string

Global variable namesLexical table

Return type

2007/04/17

Procedure data structure

• Show the data structure

2007/04/17

Procedure data structure• The option sections: The ``options'' part of a

procedure or module definition appears immediately after the declarations of local and global variables.

arrow builtin inline operator remember system trace copyright

2007/04/17

Procedure data structure

• The options arrow, builtin, inline, operator, and remember can be used only in procedure definitions.

• Option operator declares to the Maple system that the procedure was entered and is to be printed and otherwise manipulated as an operator.

2007/04/17

Procedure data structure

• The option trace can be used in procedure and module definitions.

• Option trace makes the procedure or module executeas though it were under a sufficiently high value of printlevel as to show the entry and exit calls and all the internal statements. This effect is independent of the value of printlevel, and is confined to the procedure or module that has the option.

• The option trace can help us finding mistakes.

2007/04/17

Procedure data structure

2007/04/17

Procedure data structure• define another procedure with the trace option th

at calls the procedure f

2007/04/17

Procedure data structure

args - The sequence of actual arguments

passed to a procedure

the result of f(2,2)

u in g

the result of f(3,3)

v in g

the result of g

2007/04/17

Procedure data structure• ex: input a name and a positive integer and trun

cates the name to the integer number of letters

2007/04/17

Procedure data structure• Find the mistake~ to reverse the letters in a name

error occurs here

Something wrong

2007/04/17

Procedure data structure• the correction

2007/04/17

Remember tables

• The remember table is accessible as operand 4 of the procedure structure--use op(4,eval(f)) if the name f has a procedure definition assigned to it. It can then be manipulated as an ordinary Maple table.

• Improving the computational efficiency • Giving Maple symbolic abilities• Save time but use more memory

2007/04/17

Remember tablesno remember

with rememberoption

2007/04/17

Remember tables• evaluate f at some input , remember table shows

• put more values in f’s remember table

2007/04/17

Remember tables• redefine the procedure

Call the first time

Call the second time

Call the first time

Call the second time

2007/04/17

Remember tables• speed up the calculations~ see the remember ex

2007/04/17

Remember tables• factor & expand remember table

2007/04/17

Remember tables• The Problem : Stale data

g calls h

Change the definition of h

You get the same answer

Remember table

2007/04/17

Remember tables

• Solve the problem “stale data” 1.restart or 2.forget

2007/04/17

Remember tables

• symbolic abilities sin(Pi/3) is in the remember table and make use of

it to compute sin(4*Pi/3).

Maple does not have this symbolic result in its remember table for sin.

2007/04/17

Remember tables• Teach Maple the value Maple does not

have this symbolic result

Teach Maple

2007/04/17

Remember tables• Another problem

The function doesn’t have any rule to compute.

f(x):=3*x^2-1 create a procedure with only remember table

containing one entry that defines the output of the function for the

single input x

2007/04/17

Remember tables

Redefine g

Incorrect ans

Check the definition of g in

another way

Check the definition of g

g(x):=100*x-1 didn’t redefine g, just give a remember table with

one entry in it

2007/04/17

Recursion procedures• A procedure is recursive which would mean that t

he procedure is defined in terms of itself. • It provides very compact and elegant solutions to

a programming problem. • It consumes massive amounts of computer memo

ry when executes. • Ex:n!=n*(n-1)! This recursive definition defines fac

torials in terms of factorials. The factorial symbol appears on both side of the equal sign in the definition.

• We don’t know when to stop. We need something to bring the “recursion” to a halt. For the factorial function, that something is the rule that 0!=1.

2007/04/17

Recursion procedures

• For the factorial function Recursion procedures, the rule 0!=1 can make it stop. With that rule the calculation of 5!

5! = 5*(4!) = 5*(4*(3!)) = 5*(4*(3*(2!))) = 5*(4*(3*(2*(1!)))) = 5*(4*(3*(2*(1*(0!)))))

• The complete recursive definition of the factorial function has two parts n! =n(n-1)! 0!=1

.

2007/04/17

Recursion procedures• When we write recursive procedures, we always have to do something to avoid infinite recursion.• We need a definition to stop the recursion after a finite number of steps (by using an if-then-else-fi )

2007/04/17

Recursion procedures• How to write the factorial recursion procedures?

The line of the procedure it calls itself,

the conditional statement that checks if the input is zero

2007/04/17

Recursion procedures

•compute some factorials using recursive procedure

•factorial function built into Maple so that we can check

2007/04/17

Recursion procedures• To visualize the workings of this recursive procedure

use right-quotes to delay the evaluation

call it and keep evaluating the output until it is fully evaluated.

2007/04/17

Recursion proceduresUse the option trace

2007/04/17

The trace of the output

2007/04/17

Recursion procedures

• ex: the procedure adds up all the numbers in a list

using “if-then-else-fi”

2007/04/17

Recursion procedures

add_list with option trace

add_list with delayed evaluation

2007/04/17

the addition gets done from right to left in the list, not from left to right

2007/04/17

2007/04/17

Difference here

less procedure

s

2007/04/17

Recursion procedures

• To find the largest number in a list of numbers.Step1: finds the larger of just two numbers

Step2: use bigger to create a recursion procedure biggest

2007/04/17

Recursion proceduresTest it

Test biggest on a list of randomly chosen integers

2007/04/17

Recursion procedures

• With “delay” evaluation

Something wrong

2007/04/17

Recursion procedures

• Fix the problem by modifying the definition of bigger

2007/04/17

Recursion procedures

• With “trace”

2007/04/17

Recursion proceduresThe result of option trace

2007/04/17

Recursion procedures

• Another way to visualize Only one trace here

2007/04/17

Recursion proceduresThe result of one trace

Call it

2007/04/17

Recursion procedures• Use the option remember in the recursion

procedures to save the timewithout remember~~ test the file: remember ex2

for

2007/04/17

Recursion procedures

• the tree diagram

Fib(28) 2 times,Fib(27)

3 times, Fib(26) 5times

and so on..

2007/04/17

Recursion procedures

• With remember:~~ test the file: remember ex3

2007/04/17

Recursion procedures

• another ex: a function f from the real line to the real line is periodic with period p if 0<p, and f(x+p)=f(x), for all real numbers x

• It’s almost a recursive definition since it defines f in terms of itself. But this definition is not recursive because it does not contain any kind of a terminating condition.

• How we adapt this definition to give a recursive definition of a specific periodic function?

2007/04/17

Recursion procedures• Let g be a function defined on the interval from a

to b, where a<b and b-a=p . • The recursive definition of a function f which is a

periodic extension of g to the whole real line is as follows

terminating condition

f is defined in terms of f

2007/04/17

Recursion procedures• ex:

• then:

2007/04/17

Recursion procedures• 1.define a, b, p, g

Continuous function

Expression of g

2007/04/17

Recursion procedures

• 2.define f

• evaluate f

• f has a limit of 0.36

2007/04/17

Recursion procedures

2007/04/17

Recursion procedures

• Try f using another g,g(x)=

Write the function of g

2007/04/17

Recursion procedures• g(x)=

Write the function of g

2007/04/17

Recursion procedures

• g(x)=

2007/04/17

Skills to create procedure &execution group

• to create many input lines that are needed :Ctrl-j• to combine the input lines into an execution

group : place the cursor on the first of the input lines and type

a.F4 key or b."Edit -> Split or Join -> Join Execution Groups" menu

item • Each time you hit the F4 key, the prompt below

the current execution group is merged into the current execution group.

• Undo: Ctrl-z

2007/04/17

• to split the execution group: place the cursor at the beginning of the line you want to split and type

a.F3 key or b."Edit -> Split or Join -> Split Execution Group" menu

item• to add a new line between two lines: after

splitting, a. place the cursor at the beginning of the line after the

line you want to add and type Ctrl-k or b. place the cursor at the beginning of the line before the

line you want to add and type Ctrl-j Then ……place the cursor at the beginning of the

first line and type F4 twice

2007/04/17

Skills to create procedure &execution group

• place the cursor at the end of the line before where you want to add, type Shift-Enter key combination). that this line does not have its own prompt on its left hand edge. This new line is really a continuation of the above line.

• If a procedure definition is short, it can fit on a single line.

ex: > test := proc(n::integer) 13*n; factor(n); end;

• But it’s better on several lines to make the definition easier to read.

2007/04/17

Place the cursor anywhere in this line and hit Enter. Maple gives you a new prompt, and also a warning. Just ignore the warning and type the command from. Then hit enter again.

enter the closing word (the end;) and hit Enter. Maple will give you the procedure definition.

2007/04/17

To create a multi-line for-loop or while-loop : after you typing the key word” for” on a line, keep hitting Enter to create new input lines until you enter the closing key word od (or end do

top related