0% found this document useful (0 votes)
98 views59 pages

Programacion Traducir 72-118

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views59 pages

Programacion Traducir 72-118

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

You can delete names and numbers by editing the NAMES

variable. To improve upon this program, create a delete name


routine.

Beeping to Get Attention


To enter BEEP in a program:
1. Enter a number that specifies the tone frequency in hertz.
2. Enter a number that specifies the tone duration in seconds.
3. Enter the BEEP command (!°L%OUT% L menu).
« … frequency duration BEEP … »

BEEP takes two arguments from the stack: the tone frequency from level 2 and the tone duration from level 1.
Example: The following edited version of TPROMPT sounds a 440-hertz, one-half-second tone at the prompt
for data input.
Program: Comments:
«
"ENTER a b IN ORDER:" Sounds a tone just
440 .5 BEEP before the prompt
PROMPT for data input.
TORSA
»

Stopping a Program for Keystroke Input


A program can stop for keystroke input — it can wait for the user to press a key. You can do this with the
WAIT and KEY commands.

Using WAIT for Keystroke Input


The WAIT command normally suspends execution for a specified number of seconds. However, you can
specify that it wait indefinitely until a key is pressed.

To enter WAIT in a program


■ To stop without changing the display, enter 0 and the WAIT command (PRG IN menu).
■ To stop and display the current menu, enter –1 and the WAIT command (PRG IN menu).
WAIT takes the 0 or –1 from level 1, then suspends execution until a valid keystroke is
executed.
For an argument of –1, WAIT displays the currently specified menu. This lets you build and display a menu of
user choices while the program is paused. (A menu built with MENU or TMENU is not normally displayed
until the program ends or is halted.)
When execution resumes, the three-digit key location number of the pressed key is left on the stack. This number
indicates the row, column, and shift level of the key.

To respond to WAIT while running a program:


■ Press any valid keystroke. (A prefix key such as !or ~ by itself is not a valid keystroke.)
Using KEY for Keystroke Input
You can use KEY inside an indefinite loop to “pause” execution until any key — or a certain key — is pressed.

To enter a KEY loop in a program


1. Enter the loop structure.
2. In the test-clause sequence, enter the KEY command (PRG IN menu) plus any necessary test commands.
3. In the loop-clause, enter no commands to give the appearance of a “paused” condition.
KEY returns 0 to level 1 when the loop begins. It continues to return 0 until a key is pressed — then it returns
1 to level 1 and the two-digit row-column number of the pressed key to level 2. For example, `returns 105, and
! returns 81.)
The test-clause should normally cause the loop to repeat until a key is pressed. If a key is pressed, you can use
comparison tests to check the value of the key number. (See “Using Indefinite Loop Structures” on page 1-22
and “Using Comparison Functions” on page 1-11.)

To respond to a KEY loop while running a program:


■ Press any key. (A prefix key such as !or ~is a valid key.)
Example: The following program segment returns 1 to level 1 if + is pressed, or 0 to level 1 if any
other key is pressed:
« … DO UNTIL KEY END 95 == … »

Output
You can determine how a program presents its output. You can make the output more recognizable using
the techniques described in this section.

Data Output Commands


Key Comma Descripti
nd on
!°L%OUT%:

%PVIEW PVIEW Displays PICT starting at the given coordinates.


%
%TEXT TEXT Displays the stack display.
%
%CLLC CLLCD Blanks the stack display.
D%
%DISP% DISP Displays an object in the specified line.

%FREEZ FREEZE “Freezes” a specified area of the display until a key


% press.
%MSGB MSGBO Creates a user-defined message box.
O% X
%BEEP BEEP Sounds a beep at a specified frequency (in hertz,
% level 2) and duration (in seconds, level 1).
Labeling Output with Tags
To label a result with a tag:
1. Put the output object on the stack.
2. Enter a tag — a string, a quoted name, or a number.
3. Enter the →TAG command (PRG TYPE menu).
« … object tag →TAG … »
→TAG takes two arguments — an object and a tag — from the stack and return a tagged object.

Example: The following program TTAG is identical to TINPUT, except that it returns the result as AREA: value.
Program: Comments:
«
"Key in a b"
{ ":a: :b:" {1 0} V
} INPUT OBJ→
TORSA
"AREA" Enters the tag (a
→TAG string).
Uses the program
result and string to
» create the tagged
object.
Stores the program in
`OTTAG ‰ TTAG.

Execute TTAG to calculate the area of a torus of inner radius a = 1.5 and outer radius b = 1.85. The
answer is returned as a tagged object.
J %TTAG% 1.5 ˜1.85 `

Labeling and Displaying Output as Strings


To label and display a result as a string:
1. Put the output object on the stack.
2. Enter the →STR command (PRG TYPE menu).
3. Enter a string to label the object (with "" delimiters).
4. Enter the SWAP + commands to swap and concatenate the strings.
5. Enter a number specifying the line to display the string on.
6. Enter the DISP command (PRG OUT menu).
« … object →STR label SWAP + line DISP … »
DISP displays a string without its "" delimiters.

RPL Programming 1-50


Example: The following program TSTRING is identical to TINPUT, except that it converts the program result
to a string and appends a labeling string to it.

Program: Comments:
«
"Key in a b" Converts the result to a string.
{ ":a: :b:" {1 0} Enters the labeling strings.
V} INPUT OBJ→
TORSA
→STR
"Area = "
SWAP + Swaps and adds the two strings.
CLLCD 1 DISP Displays the resultant string,
3 FREEZE without its delimiters, in line
1 of
the display.
»
Stores the program in TSTRING.
`OTSTRING ‰

Execute TSTRING to calculate the area of the torus with a = 1.5 and b = 1.85. The labeled answer appears in
the status area.
@ J%TSTRI%
1.5 ˜1.85 `

Pausing to Display Output


To pause to display a result:
1. Enter commands to set up the display.
2. Enter the number of seconds you want to pause.
3. Enter the WAIT command (PRG IN menu).
WAIT suspends execution for the number of seconds in level 1. You can use WAIT with DISP to display
messages during program execution — for example, to display intermediate program results. (WAIT interprets
arguments 0 and –1 differently — see “Using WAIT for Keystroke Input” on page 1-48.)

Using MSGBOX to Display Output


To set up a message box:
1. Enter a message string.
2. Execute the MSGBOX command.
Example: Enter the string "HELLO WORLD" `.
Execute MSGBOX (!°L %OUT% %MSGBO%).
The following message appears:
You must acknowledge a message box by pressing %OK% or −.

Using Menus with Programs


You can use menus with programs for different purposes:
■ Menu-based input. A program can set up a menu to get input during a halt in a program and then
resume executing the same program.
■ Menu-based application. A program can set up a menu and finish executing, leaving the menu to
start executing other related programs.

To set up a built-in or library menu:


1. Enter the menu number.
2. Enter the MENU command (MODES MENU menu).

To set up a custom menu:


1. Enter a list (with { } delimiters) or the name of a list defining the menu actions. If a list of two element lists
is given, the first element appears in the menu, but it is the second element that is returned to the stack when
the menu key is pressed. This second element can itself be a list with up to 3 objects, one for the menu key,
one for the left shift menu key and one for the right shift menu key.
2. Activate the menu:
■ To save the menu as the CST menu, enter the MENU command (MODES MENU menu).
■ To make the menu temporary, enter the TMENU command (MODES MENU
menu). The menu isn’t displayed until program execution halts.
Menu numbers for built-in menus are listed in Appendix H. Library menus also have numbers — the library
number serves as the menu number. So you can activate applications menus (such as the SOLVE and PLOT
menus) and other menus (such as the VAR and CST menus) in programs. The menus behave just as they do
during normal keyboard operations.
You create a custom menu to cause the behavior you need in your program — see the topics that follow. You
can save the menu as the CST menu, so the user can get it again by pressing !£. Or you can make it
temporary — it remains active (even after execution stops), but only until a new menu is selected — and it doesn’t
affect the contents of variable CST.
To specify a particular page of a menu, enter the number as m.pp, where m is the menu number and pp is the
page number (such as 94.02 for page 2 of the TIME menu). If page pp doesn’t exist, page 1 is displayed (94
gives page 1 of the TIME menu).
Example: Enter 69 MENU to get page 1 of the MODES MISC menu.
Enter 69.02 MENU to get page 2 of the MODES MISC menu.

To restore the previous menu:


■ Execute 0 MENU.

To recall the menu number for the current menu:


