Download presentation
Presentation is loading. Please wait.
Published byNeil Young Modified over 9 years ago
1
1 Maxima program control
2
2 Topics Branching Iteration
3
3 Branching
4
4 Branching controls the execution of a program Statements in a program are executed only if a condition holds. An informal example, not quite Maxima: if (gender is “male”) then use men’s room else use women’s room
5
5 Branching controls the execution of a program Statements in a program are executed only if a condition holds. Informal example, not quite Maxima: if ( gender is male ) then use men’s room else use women’s room Condition
6
6 A formal Maxima example if (gender = male) then print ("use men’s room") else print ("use women’s room"); Statement also uses the Maxima print function
7
7 Question – how does Maxima know the gender of the programmer?
8
8 The value had to have been initialized first. gender: male; We now think of sequences of Maxima instructions forming Maxima programs.
9
9 formal example has 3 words reserved in Maxima if (gender is male) then print ("use men’s room") else print ("use women’s room");
10
10 Another example if (flag = 1) then plot2d(f(x), [x, 1, 100]); else plot2d(g(x), [x, 1, 1000]);
11
11 Functions and if statements They can be combined: f(x):= if (x < 0) then 0 else if (0 <= x) and (x < 1) then x else 1
12
12 Functions and if statements They can be combined: f(x):= if (x < 0) then 0 else if (0 <= x) and (x < 1) then x else 1 Argument less than 0 Argument between 0 and 1 Any other value of the argument
13
13 What do we have to know about branches? What condition determines the choice of branch we want our program to execute? What happens in each branch? What is the value of the logical condition that determines the branch we take –Must know this before we start coding The syntax of an if-else statement
14
14 Formal syntax if cond_1 then expr_1 else expr_0 The value of this expression: –evaluates to expr_1 if cond_1 evaluates to true –otherwise the expression evaluates to expr_0.
15
15 The condition Must be able to be evaluated to either true or false. Uses operators for comparing things In nearly all situations, operators are one or more of –Relational operators –Logical operators
16
16 OperatorSymbolType Less than<Relational Less than or equal to <=Relational Greater than>Relational Greater than or equal to >=Relational
17
17 These are tricky – discuss later OperatorSymbolType equality (syntactic) =relational negation of =#relational equality (value)equalrelational negation of equal notequalrelational
18
18 OperatorSymbolType and logical or logical not logical
19
19 Some uses are obvious if (1 < 2) then print (1) else print("I love this course"); Output is 1 = 1
20
20 Some uses are obvious if (1 >= 2) then print (1) else print("I love this course"); Output is I love this course
21
21 if ((1 < 2) and (2 < 3)) then print(1) else print("I love this course"); Output is
22
22 Less obvious if ((1 < 2) and (2 < 3)) then print(1) else print("I love this course"); Output is 1 = 1 Note the use of parentheses
23
23 if ((1 3)) then print(1) else print("I love this course"); Output is
24
24 if ((1 3)) then print(1) else print("I love this course"); Output is I love this course
25
25 Let’s go back to the equality relational operators =, # equal, notequal = and # are by far the most common Even they do not quite behave the way you think We will avoid equal and notequal as much as we can
26
26 Examples of the use of = if (1 = 1) then print("use men’s room") else print("use women’s room"); Output: use men’s room
27
27 if (1 = 2-1) then print ("use men’s room") else ("use women’s room"); Output: use men’s room
28
28 if (1 = (2 + 4 + 6)/(6 + 4 + 2)*(2-1)) then ("use men’s room") else ("use women’s room"); Output: use men’s room
29
29 Unfortunately, Maxima doesn’t really understand = for everything if (1 = sin(x)^2 + cos(x)^2) then print("use men’s room") else print("use women’s room"); Output: use women’s room
30
30 More complex if-else statements if cond_1 then expr_1 elseif cond_2 then expr_2 elseif... else expr_0 evaluates to expr_k if cond_k is true and all preceding conditions are false. If none of the conditions are true, the expression evaluates to expr_0.
31
31 if (avg < 60) then print("F") elseif ((60 <= avg) and (avg < 70)) then print("D") elseif ((70 <= avg) and (avg < 80)) then print("C") elseif ((80 <= avg) and (avg < 90)) then print("B") else print(A);
32
32 Thing to note All cases are covered Parentheses were used to delimit every input to a relational operation such as and Code was indented consistently to make it more readable
33
33 There are shortcuts – you can omit the ending else if cond_1 then expr_1 is equivalent to if cond_1 then expr_1 else false
34
34 The same holds for elseif statements Try this one yourself
35
35 What happens if we omit the else? if (1 = (2 + 4 + 6)/(6 + 4 + 2)*(2-1)) then print("use men’s room"); Output is use men’s room Note that the condition in the parentheses evaluates to true.
36
36 if (1 = (2 + 4 + 6)/(6 + 4 + 2) * 2) then print("use men’s room"); Output is false Note that the condition in the parentheses evaluates to false. The phrase “use men’s room” never gets printed.
37
37 Iteration
38
38 We have already used one form of iteration: for i: 0 step 1 thru 9 do B[i] : 3 * i ;
39
39 Iteration in Maxima The idea: Identify statements you want to repeat Start the iteration, using an iterator Choose when to start Choose where to end Choose how large a step you make It’s just like walking!
40
40 This can be simplified for i: 0 thru 9 do B[i] : 3 * i ; The step can be omitted – the step value defaults to 1 if omitted. Don’t omit the step if any other increment is intended.
41
41 So far, all iterations just used loop control variables (usually indicies) We can do more – accumulate information Example: Find the sum of the integers from 1 to 100.
42
42 Approach (by hand) Add the second to the first, then the third to that sum Then the fourth to that sum, …
43
43 Approach on a calculator Clear the memory Add the first Add the second Add the third …
44
44 The Maxima approach follows the calculator model sum:0; for i: 1 thru 100 do sum : sum + i ; print(sum);
45
45 Comments show how the program works sum:0; /* initialize */ for i: 1 thru 100 do sum : sum + i ;/* accumulate */ print(sum);/* output */ 5051
46
46 Another example sum_of_squares:0; /* initialize */ for i: 1 thru 100 do sum_of_squares : sum_of_squares + i * i;/* accumulate */ print(sum_of_squares);/* output */ 338350
47
47 Probably better to use shorter name sum:0; /* initialize */ for i: 1 thru 100 do sum : sum + i *i ;/* accumulate */ print(sum);/* output */
48
48 Can find averages of arrays array(B, 20); for i: 0 thru 99 do B[i] : sin(i * %pi/4); /* init */ B[17]; 1 ------- sqrt(2) avg: 0; sum :0; for i :0 step 1 thru 99 do sum : sum + B[i]; print(sum, avg);
49
49 There are 3 forms of iteration A do-loop which follows the format we have seen so far A do-loop where the ending condition depends on some condition continues to hold. A do-loop where the loop continues to execute unless a condition is true.
50
50 There are 3 forms of iteration for variable: initial_value step increment thru limit do body (we have done this one many times already)
51
51 There are 3 forms of iteration for variable: initial_value step increment thru limit do body (we did this one already) for variable: initial_value step increment while condition do body for variable: initial_value step increment unless condition do body Let’s consider the next two forms
52
52 Example for variable: initial_value step increment while condition do body for i: 1 step 1 thru 10 do print(i) ; is eguivalent to for i: 1 step 1 while (i <= 10) do print(i) ;
53
53 Look at the example carefully for i: 1 step 1 while (i <= 10) do print(i) ; Reserved words for the loop are in red (print is a standard function in Maxima, also)
54
54 Look at the example carefully for i: 1 step 1 while (i <= 10) do print(i) ; Reserved words for the loop are in red (print is a standard function in Maxima, also) We are forced to list the start of the iterator variable and the loop termination condition. (We won’t see this in C.)
55
55 As before, we can omit the step for i: 1 while (i <= 10) do print(i) ; Recall that the default value of step is 1
56
56 The termination condition can be anything for i: 1 while ( (i < 1000) and (elapsed_run_time () <= 100)) do print(i) ; The code elapsed_run_time () <= 100 refers to an external event – do not use this unless you are prepared to have your Maxima program run for an extremely long time
57
57 The third type of do-loop in Maxima for variable: initial_value step increment unless condition do body This is not commonly used for k: 1 step 2 unless (k > 100) do print(k); Prints the odd numbers from 1 through 99
58
58 Files and Libraries
59
59 Files
60
60 How to save a Maxima session save( “out_file1”); Notice quotes save (filename, name_1, name_2, name_3,...) save (filename, values, functions, labels,...) save (filename, [m, n]) save (filename, name_1=expr_1,...) save (filename, all) save (filename, name_1=expr_1, name_2=expr_2,...)
61
61 How to resume calculations from saved sessions load(filename); The file name must be in quotes.
62
62 Can get input from files Many different functions You may need several
63
63 Category: File input Introduction to numericalioIntroduction to numericalio · batch · batchload · close · demo · file_search · file_search_demo · file_search_lisp · file_search_maxima · file_type · filename_merge · flength · fposition · load · loadfile · loadprint · openr · openr_binary · printfile · read_array · read_binary_array · read_binary_list · read_binary_matrix · read_hashed_array · read_list · read_matrix · read_nested_list · readline · setup_autoloadbatchbatchload closedemofile_searchfile_search_demo file_search_lispfile_search_maximafile_typefilename_mergeflengthfpositionload loadfileloadprintopenropenr_binary printfileread_arrayread_binary_array read_binary_listread_binary_matrix read_hashed_arrayread_listread_matrix read_nested_listreadlinesetup_autoload
64
64 Each function has a specific use read_array read_binary_array read_binary_list read_binary_matrix read_hashed_array read_list read_matrix readline,readline …
65
65 The syntax Always starts with the “input stream” – the name of a file. The file name is almost always in quotes. Path names are allowed Choose the read function that matches the data you want to use. Be sure the data format in the file matches exactly the format you want.
66
66 Data in files must be delimited The functions for plain-text input and output take an optional argument, separator_flag, that tells what character separates data. For plain-text input, these values of separator_flag are recognized: –comma for comma separated values –pipe for values separated by the vertical bar character –semicolon for values separated by semicolon ; –space for values separated by space or tab characters.
67
67 Data in files must be delimited If the file name ends in.csv and separator_flag is not specified, comma is assumed. If the file name ends in something other than.csv and separator_flag is not specified, space is assumed.
68
68 Data in files must be delimited In plain-text input, multiple successive space and tab characters count as a single separator. Multiple comma, pipe, or semicolon characters are significant. Successive comma, pipe, or semicolon characters (with or without intervening spaces or tabs) are considered to have false between the separators. 1234,,Foo is treated the same as 1234,false,Foo.
69
69 The most common delimiters Comma and tab Excel data files can be saved in these formats!
70
70 The difference between amateurs and professionals Amateurs assume the data is correctly formatted. Professionals program to handle poorly formed data.
71
71 The difference between amateurs and professionals Amateurs assume the data is correctly formatted. Professionals program to handle poorly formed data. It takes up to 9 times as much effort to do this extra programming as in the original. You are not professional programmers – just make sure the data is clean.
72
72 Is the data delimited consistently? 13512 7183615
73
73 Yes 13512 7183615 Separator was a tab. Hard to see the alignment.
74
74 Yes 1,3,5,12 7,18,36,15 Separator is changed to a comma.
75
75 Can write output to files
76
76 A good idea Take the Excel data from Program 1 and save it as a comma-delimited text file.
77
77 Category: File output Introduction to numericalioIntroduction to numericalio · appendfile · close · closefile · draw · draw2d · draw3d · draw_file · file_output_append · filename_merge · flength · fposition · freshline · multiplot_mode · newline · opena · opena_binary · openw · openw_binary · printf · save · stringout · tex · with_stdout · write_binary_data · write_data · writefileappendfile closeclosefiledrawdraw2ddraw3d draw_filefile_output_append filename_mergeflengthfposition freshlinemultiplot_modenewline openaopena_binaryopenw openw_binaryprintfsavestringout texwith_stdoutwrite_binary_data write_datawritefile
78
78 The syntax Always starts with the “output stream” – the name of a file. The file name is almost always in quotes. Choose the write or append function that matches the data you want to use. Be sure the data format in the file matches exactly the format you want.
79
79 Some names are tricky file_output_append openaopena · openw openw_binary printf The a means append – otherwise we might overwrite a file. The printf suggests a connection to C.
80
80 A good idea Do a previous Maxima exercise with arrays or lists and write the data to an output file.
81
81 Special output Graphics can be output to files. We will show this when we discuss plotting in Maxima.
82
82 Libraries
83
83 There are many types of libraries Some are provided with the Maxima distribution. –Read the manual for the libraries you need Some are user-provided. Libraries must be loaded before use Load only the ones you need – saves space and avoids name clashes –True for all types of libraries
84
84 Some standard Maxima libraries draw (for drawing) descript (for statistics) lapack for linear algebra
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.