■ Execute the RCLMENU command (MODES MENU menu).

Using Menus for Input


To display a menu for input in a program:
1. Set up the menu — see the previous section.
2. Enter a command sequence that halts execution (such as DISP, PROMPT, or HALT).
The program remains halted until it’s resumed by a CONT command, such as by pressing !æ. If you create
a custom menu for input, you can include a CONT command to automatically resume the program when you
press the menu key.
Example: The following program activates page 1 of the MODES ANGL menu and prompts you to set the angle
mode. After you press the menu key, you have to press !æto resume execution.
« 65 MENU "Select Angle Mode" PROMPT »
Example: The PIE program on page 2-34 assigns the CONT command to one key in a temporary menu.
Example: The MNX program on page 2-16 sets up a temporary menu that includes a program containing
CONT to resume execution automatically.

Using Menus to Run Programs


You can use a custom menu to run other programs. That menu can serve as the main interface for an application (a
collection of programs).

To create a menu-based application:


1. Create a custom menu list for the application that specifies programs as menu objects.
2. Optional: Create a main program that sets up the application menu — either as the CST menu or as a
temporary menu.
Example: The following program, WGT, calculates the mass of an object in either English or SI units given
the weight. WGT displays a temporary custom menu, from which you run the appropriate program. Each
program prompts you to enter the weight in the desired unit system, then calculates the mass. The menu
remains active until you select a new menu, so you can do as many calculations as you want. Enter the
following list and store it in LST:
{
{ "ENGL" « "ENTER Wt in POUNDS" PROMPT 32.2 / » }
{ "SI" « "ENTER Wt in NEWTONS" PROMPT 9.81 / » }
}
OLST ‰

Program: Comments:
« LST TMENU » Displays the custom
menu stored in LST.
Stores the program in
`OWGT ‰
WGT.
Use WGT to calculate the mass of an object of weight 1.25 N. The program sets up the menu, then completes
execution.
J%WGT%
Select the SI unit system, which starts the program in the menu list.
%SI%

Key in the weight, then resume the program.


1.25!æ

Example: The following program, EIZ, constructs a custom menu to emulate the HP Solve application for a
capacitive electrical circuit. The program uses the equation E = IZ, where E is the voltage, I is the current, and
Z is the impedance.
Because the voltage, current, and impedance are complex numbers, you can’t use the HP Solve application to
find solutions. The custom menu in EIZ assigns a direct solution to the left-shifted menu key for each variable,
and assigns store and recall functions to the unshifted and right-shifted keys — the actions are analogous to the
HP Solve application. The custom menu is automatically stored in CST, replacing the previous custom menu —
you can press
!£ to restore the menu.

Program: Comments:
«
DEG -15 SF -16 SF Sets Degrees mode. Sets flags –15 and –
2 FIX 16 to display complex numbers in polar
form. Sets the display mode to 2 Fix.
{ Starts the custom menu
{ "E" { « 'E' STO » list. Builds menu key 1
« I Z * DUP 'E' for E.
STO "E: " SWAP +
CLLCD Unshifted action: stores the object in E.
1 DISP 3 FREEZE » Left- shift action: calculates I × Z, stores it
«E»} } in E, and displays it with a label. Right-shift
action: recalls the object in E.
{ "I" { « 'I' STO »
« E Z / DUP 'I' STO Builds menu key 2.
"I:"SWAP + CLLCD
1 DISP 3 FREEZE »
«I »} }
{ "Z"{ « 'Z' STO »
« E I / DUP 'Z' Builds menu key 3.
STO "Z:" SWAP +
CLLCD
1 DISP 3 FREEZE »
«Z»} }
} Ends the list.
ME Displays the custom menu.
NU
»
Stores the program in EIZ.
`OEIZ ‰

For a 10-volt power supply at phase angle 0°, you measure a current of 0.37-amp at phase angle 68°.
Find the impedance of the circuit using EIZ.
@ J%EIZ%
Key in the voltage value.
!Ü10 ~@6 0
Store the voltage value. Then key in and store the current value. Solve for the impedance.

%%E%% !Ü .37 ~@6 68 %%I%%


!%%Z%%

Recall the current and double it. Then find the voltage.
@%%I%% 2 *%%I%% !%%E%%

Press (!&H)%FMT% %STD% and L %MODES %ANGLE %RECT% to restore Standard and Rectangular modes.

Turning Off the Calculator from a Program


To turn off the calculator in a program:
■ Execute the OFF command (PRG RUN menu).
The OFF command turns off the calculator. If a program executes OFF, the program resumes when the
calculator is next turned on.
2
RPL Programming Examples
The programs in this chapter demonstrate basic programming concepts. These programs are intended to
improve your programming skills, and to provide supplementary functions for your calculator.
At the end of each program, the program’s checksum and size in bytes are listed to help make sure you typed
the program in correctly. (The checksum is a binary integer that uniquely identifies the program based on its
contents). To make sure you’ve keyed the program in correctly, store it in its name, put the name in level 1,
then execute the BYTES command (!°#MEM# %BYTES%). This returns the program’s checksum to level 2,
and its size in bytes to level 1. (If you execute BYTES with the program object in level 1, you’ll get a different
byte count.)
The examples in this chapter assume the calculator is in its initial, default condition — they assume you haven’t
changed any of the calculator’s operating modes, with the exception of selecting RPN mode. (To reset the
calculator to this condition, see “Memory Reset” in chapter 5 of the HP 48G Series User's Guide.)
Each program listing in this chapter gives the following information:
■ A brief description of the program.
■ A syntax diagram (where needed) showing the program’s required inputs and resulting outputs.
■ Discussion of special programming techniques in the program.
■ Any other programs needed.
■ The program listing.
■ The program’s checksum and byte size.

Fibonacci Numbers
This section includes three programs that calculate Fibonacci numbers:
■ FIB1 is a user-defined function that is defined recursively (that is, its defining procedure contains its own
name).
FIB1 is short.
■ FIB2 is a user-defined function with a definite loop. It’s longer and more complicated than FIB1, but faster.
■ FIBT calls both FIB1 and FIB2 and calculates the execution time of each subprogram.
FIB1 and FIB2 demonstrate an approach to calculating the nth Fibonacci number Fn, where:
F0 = 0, F1 = 1, Fn = Fn-1 + Fn-2
FIB1 (Fibonacci Numbers, Recursive Version)

Level → Level
1 1
n → Fn

RPL Programming Examples 2-1


Techniques used in FIB1
■ IFTE (if -then-else function). The defining procedure for FIB1 contains the conditional function IFTE,
which can take its argument either from the stack or in algebraic syntax.
■ Recursion. The defining procedure for FIB1 is written in terms of FIB1, just as Fn is defined in terms of
Fn-1 and Fn-2.

FIB1 program listing

Program: Comments:
«
→ n 'IFTE(n Defines local variable n.
‰1 The defining procedure,
n an algebraic expression. If
FIB1(n-1)+FIB1(n- n ≤ 1, Fn = n, else Fn =
2))' Fn-1+Fn-2.
»
Stores the program in FIB1.
`OFIB1 K

Checksum: # 14909d (press O%FIB1% !°#MEM# %BYTES%)


Bytes: 113.5
Example: Calculate F6. Calculate F10 using algebraic
syntax. First calculate F6.
J
6 %FIB1%

Next, calculate F10 using algebraic syntax.


O%FIB1% !Ü10 N

FIB2 (Fibonacci Numbers, Loop Version

Level → Level
1 1
n → Fn

Techniques used in FIB2


■ IF…THEN…ELSE…END. FIB2 uses the program-structure form of the conditional. (FIB1 uses IFTE.)
■ START…NEXT (definite loop). To calculate Fn, FIB2 starts with F0 and F1 and repeats a loop to
calculate successive values of Fi.
FIB2 program listing

Program: Comments:
«
→n Creates a local variable structure.
«
IF n 1 ‰ If n ≤ 1,
THEN n then Fn = n;
ELSE otherwise …
0 1 Puts F0 and F1 on the stack.
2n From 2 to n does the following loop:
START
DUP Copies the latest F (initially F1)
ROT Gets the previous F (initially F0)
+ Calculates the next F (initially F2)
NEXT Repeats the loop.
SWAP DROP Drops Fn-1.
END Ends the ELSE clause.
» Ends the defining procedure.
»
Stores the program in FIB2.
`O FIB2 K

Checksum: # 23902d (press O%FIB2% !°#MEM# %BYTES%)


Bytes: 89

Example: Calculate F6 and

F10. Calculate F6.


J
6 %FIB2%

Calculate F10.
10 %FIB2%
FIBT (Comparing Program-Execution Time)
FIB1 calculates intermediate values Fi more than once, while FIB2 calculates each intermediate Fi only once.
Consequently, FIB2 is faster. The difference in speed increases with the size of n because the time required for
FIB1 grows exponentially with n, while the time required for FIB2 grows only linearly with n.
FIBT executes the TICKS command to record the execution time of FIB1 and FIB2 for a given value of n.

Level 1 → Level 3 Level 2 Level 1


n → Fn FI TIM z FI TIM z
B E: B E:
1 2

Techniques used in FIBT


■ Structured programming. FIBT calls both FIB1 and FIB2.
■ Programmatic use of calculator clock. FIBT executes the TICKS command to record the start and
finish of each subprogram.
■ Labeling output. FIBT tags each execution time with a descriptive message.

Required Programs
■ FIB1 (page 2-1) calculates Fn using recursion.
■ FIB2 (page 2-2) calculates Fn using looping.

FIBT program listing

Program: Comments:
«
DUP TICKS SWAP Copies n, then executes FIB1,
FIB1 SWAP TICKS SWAP recording the start and stop time.
- B→R 8192 / Calculates the elapsed time, converts it
to a real number, and converts that
number to seconds.
Leaves the answer returned by FIB1 in level
2.
"FIB1 TIME" →TAG Tags the execution time.
ROT TICKS SWAP Executes FIB2, recording the start and
FIB2 TICKS stop time.
SWAP DROP SWAP Drops the answer returned by FIB2 (FIB1
- B→R 8192 / returned the same answer). Calculates the
elapsed time for FIB2 and converts to
seconds.
"FIB2 TIME" →TAG Tags the execution time.
»
Stores the program in FIBT.
`OFIBT K

Checksum: #
23164d Bytes:129
Example: Calculate F13 and compare the execution time for the two
methods. Select the VAR menu and do the calculation.
J
13 %FIBT%

F13 is 233. FIB2 takes fewer seconds to execute than FIB1 (far fewer if n is large). (The times required for the
calculations depend on the contents of memory and other factors, so you may not get the exact times shown
above.)

Displaying a Binary Integer


This section contains three programs:
■ PAD is a utility program that converts an object to a string for right-justified display.
■ PRESERVE is a utility program for use in programs that change the calculator’s status (angle mode, binary
base, and so on).
■ BDISP displays a binary integer in HEX, DEC, OCT, and BIN bases. It calls PAD to show the
displayed numbers right-justified, and it calls PRESERVE to preserve the binary base.

PAD (Pad with Leading Spaces)


PAD converts an object to a string, and if the string contains fewer than 22 characters, adds spaces to the
beginning of the string till the string reaches 22 characters.
When a short string is displayed with DISP, it appears left-justified: its first character appears at the left end of
the display. By adding spaces to the beginning of a short string, PAD moves the string to the right. When the
string (including leading spaces) reaches 22 characters, it appears right-justified: its last character appears at the right
end of the display. PAD has no effect on longer strings.

Level → Level 1
1
object → "object"

Techniques used in PAD


■ WHILE…REPEAT…END (indefinite loop). The WHILE clause contains a test that executes the
REPEAT clause and tests again (if true) or skips the REPEAT clause and exits (if false).
■ String operations. PAD demonstrates how to convert an object to string form, count the number of
characters, and combine two strings.
PAD program listing

Program: Comments:
«
→STR Makes sure the object is in string form.
(Strings
are unaffected by this command.)
WHILE Repeats if the string contains fewer
DUP SIZE 22 < than 22 characters.
REPEAT Loop-clause adds a leading space.
" " SWAP +
END End loop.
»
Stores the program in PAD.
`OPAD K

Checksum: #
6577d Bytes:57.5

PAD is demonstrated in the program BDISP.

PRESERVE (Save and Restore Previous Status)


PRESERVE stores the current calculator (flag) status, executes a program from the stack, and restores the previous
status.

Level 1 → Level 1
«program» → res o program
ult f
'program' → o
program
res
ult f

Techniques used in PRESERVE


■ Preserving calculator flag status. PRESERVE uses RCLF (recall flags) to record the current status of
the calculator in a binary integer, and STOF (store flags) to restore the status from that binary integer.
■ Local-variable structure. PRESERVE creates a local variable structure to briefly remove the binary
integer from the stack. Its defining procedure simply evaluates the program argument, then puts the binary
integer back on the stack and executes STOF.
■ Error trapping. PRESERVE uses IFERR to trap faulty program execution on the stack and to restore
flags. DOERR shows the error if one occurs.
PRESERVE program listing

Program: Comments:
«
RCLF Recalls the list of four 64-bit
binary integers representing the
status of the 128 system flags
and
128 user flags.
→f Stores the list in local variable f.
« Begins the defining procedure.
IFERR Starts the error trap.
EVAL Executes the program placed on
the stack as the level 1
argument.
THEN If the program caused an error,
f STOF ERRN DOERR restores flags, shows the error,
and
aborts execution.
END Ends the error routine.
f STOF Puts the list back on the stack,
then restores the status of all
flags.
» Ends the defining procedure.
»
Stores the program in
`OPRESERVE K PRESERVE.

Checksum: #
26834d Bytes:
71

PRESERVE is demonstrated in the program BDISP.

BDISP (Binary Display)


BDISP displays a real or binary number in HEX, DEC, OCT, and BIN bases.

Level 1 → Level 1
#n → #n

n → n
Techniques used in BDISP
■ IFERR…THEN…END (error trap). To accommodate real-number arguments, BDISP includes the
command R→B (real-to-binary). However, this command causes an error if the argument is already a binary
integer. To maintain execution if an error occurs, the R→B command is placed inside an IFERR clause. No
action is required when an error occurs (since a binary number is an acceptable argument), so the THEN
clause contains no commands.
■ Enabling LASTARG. In case an error occurs, the LASTARG recovery feature must be enabled to return
the argument (the binary number) to the stack. BDISP clears flag –55 to enable this.
■ FOR…NEXT loop (definite loop with counter). BDISP executes a loop from 1 to 4, each time
displaying n (the number) in a different base on a different line. The loop counter (named j in this program) is
a local variable created by the FOR…NEXT program structure (rather than by a → command), and
automatically incremented by NEXT.
■ Unnamed programs as arguments. A program defined only by its « and » delimiters (not stored in a
variable) is not automatically evaluated, but is placed on the stack and can be used as an argument for a
subroutine. BDISP demonstrates two uses for unnamed program arguments:
O BDISP contains a main program argument and a call to PRESERVE. This program argument goes on the
stack and is executed by PRESERVE.
O BDISP also contains four program arguments that “customize” the action of the loop. Each of these contains a
command to change the binary base, and each iteration of the loop evaluates one of these arguments.
When BDISP creates a local variable for n, the defining procedure is an unnamed program. However, since
this program is a defining procedure for a local variable structure, it is automatically executed.

Required Programs
PAD
■ PAD (Pad with Leading Spaces) expands a string to 22 characters so that DISP shows it right-justified.
PRESERVE
■ PRESERVE stores the current status, executes the main nested program, and restores the status.
BDISP program listing

Program: Comments:
«
« Begins the main nested program.
DUP Makes a copy of n.
-55 CF Clears flag –55 to enable LASTARG.
IFERR Begins error trap.
R→B Converts n to a binary integer.
TH If an error occurs, do nothing (no commands
EN in the THEN clause).
EN
D
→n Creates a local variable n and begins the
« defining program.
CLLCD Clears the display.
« BIN » Nested program for BIN.
« OCT » Nested program for OCT.
« DEC » Nested program for DEC.
« HEX » Nested program for HEX.
1 4 Sets the counter limits.
FOR j Starts the loop with counter j.
EVAL Executes one of the nested base programs
(initially for HEX).
n →STR Makes a string showing n in the current base.

PAD Pads the string to 22 characters.


j DISP Displays the string in the jth line.
NEXT Increments j and repeats the loop.
» Ends the defining program.
3 FREEZE Freezes the status and stack areas.
» Ends the main nested program.
PRESERVE Stores the current flag status, executes the
main
nested program, and restores the status.
»

`OBDISP K Stores the program in BDISP.

Checksum: #
22884d Bytes:187
Example: Switch to DEC base, display #100 in all bases, and check that BDISP restored the base to DEC.
Clear the stack and select the MTH BASE menu. Make sure the current base is DEC and enter #100.

‚ã%DEC%
!â100 `

Execute BDISP.
J %BDISP%

Return to the normal stack display and check the current base.

‚ã

Although the main nested program left the calculator in BIN base,
PRESERVE restored DEC base. To check that BDISP also works for
real numbers, try 144.
J
144 %BDISP%
Press − to return to the stack display.

Median of Statistics Data


This section contains two programs:
■ %TILE returns the value of a specified percentile of a list.
■ MEDIAN uses %TILE to calculate the median of the current statistics data.

%TILE (Percentile of a list)


%TILE sorts a list, then returns the value of a specified percentile of the list. For example, typing {list} 50 and
pressing %©TILE% returns the median (50th percentile) of the list.

Level 2 Level 1 → Level 1


{ l } n → n percent o sort list
i t ile f ed
h
s
t

RPL Programming Examples 2-10


Techniques used in %TILE
■ FLOOR and CEIL. For an integer, FLOOR and CEIL both return that integer; for a noninteger,
FLOOR and CEIL return successive integers that bracket the noninteger.
■ SORT. The SORT command sorts the list elements into ascending order.

%TILE program listing

Program: Comments:
«
SWAP SORT Brings the list to level 1 and sorts it.
DUP SIZE Copies the list, then finds its size.
1 + ROT % Calculates the position of the specified
percentile.
DUP2 Makes a copy of the list and the percentile.
FLOOR Rounds the position to the lower integer.
1 MAX OVER SIZE MIN Ensures it is between 1 and the size of the list.
GET Gets the corresponding number.
ROT ROT Moves the list to level 1.
CEIL Rounds the position to the upper integer.
1 MAX OVER SIZE MIN Ensures it is between 1 and the size of the list.
GET Gets the corresponding number.
+2 / Calculates the average of the two numbers.
»
Stores the program in %TILE.
`O%TILE K
Checksum: #
3805d Bytes:92.5

Example: Calculate the median of the list {8 3 1 5 2}.


!ä8 3 1 5 2`
J50 %©TILE%

MEDIAN (Median of Statistics Data)


MEDIAN returns a vector containing the medians of the columns of the statistics data. Note that for a sorted
list with an odd number of elements, the median is the value of the center element; for a list with an even
number of elements, the median is the average value of the elements just above and below the center.

Level 1 → Level 1

→ [ x1 x2 … xm ]
Techniques used in MEDIAN
■ Arrays, lists, and stack elements. MEDIAN extracts a column of data from ΣDAT in vector form. To
convert the vector to a list, MEDIAN puts the vector elements on the stack and combines them into a list.
From this list the median is calculated using %TILE.
The median for the mth column is calculated first, and the median for the first column is calculated last. As
each median is calculated, ROLLD is used to move it to the top of the stack.
After all medians are calculated and positioned on the stack, they’re combined into a vector.
■ FOR…NEXT (definite loop with counter). MEDIAN uses a loop to calculate the median of each
column. Because the medians are calculated in reverse order (last column first), the counter is used to reverse
the order of the medians.

Required Program
■ %TILE (page 2-10) sorts a list and returns the value of a specified percentile.

MEDIAN program listing (Note: Use approximate mode for this program and example).

Program: Comments:
«
RCLΣ Puts a copy of the current statistics matrix ΣDAT
on the stack.
DUP SIZE Puts the list { n m } on the stack, where n is the
number of rows in ΣDAT and m is the number of
columns.
OBJ→ DROP Puts n and m on the stack, and drops the list size.
→snm Creates local variables for s, n, and m.
« Begins the defining
'ΣDAT' TRN procedure. Recalls and
transposes ΣDAT.
Now n is the number of columns in ΣDAT and m
is the number of rows. (To key in the Σ character,
press @½, then delete the parentheses.)
1 m Specifies the first and last rows.
FOR For each row, does the following: Extracts the last
j row in ΣDAT.
Σ- Initially this is the mth row, which corresponds to
the
mth column in the original ΣDAT.
(To key in the Σ– command, use @µ.)
OBJ→ DROP Puts the row elements on the stack. Drops the
index list { n }.
n →LIST Makes an n-element list.
50 %TILE Sorts the list and calculates its median.
j ROLLD Moves the median to the proper stack level.
NEXT Increments j and repeats the loop.
Program: Comments:
m Combines all the medians into an m-element
→ARRY vector. Restores ΣDAT to its previous value.
s STOΣ Ends the defining procedure.
»
»
Stores the program in MEDIAN.
`OMEDIAN K

Checksum: #
256d Bytes:140
Example: Calculate the median of the following data.
18 12
4 7
3 2
11 1
31 48
20 17

There are two columns of data, so MEDIAN will return a two-element


vector. Enter the matrix.
‚Ù%OK% %EDIT%
18 `12 `˜šš
4 `7 `
3 `2 `
11 `1 `
31 `48 `

20 `17 `
` %OK%
The matrix is now stored in ΣDAT.
Calculate the median.
J %MEDIA%

Clear approximate mode (set exact mode) before going on to the next example.

Expanding and Collecting Completely


This section contains two programs:
■ MULTI repeats a program until the program has no effect on its argument.
■ EXCO calls MULTI to completely expand and collect an algebraic.
MULTI (Multiple Execution)
Given an object and a program that acts on the object, MULTI applies the program to the object repeatedly
until the program no longer changes the object.

Level Level → Level 1


2 1
object «progra → objectresult

Techniques used in MULTI


■ DO…UNTIL…END (indefinite loop). The DO clause contains the steps to be repeated. The UNTIL
clause contains the test that repeats both clauses again (if false) or exits (if true).
■ Programs as arguments. Although programs are commonly named and then executed by calling their
names, programs can also be put on the stack and used as arguments to other programs.
■ Evaluation of local variables. The program argument to be executed repeatedly is stored in a local variable.
It’s convenient to store an object in a local variable when you don’t know beforehand how many copies
you’ll need. An object stored in a local variable is simply put on the stack when the local variable is
evaluated. MULTI uses the local variable name to put the program argument on the stack and then executes
EVAL to execute the program.
MULTI program listing
Program: Comments:
«
→p Creates a local variable p that contains
the
program from level 1.
« Begins the defining procedure.
DO Begins the DO loop clause.
DUP Makes a copy of the object, now in level
1.
p EVAL Applies the program to the object,
returning its new version.
DUP Makes a copy of the new object.
ROT Moves the old version to level 1.
UNTIL Begins the DO test clause.
SAME Tests whether the old version and the
new
version are the same.
END Ends the DO structure.
» Ends the defining procedure.
»
Stores the program in MULTI.
`OMULTI K
Checksum: #
22693d Bytes:
56
MULTI is demonstrated in the next programming example.
EXCO (Expand and Collect Completely)
EXCO repeatedly executes EXPAN on an algebraic until the algebraic doesn’t change, then repeatedly
executes COLCT until the algebraic doesn’t change. In some cases the result will be a number.
Expressions with many products of sums or with powers can take many iterations of EXPAN to
expand completely, resulting in a long execution time for EXCO.

Level 1 → Level 1
'algebraic' → 'algebr
aic'
'algebraic' →
z

Techniques used in EXCO


■ Subroutines. EXCO calls the program MULTI twice. It is more efficient to create program MULTI and
simply call its name twice than write each step in MULTI two times.

Required Programs
■ MULTI (Multiple Execution) repeatedly executes the programs that EXCO provides as arguments.

EXCO program listing

Program: Comments:
«
« EXPAN » Puts a program on the stack as
the level 1 argument for
MULTI. The program
executes the EXPAN
command.
MULTI Executes EXPAN until the
algebraic object doesn’t
change.
« COLCT » Puts another program on the
stack for MULTI. The
program executes the COLCT
command.
MULTI Executes COLCT until the
algebraic object doesn’t
change.
»
Stores the program in EXCO.
`OEXCO K
Checksum: #
41162d Bytes:
65.5
Example: Expand and collect completely the expression:
2
3x4y +z +8x –5z
Enter the expression.
O3 * X *
!Ü4 *Y+Z ™+

! Ü 8 *X -5 *Z

™Q2
`
Select the VAR menu and start the program.
J %EXCO%

Minimum and Maximum Array Elements


This section contains two programs that find the minimum or maximum element of an array:
■ MNX uses a DO…UNTIL…END (indefinite) loop.
■ MNX2 uses a FOR…NEXT (definite) loop.

MNX (Minimum or Maximum Element—Version 1)


MNX finds the minimum or maximum element of an array on the stack.

Level 1 → Level2 Level 1


[[ arr ]] → [[ arr ]] Z o Zmax
ay ay m r
in

Techniques used in MNX


■ DO…UNTIL…END (indefinite loop). The DO clause contains the sort instructions. The UNTIL
clause contains the system-flag test that determines whether to repeat the sort instructions.
■ User and system flags for logic control:
O User flag 10 defines the sort: When flag 10 is set, MNX finds the maximum element; when flag 10 is
clear, it finds the minimum element. You determine the state of flag 10 at the beginning of the program.
O System flag –64, the Index Wrap Indicator flag, determines when to end the sort. While flag –64 is clear,
the sort loop continues. When the index invoked by GETI wraps back to the first array element, flag –64 is
automatically set, and the sort loop ends.
■ Nested conditional. An IF…THEN…END conditional is nested in the DO…UNTIL…END conditional,
and determines the following:
O Whether to maintain the current minimum or maximum element, or make the current element the
new minimum or maximum.
O The sense of the comparison of elements (either < or >) based on the status of flag 10.

■ Custom menu. MNX builds a custom menu that lets you choose whether to sort for the minimum or
maximum element. Key 1, labeled %MAX%, sets flag 10. Key 2, labeled %MIN%, clears flag 10.
■ Logical function. MNX executes XOR (exclusive OR) to test the combined state of the relative value of the
two elements and the status of flag 10.
MNX program listing

Program: Comments:
«
{{ "MA Defines the option menu. %MAX%
X" sets flag 10 and continues
« 10 SF CONT » } execution.
{ "MIN" %MIN% clears flag 10 and
« 10 CF CONT » }} continues execution.
TMENU Displays the temporary menu
"Sort for MAX or MIN?" and a prompt message.
PROMPT
1 GETI Gets the first element of the array.
DO Begins the DO loop.
ROT ROT GETI Puts the index and the array in
levels 1 and 2, then gets the new
array element.
4 ROLL DUP2 Moves the current minimum or
maximum array element from
level 4 below 1, then copies both.
IF Tests the combined state of the
> 10 FS? XOR relative value of the two elements
and the status of flag 10.
THE If the new element is either less
N than the current maximum or
SW greater than the current
AP minimum, swaps the new
END element into level 1.
DROP Drops the other element off the
stack.
UNTIL Begins the DO test-clause.
-64 FS? Tests if flag –64 is set — if the
index reached the end of the
array.
END Ends the DO loop.
SWAP DROP 0 MENU Swaps the index to level 1 and
drops it. Restores the last menu.
»
Stores the program in MNX.
`OMNX K
Checksum: #
20991d Bytes:194.5

Example: Find the maximum element of the following matrix:


12 56
45 1
9 14
Enter the matrix.

12 `56 `˜šš
45 `1 `
9 `14 `
`
Select the VAR menu and execute MNX.
J %MNX%

Find the maximum element.


%MAX%

MNX2 (Minimum or Maximum Element—Version 2)


Given an array on the stack, MNX2 finds the minimum or maximum element in the array. MNX2 uses a
different approach than MNX: it executes OBJ→ to break the array into individual elements on the stack for
testing, rather than executing GETI to index through the array.

Level 1 → Level2 Level 1


[[ arr ]] → [[ arr ]] Z o Zmin
ay ay m r
ax

Techniques used in MNX2


■ FOR…NEXT (definite loop). The initial counter value is 1. The final counter value is nm –1, where nm
is the number of elements in the array. The loop-clause contains the sort instructions.
■ User flag for logic control. User flag 10 defines the sort: When flag 10 is set, MNX2 finds the
maximum element; when flag 10 is clear, it finds the minimum element. You determine the status of flag 10
at the beginning of the program.
■ Nested conditional. An IF…THEN…END conditional is nested in the FOR…NEXT loop, and
determines the following:
O Whether to maintain the current minimum or maximum element, or make the current element the
new minimum or maximum.
O The sense of the comparison of elements (either < or >) based on the status of flag 10.

■ Logical function. MNX2 executes XOR (exclusive OR) to test the combined state of the relative value of the
two elements and the status of flag 10.
■ Custom menu. MNX2 builds a custom menu that lets you choose whether to sort for the
minimum or maximum element. Key 1, labeled %MAX%, sets flag 10. Key 2, labeled %MIN%, clears flag 10.
MNX2 program listing

Program: Comments:
«
{{ "MA Defines the temporary option menu.
X" %MAX% sets flag 10 and continues
« 10 SF CONT » } execution. %MIN% clears flag 10 and
{ "MIN"
« 10 CF CONT » }} continues execution.
TMENU Displays the temporary menu
"Sort for MAX or MIN?" and a prompting message.
PROMPT
DUP OBJ→ Copies the array. Returns the individual
array
elements to levels 2 through nm+1, and
returns the list containing n and m to level
1.
1 Sets the initial counter value.
SWAP OBJ→ Converts the list to individual elements on
the stack.
DROP * 1 - Drops the list size, then calculates the final
counter value (nm - 1).
FOR n Starts the FOR…NEXT loop.
DUP2 Saves the array elements to be tested
(initially
the last two elements). Uses the last array
element as the current minimum or
maximum.
IF Tests the combined state of the relative
> 10 FS? XOR value of the two elements and the status
of flag 10.
THE If the new element is either less than the
N current maximum or greater than the
SW current minimum, swaps the new element
AP into level
END
1.
DROP Drops the other element off the stack.
NEXT Ends the FOR…NEXT loop.
0 MENU Restores the last menu.

»
Stores the program in MNX2.
`OMNX2 K
Checksum: #
6992d Bytes:188.5

Example: Use MNX2 to find the minimum element of the matrix from the previous example:
12 56
45 1
9 14

Enter the matrix (or retrieve it from the previous example).


12 `56 `˜šš
45 `1 `
9 `14 `
`
Select the VAR menu and execute MNX2.
J %MNX2%

Find the minimum element.


%MIN%

Applying a Program to an Array


APLY makes use of list processing to transform each element of an array according to a desired procedure.
The procedure applied to each element must be a program that takes exactly one argument (i.e. the element)
and returns exactly one result (i.e. the transformed element).
The procedure assumes flag –55 to be clear, and unexpected results could be returned if flag –55 is set.

Level 2 Level 1 → Level 1


[ arr ] « progr » → [[ ar ] o { ar }}
ay am ra r { ra
y y

Techniques used in APLY


■ Manipulating Meta-Objects. Meta-objects are composite objects like arrays and lists that have been
disassembled on the stack. APLY illustrates several approaches to manipulating the elements and dimensions
of such objects.
■ Application of List Processing. APLY makes use of DOSUBS (although DOLIST might also have
been used) to perform the actual transformation of array elements.
■ Using an IFERR…THEN…ELSE…END Structure. The entire symbolic pseudo-array case is
handled within a error structure — triggered when the →ARRY command generates an error when symbolic
elements are present.
■ Using Flags. User flag 1 is used to track the case when the input array is a vector.

APLY program listing

Program: Comments:
«
→a p Store the array and program in local
« variables. Begin the main local variable
RPL Programming Examples 2-20
structure.

RPL Programming Examples 2-21


Program: Comments:
1 CF Make sure the flag 1 is clear to
begin the procedure.
a DUP SIZE Retrieve the dimensions of the array.
DUP Determine if the array is a vector.
SIZE IF
1 ==
THEN 1 SF 1 + If array is a vector, set flag 1 and add a
second dimension by treating the vector
as an n × 1 matrix.
SWAP OBJ→ OBJ→ DROP Disassemble the original vector,
leaving the element count, n, in level
1.
1 + ROLL Roll the elements up the stack and
bring the “matrix” dimensions of the
vector to level 1.
ELSE DROP2 a OBJ→ If array is a matrix, clean up the stack and
decompose the matrix into its elements,
leaving its dimension list on level 1.
END DUP OBJ→ DROP * Duplicate the dimension list and
compute the total number of elements.
SWAP OVER 2 + Roll up the element count and combine
ROLLD →LIST all elements into a list. Note that the
elements in the list are in row-major
order.
1 p DOSUBS Recalls the program and uses it as an
argument for DOSUBS (DOLIST works
in this case as well). Result is a list of
transformed elements.
OBJ→ 1 + ROLL Disassembles the result list and brings the
array dimensions to level 1.
IFERR Begins the error-trapping structure. Its
purpose is to find and handle the cases
when the result list contains symbolic
elements.
IF 1 FS? Was original array a vector? If the original
THEN OBJ→ DROP array was a vector, then drop the second
→LIST dimension
(1) from the dimension list.
END →ARRY Convert the elements into an array with the
given dimensions. If there are symbolic
elements present, an error will be generated
and the error clause which follows will be
executed.
THEN Begin the error clause.
OBJ→ Put the array dimensions on levels 2 and
1. If the array is a vector, level 1
contains a 1.
IF 1 FC?C Is original array a matrix? Clear flag
1 after performing the test.
THEN DROP Drop the number of matrix elements.
END → n m Store the array dimensions in local
variables.
« 1 n Begin local variable structure and
FOR initiate FOR…NEXT loop for each
i row.
m →LIST Collect a group of elements into a row (a
list).
'm*(n-i)+i' Computes the number of elements to roll
EVAL ROLLD so that the next row can be collected.
Program: Comments:
NEXT Repeat loop for the next row.
n →LIST Gather rows into a list, forming a list
of lists (symbolic pseudo-array).
» Close the local variable structure and end the
END 1 CF IFERR…THEN…END structure. Clear flag
1 before exiting the program.
»
»
Stores the program in APLY.
`OAPLY K

Checksum: #
11132d Bytes:314

Example: Apply the function, f(x) = Ax3-7 to each element x of the vector [ 3 -2 4 ].
!Ô3†2W†4`
‚å 3 QA *7 -
`J %APLY%
H#DISP ˜˜
(select small stack display to
see all vector elements.)

Converting Between Number Bases


nBASE converts a positive decimal number (x) into a tagged string representation of the equivalent value in a
different number base (b). Both x and b must be real numbers. nBASE automatically rounds both arguments to the
nearest integer.

Level Level → Level 1


2 1
x b → x bas "string"
eb:

Techniques used in nBASE


■ String Concatenation and Character Manipulation. nBASE makes use of several string and
character manipulation techniques to build up the result string.
■ Tagged Output. nBASE labels (“tags”) the output string with its original arguments so that the
output is a complete record of the command.
■ Indefinite Loops. nBASE accomplishes most of its work using indefinite loops — both
DO...UNTIL...END and WHILE...REPEAT...END loops.
nBASE program listing

Program: Comments:
«
1 CF 0 RND SWAP 0 RND RCLF Clear flag 1, round both arguments
to
integers and recall flag settings.
→b n f Store the base, number and flag
settings
in local variables.
« Begin the outer local variable
structure.
STD n LOG b LOG / Sets “standard” display mode and
computes the ratio of the common
logarithms of number and base.
10 RND Rounds result to remove imprecision
in
last decimal place.
IP n 0 Find the integer part of log ratio,
recall
the original number, and initialize
the
counter variable k for use in the
DO...UNTIL loop.
→i mk Store the values in local variables.
« Begin inner local variable
" structure, enter an empty string
" and begin the
DO...UNTIL...END loop.
D
O Compute the decimal value
'm' EVAL b of the (i – k) th position in
i 'k' EVAL the string.
- ^
DUP2 MOD Makes a copy of the arguments and
computes the decimal value still
remaining that must be accounted
for
by other positions.
IF DUP 0 == Is the remainder zero and m  b?
'm' EVAL b
Š
AND
THEN 1 SF If the test is true, then set flag 1.
END 'm' STO Store the remainder in m.
/ IP Compute the number of times the
current position-
value goes into the remaining
decimal
value. This is the “digit” that belongs
in
the current position.
IF DUP 10 Š Is the “digit” ≥ 10?
THEN 55 Then convert the digit into a
ELSE 48 alphabetic digit (such as A, B, C,
END + …).
CHR
+ 'k' 1 STO+ Append the digit to the current
result
string and increment the counter
variable k.
Program: Comments:
UNTIL 'm' EVAL 0 == Repeat the DO...UNTIL loop until m
=
0 (i.e. all decimal value have been
accounted for).
END Is flag 1 set? Clear the flag after the
IF 1 FS?C test.
THEN "0" + Then add a placeholding zero to the
result string.
WHILE i 'k' EVAL Begin WHILE...REPEAT loop to
- 0 ‹ determine if additional placeholding
zeros are needed.
Loop repeats as long as i≠k.
REPEAT "0" + Add an additional placeholding zero
1 'k' STO+ and increment k before repeating
the test-
clause.
E End the WHILE...REPEAT...END
ND loop, the IF...THEN...END
EN structure, and the inner local
D variable structure.
»
" base" b End the outermost
+ n SWAP + IF...THEN...ELSE...END structure
→TAG and
create the label string and tag the
result
string using the original arguments.
f STOF Restore original flag settings.
»
»
Stores the program in nBASE.
`OnBASE K
Checksum: #
54850d Bytes:433
Example: Convert 100010 to base 23.
1000 `23 J %NBASE%

Verifying Program Arguments


The two utility programs in this section verify that the argument to a program is the correct object type.
■ NAMES verifies that a list argument contains exactly two names.
■ VFY verifies that the argument is either a name or a list containing exactly two names. It calls NAMES if
the argument is a list.
You can modify these utilities to verify other object types and object content.
NAMES (Check List for Exactly Two Names)
If the argument for a program is a list (as determined by VFY), NAMES verifies that the list contains exactly
two names. If the list does not contain exactly two names, an error message appears in the status area and
program execution is aborted.

Level 1 → Level 1
{ valid →
list }
{ } → (er messa i stat area)
invalid ror ge n us
list

Techniques used in NAMES


■ Nested conditionals. The outer conditional verifies that there are two objects in the list. If so, the
inner conditional verifies that both objects are names.
■ Logical functions. NAMES uses the AND command in the inner conditional to determine if both objects
are names, and the NOT command to display the error message if they are not both names.

NAMES program listing

Program: Comments:
«
IF Starts the outer conditional
structure.
OBJ→ Returns the n objects in the list to
levels 2 through (n + 1), and
returns the list size n to level 1.
DUP 2. SAME Copies the list size and tests if it’s
2.
THEN If the size is 2, moves the
DROP objects to level 1 and 2, and
IF starts the inner conditional
structure.
TYPE 6. SAME Tests if the object is a name:
returns 1 if so, otherwise 0.
SWAP TYPE 6. SAME Moves the second object to level 1,
then tests if it is a name (returns 1
or 0).
AND Combines test results: Returns 1 if
both tests were true, otherwise
returns 0.
NOT Reverses the final test result.
THEN If the objects are not both
"List needs two names, displays an error
names" DOERR message and aborts execution.
END Ends the inner conditional structure.
ELSE If the list size is not 2, drops the list
DROP size, displays an error message, and
N aborts execution.
"Illegal list
size" DOERR
END Ends the outer conditional.
»
Stores the program in NAMES.
`ONAMES K
Checksum: #
10752d Bytes:141.5
NAMES is demonstrated in the program VFY.

VFY (Verify Program Argument)


VFY verifies that an argument on the stack is either a name or a list that contains exactly two names.

Level 1 → Level 1
'name' → 'name'

{ valid list } → { valid list }

{ invalid → { invalid (a error i stat area)


list } list }
→ n message n us area)
invalid invalid
object object d error stat

( message i us

a n

Techniques used in VFY


■ Utility programs. VFY by itself has little use. However, it can be used with minor modifications by
other programs to verify that specific object types are valid arguments.
■ CASE…END case structure). VFY uses a case structure to determine if the argument is a list or a name.
■ Structured programming. If the argument is a list, VFY calls NAMES to verify that the list contains
exactly two names.
■ Local variable structure. VFY stores its argument in a local variable so that it can be passed to
NAMES if necessary.
■ Logical function. VFY uses NOT to display an error message.

Required Programs
NAMES
■ NAMES verifies that a list argument contains exactly two names.

VFY program listing

Program: Comments:
«
DUP Copies the original argument to
leave on the stack.
DTAG Removes any tags from the
argument for subsequent testing.
→ argm Stores the argument in local variable
argm.
« Begins the defining procedure.
CASE Begins the case structure.
argm TYPE 5. SAME Tests if the argument is a list.
THEN If so, puts the argument back on the
argm NAMES stack and calls NAMES to verify that
END the list is valid, then leaves the
CASE structure.
Program: Comments:
argm TYPE 6. SAME Tests if the argument is not a name.
NOT THEN If so, displays an error message and
"Not name or list" aborts execution.
DOERR
END
END Ends the CASE structure.
» Ends the defining procedure.
»
Enters the program, then stores it in
`OVFYK VFY.

Checksum: #
31403d Bytes:139.5

Example: Execute VFY to test the validity of the name argument BEN. (The argument is valid and is simply
returned to the stack.)
OBEN `
J %VFY%
Example: Execute VFY to test the validity of the list argument {BEN JEFF SARAH }. Use the name from the
previous example, then enter the names JEFF and SARAH and convert the three names to a list.
OJEFF `
OSARAH `
3 !° %LIST% %²LIST%
Execute VFY. Since the list contains too many names, the error message is displayed and execution is aborted.
J %VFY%

Converting Procedures from Algebraic to RPN


This section contains a program, →RPN, that converts an algebraic expression into a series (list) of
objects in equivalent RPN order.

Level 1 → Level 1
‘symb’ → { obje }
cts
Techniques used in →RPN
■ Recursion. The →RPN program calls itself as a subroutine. This powerful technique works just like
calling another subroutine as long as the stack contains the proper arguments before the program calls itself.
In this case the level 1 argument is tested first to be sure that it is an algebraic expression before →RPN is
called again.
■ Object Type-Checking. →RPN uses conditional branching that depends on the object type of the
level 1 object.
■ Nested program Structures. →RPN nests IF…THEN…END structures inside FOR…NEXT loops
inside a IF…THEN… ELSE…END structure.
■ List Concatenation. The result list of objects in RPN order is built by using the ability of the +
command to sequentially append additional elements to a list. This is a handy technique for gathering
results from a looping procedure.

→RPN program listing

Program: Comments:
«
OBJ→ Take the expression apart.
IF If the argument count is nonzero,
OVER then store the count and the
THEN → n f function.
« Begins local variable defining
procedure.
1 n Begins FOR…NEXT loop, which
FOR converts any algebraic arguments to
i lists.
IF DUP TYPE 9. SAME Tests whether argument is an
algebraic.
THEN →RPN If argument is an algebraic, convert it to
a
list first.
END n ROLLD Roll down the stack to prepare for the
next argument.
NEXT Repeat the loop for the next
argument.
IF DUP TYPE 5. ‹ Tests to see if level 1 object is a list.
THEN 1 →LIST If not a list, then convert it to one.
END Ends the IF…THEN…END structure.
IF n 1 > Tests to see if there is more than one
argument.
THEN 2 Combine all of the arguments into a
n list.
START
+
NEXT
END f + Append the function to the end of the
list.
» End the local variable defining
procedure.
ELSE 1 →LIST SWAP DROP For functions with no arguments,
converts to a simple list.
END End the IF…THEN… ELSE…END
structure.
»
`O→RPN K Stores the program in →RPN.
Checksum: #
1522d Bytes:189.5

Example: Convert the following algebraic expression to a series of objects in RPN syntax:
'A*COS(B+ƒ(C/D))-X^3'.
OA *TB +R!Ü
C /D ™™-X Q3 `%²RPN%

Bessel Functions
This section contains a program, BER, that calculates the real part Bern(x) of the Bessel function Jn (xe3πi/4). When n
= 0,
4
x  2  x  28 4!
Berx  = 1 – -+ -–
2! 2 2

Level → Level
1 1
z → Ber(z)

Techniques used in BER


■ Local variable structure. At its outer level, BER consists solely of a local variable structure and so has
two properties of a user-defined function: it can take numeric or symbolic arguments from the stack, or it can
take arguments in algebraic syntax. However, because BER uses a DO…UNTIL…END loop, its defining
procedure is a program. (Loop structures are not allowed in algebraic expressions.) Therefore, unlike user-
defined functions, BER is not differentiable.
■ DO…UNTIL…END loop (indefinite loop with counter). BER calculates successive terms in the series
using a counter variable. When the new term does not differ from the previous term to within the 12-digit
precision of the calculator, the loop ends.
■ Nested local variable structures. The outer structure is consistent with the requirements of a user-
defined function. The inner structure allows storing and recalling of key parameters.
BER program listing

Program: Comments:
«
→x Creates local variable x.
« Begins outer defining procedure.
'x/2' →NUM 2 1 Enters x/2, the first counter value,
→ xover2 j sum and the first term of the series, then
creates
local variables.
« Begins inner defining procedure.
DO Begins the loop.
sum Recalls the old sum and
'sum+(-1)^(j/2)* calculates the new sum.
xover2^(2*j)/SQ(j!
)'
EVAL
2 'j' STO+ Increments the counter.
DUP 'sum' STO Stores the new sum.
UNTIL Ends the loop clause.
== Tests the old and new sums.
END Ends the loop.
sum Recalls the sum.
» Ends inner defining procedure.
» Ends outer defining procedure.
»
Stores the program in BER.
`OBER K

Checksum: #
15837d Bytes:203
Example: Calculate BER(3).
J

3 %BER%
Calculate BER(2) in algebraic syntax.
O %BER% !Ü2
N

RPL Programming Examples 2-30


Animation of Successive Taylor’s Polynomials
This section contains three programs that manipulate graphics objects to display a sequence of Taylor’s
polynomials for the sine function.
■ SINTP draws a sine curve, and saves the plot in a variable.
■ SETTS superimposes plots of successive Taylor’s polynomials on the sine curve plot from SINTP, and saves
the resulting graphics objects in a list.
■ TSA uses the ANIMATE command to display in succession each graphics object from the list built in SETTS.

SINTP (Converting a Plot to a Graphics Object)


SINTP draws a sine curve, returns the plot to the stack as a graphics object, and stores that graphics object in a
variable. Make sure your calculator is in Radians mode.

Techniques used in SINTP


■ Programmatic use of PLOT commands. SINTP uses PLOT commands to build and display a graphics
object.

SINTP program listing

Program: Comments:
«
'SIN(X)' STEQ Stores the expression
for sin x in EQ.
FUNCTION '-2*π' Sets the plot type and
→NUM DUP NEG XRNG x- and y-axis display
-2 2 YRNG ranges.
ERASE DRAW Erases PICT, then plots
the expression.
PICT RCL 'SINT' STO Recalls the resultant
graphics object and
stores it in SINT.
»
Stores the program in
`O SINTP K SINTP.

Checksum: #
41184d Bytes:
94
SINTP is demonstrated in the program TSA.
SETTS (Superimposing Taylor’s polynomials)
SETTS superimposes successive Taylor’s polynomials on a sine curve and stores each graphics object in a list.

Techniques used in SETTS


■ Structured programming. SETTS calls SINTP to build a sine curve and convert it to a graphics object.
■ FOR…STEP (definite loop). SETTS calculates successive Taylor’s polynomials for the sine
function in a definite loop. The loop counter serves as the value of the order of each polynomial.
■ Programmatic use of PLOT commands. SETTS draws a plot of each Taylor’s polynomial.
■ Manipulation of graphics objects. SETTS converts each Taylor’s polynomial plot into a graphics object.
Then it executes + to combine each graphics object with the sine curve stored in SINT, creating nine new
graphics objects, each the superposition of a Taylor’s polynomial on a sine curve. SETTS then puts the nine
new graphics objects, and the sine curve graphics object itself, in a list.

SETTS program listing

Program: Comments:
«
SINTP Plots a sine curve and
stores the graphics object
in SINT.
1 17 FOR n Sets the range for the
FOR loop using local
variable n.
'SIN(X)' 'X' n Plots the Taylor’s
TAYLR STEQ ERASE polynomial of order n.
DRAW
PICT RCL SINT + Returns the plot to the
stack as a graphics object
and executes + to
superimpose the sine plot
from SINT.
2 STEP Increments the loop
counter
n by 2 and repeats the
loop.
SINT Puts the sine curve
10 graphics object on the
→LIST stack, then builds a list
'TSL' containing it and the nine
STO
graphics objects created in
the loop. Stores the list in
TSL.
»
Stores the program in
`OSETTS K SETTS.
Checksum: #
41304d Bytes:
130.5
SETTS is demonstrated in the program TSA.
TSA (Animating Taylor’s Polynomials)
TSA displays in succession each graphics object created in SETTS.
Techniques used in TSA
■ Passing a global variable. Because SETTS takes several minutes to execute, TSA does not call SETTS.
Instead, you must first execute SETTS to create the global variable TSL containing the list of graphics objects.
TSA simply executes that global variable to put the list on the stack.
■ ANIMATE. TSA uses the ANIMATE command to display in succession each graphics object from the list.

TSA program listing

Program: Comments:
«
TSL OBJ→ Puts the list TSL on the
stack and converts it to 10
graphics objects and the
list
count.
{ { #0 #0 } .5 0 } Set up the parameters for
+
ANIMATE.
ANIMATE Displays the graphics in
succession.
11 DROPN Removes the graphics
objects
and list count from the
stack.
»
Stores the program in
`OTSA K
TSA.
Checksum: #
24644d Bytes:92.5
Example: Execute SETTS and TSA to build and display in succession a series of Taylor’s
polynomial approximations of the sine function.
Ensure Radians mode is set and execute SETTS to build the list of graphics objects. (SETTS takes several
minutes to execute.) Then execute TSA to display each plot in succession. The display shows TSA in progress.
!&H %!ANGLE% %!RAD% ( if necessary)
J %SETTS%
%TSA%

Press − to stop the animation. Press !&H %!ANGLE% %!DEG% to restore Degrees mode if desired.
Programmatic Use of Statistics and Plotting
This section describes a program PIE you can use to draw pie charts. PIE prompts for single variable data,
stores that data in the statistics matrix ΣDAT, then draws a labeled pie chart that shows each data point as a
percentage of the total.

Techniques used in PIE


■ Programmatic use of PLOT commands. PIE executes XRNG and YRNG to define x- and y-axis
display ranges in user units, and executes ARC and LINE to draw the circle and individual slices.
■ Programmatic use of matrices and statistics commands.
■ Manipulating graphics objects. PIE recalls PICT to the stack and executes GOR to merge the label
for each slice with the plot.
■ FOR…NEXT (definite loop). Each slice is calculated, drawn, and labeled in a definite loop.
■ CASE…END structure. To avoid overwriting the circle, each label is offset from the midpoint of the arc of
the slice. The offset for each label depends on the position of the slice in the circle. The CASE…END
structure assigns an offset to the label based on the position of the slice.
■ Preserving calculator flag status. Before specifying Radians mode, PIE saves the current flag status in a
local variable, then restores that status at the end of the program.
■ Nested local variable structures. At different parts of the process, intermediate results are saved in
local variables for convenient recall as needed.
■ Temporary menu for data input.

PIE program listing

Program: Comments:
«
RCLF → flags Recalls the current flag status
and stores it in variable flags.
«
RAD Sets Radians mode.
{{ "SLICE" Σ+ } Defines the input menu: key 1
{ } executes Σ+ to store each data
{ "CLEAR" CLΣ } point in ΣDAT, key 3 clears
{ } { } ΣDAT, and key 6 continues
{ "DRAW" CONT }} program execution after data
entry.
TMENU
"Key values Displays the temporary
into SLICE menu. Prompts for inputs.
DRAW represents the newline
restarts character (… ë) after you
program."
PROMPT enter the program on the
stack.
ERASE 1 131 XRNG Erases the current PICT and sets
1 64 YRNG CLLCD plot parameters.
"Please wait... Displays “drawing” message.
Drawing Pie
Chart"
1 DISP
Program: Comments:
(66 32) 20 0 6.28 ARC Draws the circle.

PICT RCL →LCD Displays the empty circle.


RCLΣ TOT / Recalls the statistics data
matrix,
computes totals, and calculates
DUP 100 * the proportions.
Converts the proportions
→ prcnts to percentages.
Stores the percentage matrix in
« prcnts.
2 π →NUM *
* 0
Multiplies the proportion
→ prop angle matrix by 2π, and enters the
initial angle (0).
«
prop SIZE Stores the angle matrix in
OBJ→ DROP prop and angle in angle.
SWAP
Sets up 1 to m as loop counter
FOR n
range.
(66 32) prop n GET
'angle' STO+
Begins loop-clause.
Puts the center of the circle on the
angle COS angle stack, then gets the nth value from
SIN R→C 20 * OVER the proportion matrix and adds it
+ LINE to angle.
PICT RCL
angle prop n GET Computes the endpoint and
2 / - DUP DUP draws the line for the nth slice.
COS SWAP SIN
R→C 26 * (66 Recalls PICT to the stack.
32) + For labeling the slice, computes
SW the midpoint of the arc of the
AP slice.
CA
SE
Starts the CASE structure to test
DUP 1.5 angle and determine the offset value
‰ THEN for the label.
DROP From 0 to 1.5 radians, doesn’t
END offset the label.
DUP 4.4
‰ THEN
DROP 15 From 1.5 to 4.4 radians, offsets
- END the label 15 user units left.
5<
THEN
(3 2) + From 4.4 to 5 radians, offsets
END
END the label 3 units right and 2
units up.

Ends the CASE structure.


Program: Comments:
prcnts n GET Gets the nth value from the
1 RND percentage matrix, rounds it to
→STR "%" + one decimal place, and converts
it to a
string with “%” appended.
1 →GROB Converts the string to a graphics
object.
GOR DUP PICT STO Adds the label to the plot and
stores
the new plot.
→L Displays the updated
CD plot. Ends the loop
NEXT structure. Displays the
{ } PVIEW finished plot.
»
»
flags STOF Restores the original flag status.
» 0 MENU Restores the previous menu.
(You must first press − to
clear
the plot.)

»
Stores the program in PIE.
`OPIE K

Checksum: #
16631d Bytes:737
Example: The inventory at Fruit of the Vroom, a drive-in fruit stand, includes 983 oranges, 416 apples, and
85 bananas. Draw a pie chart to show each fruit’s percentage of total inventory.
J %PIE%

Clear the current statistics data. (The prompt is


removed from the display.) Key in the new data and
draw the pie chart.
CLEAR

983 %SLICE%
416 %SLICE%
85 %SLICE%
%DRAW%

Press − to return to the stack display.


Trace Mode
This section contains two programs, αENTER and ßENTER, which together provide “trace mode” for the
calculator using an external printer. To turn on “trace mode,” set flag –63 and activate User mode. To turn
off “trace mode,” clear flag –63 or turn off User mode.

Techniques used in αENTER and ßENTER


■ Vectored ENTER. Setting flag –63 and activating User mode turns on vectored ENTER. When
vectored ENTER is turned on and variable αENTER exists, the command-line text is put on the stack as
a string and αENTER is evaluated. Then, if variable ßENTER exists, the command that triggered the
command-line processing is put on the stack as a string and ßENTER is evaluated.

αENTER program listing

Program: Comments:
«
PR1 Prints the command line
OBJ→ text, then converts the
string to an
object and evaluates it.
»
Stores the program in
`O αENTER K
αENTER. (Press ~‚A to
type α. You must use this
name.)
Checksum: #
127d Bytes:25.5

ßENTER program listing

Program: Comments:
«
PR1 DROP Prints the command that
PRSTC caused the processing, then
drops it and
prints the stack in compact
form.
»
Stores the program in
`O ßENTER K
ßENTER. (Press ~‚B to
type ß. You must use this
name.)
Checksum: #
31902d Bytes:
28
Inverse-Function Solver
This section describes the program ROOTR, which finds the value of x at which f(x) = y. You supply the
variable name for the program that calculates f(x), the value of y, and a guess for x (in case there are multiple
solutions).

Level 3 Level Level → Level


2 1 1
'functi name' y xguess → x
on

Techniques used in ROOTR


■ Programmatic use of root-finder. ROOTR executes ROOT to find the desired x-value.
■ Programs as arguments. Although programs are commonly named and then executed by calling their
names, programs can also be put on the stack and used as arguments to other programs.

ROOTR program listing

Program: Comments:
«
→ fname yvalue xguess Creates local variables.
« Begins the defining procedure.
xguess 'XTEMP' STO Creates variable XTEMP (to be solved
« XTEMP for). Enters program that evaluates f(x)
fname yvalue
- » - y.

'XTEMP' Enters name of unknown


xguess variable. Enters guess for
ROOT XTEMP.
» Solves program for
'XTEMP' PURGE XTEMP. Ends the defining
» procedure. Purges the
temporary variable.
Stores the program in ROOTR.
`OROOTR K

Checksum: #
4708d Bytes:163
Example: Assume you often work with the expression
3.7x3 + 4.5x2 + 3.9x + 5 and have created the program X→FX to calculate the value:
« → x '3.7*x^3+4.5*x^2+3.9*x+5' »
You can use ROOTR to calculate the inverse function.

FINNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
N
Full Command and Function Reference 3-40

You might also like