0% found this document useful (0 votes)
490 views238 pages

Hp42s Examples and Techniques - HiRes OCR

Hp42s Examples and Techniques

Uploaded by

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

Hp42s Examples and Techniques - HiRes OCR

Hp42s Examples and Techniques

Uploaded by

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

RPN Sdientific Calculator

Programming FExamples and Techniques

HP-425
A acians
HP-42S
RPN Scientific
Programming Examples and Techniques

HEWLETT
[fifi] PACKARD

Edition1 July 1988


Reorder Number 00042-90020
Notice
This manual and any keystroke programs contained herein are provided
" as is" and are subject to change without notice. Hewlett-Packard Com-
pany makes no warranty of any kind with regard to this manual or the
keystroke programs contained herein, including, but not limited to, the
implied warranties of merchantability and fitness for a particular pur-
pose. Hewlett-Packard Company shall not be liable for any errors or for
incidental or consequential damages in connection with the furnishing,
performance, or use of this manual or the keystroke programs contained
herein.

o Hewlett-Packard Company 1988. All rights reserved. Reproduction,


adaptation,or translation of this manual, including any programs, is prohi-
bited without prior written permission of Hewlett-Packard Company,
except as allowed under the copyright laws. Hewlett-Packard Company
grants you the right to use any program contained in this manual in this
Hewlett-Packard calculator.

The programsthat control your calculator are copyrighted and all rights
are reserved. Reproduction, adaptation, or translation of those programs
without prior written permission of Hewlett-Packard Companyis also
prohibited.

Corvallis Division
1000 N.E. Circle Blvd.
Corvallis, OR 97330, U.S.A.

Printing History
Edition 1 July 1988 Mfg. No. 00042-90019
Contents

6 List of Examples
9 How to Use This Manual

1 12 Programming
12 Simple Programming
13 Flowcharting
15 Defining the Program
15 Prompting for Data Input
16 Displaying Program Results
19 Executing the Program
21 Branching
22 Conditional Branching
25 Subroutines
29 Menu-Controlled Branching
39 Controlled Looping
43 Indirect Addressing in Programs
46 Flags in Programs
46 User Flags
47 System Flags
49 Error Trapping
51 A Summary Program
58 The Triangle Solutions Program

Contents
2 67 Enhancing HP-41 Programs
67 Using Named Variables
68 Using HP-42S Data Input and Output Functions
68 Prompting for Data with INPUT
€8 Displaying Data with VIEW
69 Operations with HP-42S Data Types
69 Using the Two-Line Display
71 Using Menu Variables
73 Assigning a Program to the CUSTOM Menu

3 77 The Solver
77 Basic Use of the Solver
80 Providing Initial Guessesfor the Solver
80 Directing the Solverto a Realistic Solution
83 Finding More Than One Solution
86 Emulating the Solver in a Program
92 Using the Solver in Programs
92 Using the Solver and Explicit Solutionsin a Program
101 Using the SOLVE and PGMSLYVFunctions with
Indirect Addresses
105 More on How the Solver Works
105 The Root(s) of a Function
107 The Solver’s Ability to Find a Root
108 Interpreting the Results of the Solver
123 Round-Off Error and Underflow

4 124 Integration
124 Basic Integration
127 Approximating an Integral That Has an Infinite Limit
131 Using the Solver and Integration Interactively
134 More on How Integration Works
134 The Accuracy Factor and the Uncertainty of
Integration
140 Conditions That Can Cause Incorrect Results
143 Conditions That Prolong Calculation Time

4 Contents
146 Matrices
146 Using the Matrix Editor and Indexing Functions
147 Creating a Named Matrix
147 Using the Matrix Editor
149 Using Indexing Utilities and Statistics
Functions Interactively
150 Matrix Utilities
154 Vector Solutions
154 Geometry
156 Coordinate Transformations
163 Solving Simultancous Equations
168 Using the Solver with Simultaneous Equations
172 Matrix Operations in Programs

174 Statistics
175 List Statistics
181 Using the Summation-Coefficient Functions +,
¥ -, and CLY) in Programs
193 Curve Fitting in Programs

194 Graphics and Plotting


194 Graphics
202 Multifunction Plots
212 Plotting Data from a Complex Matrix

Contents
List of Examples
The following list groups the examples by chapter.

1 Programming
20 Executing a Program from the CUSTOM Menu
32 A Programmable Menu
42 Loop Control in a Program
57 The Flag Catalog Program

2 Enhancing HP-41 Programs


74 Executing an Enhanced HP-41 Program from the
CUSTOM Menu

3 The Solver
78 Basic Use ofthe Solver
80 Directing the Solver to a Realistic Solution
84 Using the Solver to Find Two Real Solutions
87 Using the Solver for a Simple Resistive Circuit
90 Calculating Complex Values in an RC Circuit
99 Executing Algebraic Solutions for TVM Problems
101 Using SOLVE with an Indirect Address
110 A Case 1 Solution with Two Roots
112 A Case 2 Solution
114 A Discontinuous Function
116 A Pole

6 List of Examples
118 A Relative Minimum
119 An Asymptote
120 A Math Error
121 A Local Flat Region

Integration
125 Basic Integration
128 Evaluating an Integral That Has an Infinite Upper
Limit
131 Using the Solver and Integration Interactively
136 The Accuracy Factor and the Uncertainty of
Integration
138 A Problem Where the Uncertainty of Integration is
‘ Relatively Large
140 A Condition That Causes Incorrect Results
142 Subdividing the Interval of Integration
143 An Upper-Limit Approximation That Prolongs
Calculation Time

Matrices
146 Accumulating Meterological Data
158 The Area of a Parallelogram
161 A Three-Dimensional Translation with Rotation
163 Solving Real-Number Simultaneous Equations
166 Solving Simultaneous Equations That Have
Complex Terms
169 Using the Solver to Find the Value of an Element
in the Coefficient Matrix

Statistics
178 Accumulating Statistical Data in a Matrix
191 A Linear Regression for Three Independent
Variables

List of Examples 7
7 Graphics and Plotting
199 Building a Logo
201 Using Binary Data to Build a Logo
210 Plotting Multiple Functions
219 Plotting Data from a Compression Process
and Fitting a Power Curve to the Data

8 List of Examples
How to Use This Manual
Welcome to the Programming Examples and Techniques manual for your
HP-42S calculator. This manual builds on concepts introduced to you in
the HP-42S Owner’s Manual so that you can more fully utilize your
calculator’s powerful problem-solving capabilities. This manual focuses on
the following subjects:

m Programming techniques for the HP-42S.


= Enhancing existing HP-41 programs.
m Using the HP-42S built-in applications:
a The Solver.
s Integration.
® Matrices.
m Statistics.
® Building and printing graphics patterns and plots.

There are many examples in this manual. We feel that the best way to
help you gain expertise with yourcalculator is to show you how to solve
practical problems in mathematics, science, engineering, and finance.
Many of these problemsare solved using programs. Chapter 1, "Program-
ming," addresses the task of creating programs with the HP-428. It further
develops material presented to you in chapters 8 through 10 ofthe
owner’s manual.

Chapter2 specifically addresses the topic of enhancing programs written


for the HP-41 calculator. It builds on the material introduced in chapter
11 of your owner’s manual.

Chapters 3 through 6 further develop the built-in applications discussed in


chapters 12 through 15 of the owner’s manual. If you wish to learn more

How to Use This Manual 9


about matrix operations, for example, you can turn directly to chapter 5,
"Matrices,” without working through the preceding chapters. However,
since many of the examples in the manual are programmed solutions to
problems, you shouldfirst review chapter 1.

Chapter 7 describes how to generate graphics patterns and plots using the
HP-42S calculator and, in several examples, the optional HP 82240A
Infrared Printer. It builds on the material presented in chapter 7 of the
owner’s manual.

The notations in this manual are consistent with those in the owner’s
manual:

m Plain typeface is used for numbers and Alpha characters in keystroke


sequences: 1.2345, ABCD.
m Black keyboxes are used for primary keyboard functions in keystroke
sequences: (EXIT).
m Orange keyboxes preceded by the orange shift key are used for secon-
dary (shifted) functions in keystroke sequences: J[ASSIGN).
s Menu keyboxes are used for functions executed from a menu in
keystroke sequences: Le
m Capital letters are used for any functionthatis referenced in text:
CLP.
s Capital letters are used for program namesthat are referenced in
text: SSS.
s Italic letters are used for variable names that are referenced in text:
STEP
@ Dot matrix typeface is used for program listings:
01 LBL "RRER".

At the beginning of each example,it is assumed that the stack registers


(X-, Y-, Z-, and T-registers) are clear (contain the value 0). Itis also
assumed that the value of each variable in the examples is 0. Your display
may sometimes differfrom the displays in the manual. However,if you exe-
cute the keystroke sequences as they are shown in the examples,the
values ofthe stack registers and variables in your calculator at the start of
the examples will not affect the answers you obtain.

10 How to Use This Manual


Some examples include optional instructions to print results with the
HP 82240A Infrared Printer. If you have a printer and execute these
instructions, you will not see some of the subsequentdisplays in the exam-
ple. These displays will be printed.

How to Use This Manual "


Programming
Your calculator is a powerful and easy-to-use tool for creating and execut-
ing programs. This chapter builds on programming methods introduced to
you in chapters 8 through 10 of your owner’s manual. Specifically, this
chapter addresses:

® Simple programming.
= Branching.
s Looping controlled by a counter.
® Indirect addressing.
s Flags in programs.
m Error trapping.

Simple Programming
The program SSS in this section finds the values of the three angles of a
triangle when the values of the three sides are known. (The annotated list-
ing is on pages 17 through 18.)

12 1: Programming
S3

When the dimensions of the three sides (S, Sz, and S3) of a triangle are
known, the following equations are used to calculate the three angles
(Al 9A2’ andA3)‘

VP(P -Sz) (S],+SZ+SS)


Az 3 =2 arccos[ -
(5:53) ]w—~~\whereP
ere >
= ———

A,=2arccos |——————
VPP —sl)]
2 (S2S3)
A, = arccos [ -cos (A3 + Az)]*

These equations form the main body of SSS.

Flowcharting

A flowchartis a graphical outline of a program. Flowcharts are used in


this manual to help you understand how programs solve problems.
Flowcharts can also help you design your own programsby breaking them
down into smaller groups ofinstructions. The flowchart can be as simple
or as detailed as you like. Flowcharts are drawn linearly, from top to bot-
tom,representing the general flow of the program from beginning to end.

* This expression for 4 , enables you to calculate 4 in any angular mode.

1: Programming 13
Here is a flowchart for one possible program solution for the side-side-
side triangle problem.

CALCULATE
A3
v
CALCULATE
Ao
v
CALCULATE
Ay

v
DISPLAY
AyAsAg

14 1: Programming
This manual uses the following conventions for flowchart symbols:

m An oval represents the beginning or end of a routine. This can be the


beginning or end of a program,a subroutine, or a counter-controlled
loop within a program.
® A circle represents a program label. It also represents a GTO instruc-
tion to a program label from another pointin the program. (This con-
vention reduces the need for connecting lines that can make the
flowchartdifficult to read.)
m A rectangle represents a functional operation in the program.
m A diamond represents a decision the program makes based on a com-
parison of two values (or based on the status of a flag).
m A triangle represents a decision the user (that’s you) makes by select-
ing oneof several possible program routines, each of which performs
a different task.

Defining the Program


Program SSS begins with a global label and ends with an END instruction.
These two instructions define the beginning and end of the program.

Bl LBL "gsg

45 END

Prompting for Data Input

SSS prompts you for data input (prompts you for the three known values
of the sidesofthe triangle).

B2 INFUT "S51°
83 INPUT “sz2"
84 IHFUT "53"

1: Programming 15
Displaying Program Results
SSS concludes by displaying (or printing) the calculated results (the three
angles).

41 SF 21
42 YIEW "A1"
43 VIEW "R2"
44 YIEW "R3"

This section of the program begins by setting flag 21, the Printer Enable
flag. When flag 21 is set, a VIEW (or AVIEW)instructionis:

® Printed and displayed if you have executed PRON. Program execution


does not halt when a message is displayed; a subsequent VIEW (or
AVIEW) instruction erases the current message. When you set flag
21 and execute PRON,and then execute a program that has a
sequence of VIEW (or AVIEW) instructions, you must have a printer
present and turned on to record each message; you'll see only the last
message in the display.
u Displayed by the calculator if you have executed PROFF. (PROFF is
the default mode for the calculator. You need to execute PROFF only
if you have previously executed PRON.) When you set flag 21 in
PROFF mode, program execution halts after each VIEW (or
AVIEW) instruction and must be resumed bypressing [R/S].

16 1: Programming
Helpful hints for keying in programs:

1. If the variables you are using in your program do notalready exist,


create them before you select Program-entry mode (by pressing 0
variable for each variable). When you subsequently key in a
STO, RCL, INPUT, or VIEW instruction during program entry and
are prompted for a register or variable, the existing variables
(including the ones you just created) are displayed in the variable-
catalog menu. You only need to press the corresponding menu key,
rather than type the variable name.
In Program-entry mode, first key in all the global labelinstructions
in your program (bypressing MFGMFCN) i Jabel for each
label). When you subsequently key in branchmstructlons and are
prompted for a label, the existing globallabels (including the ones
you just created) are displayed in the program-catalog menu. You
only need to press the corresponding menu key, rather than type the
name.

Longer programs in this manual are preceded by instructions thatlist the


variables and labelsto create for program entry.

To key in SSS: Create variables S1, S2, §3, 41, A2, A3, and P before
program entry.

Here is an annotatedlisting of SSS.

Program: Comments:

a8 { 115-Bute Prgm 2 Line 01: Define the beginning ofthe


81 LBL "Sgs* program.

az IHPUT "S1¢ Lines 02— 04: Prompt for the values of


a2 INPUT "S2" the three sides and store the values in
a4 IHPUT "53" named variables.

a3 RCL "S1" Lines 05-40: Calculate 4,,4,, and


a5 RCL+ "S52" Ag. Store the values in named vari-
a7 RCL+ "g5a ables.
a3 2
a9

1: Programming 17
STU IIPII

Are
LASTA
RCLx "2

RCL "S1"
RCLx "5z

S SRORT
HCOS
i a0 ) oo,
Lo 0 03 Q3 Q0 0 00 Q0 P P T3 {0 P P D M) T

¥ I2

STO "AS"
SIN
RCL P
K12
LASTH
RCLx "S1°
9 RCL+ "5
03 =l T i £ IO oD

RCL+ 'S
SERT
G
HLLES

0 n H-E n

CL+ "A3"

RACOS
STO "ALY

SF 21 Lines 41 -44: Display (or print) the


2 VIEW "A1" calculated results.
: WIEM A2
VYIEW "A3"

435 EHL Line 45: End the program.

18 1: Programming
Executing the Program
You can execute SSS by using any oneof the following keystroke
sequences.

Using the Program Catalog. The global label SSS was automatically
placed in the program catalog when you keyed in program line 01. You
can execute the program by pressing
PCATALOG] FGM . 888

This sequence requires a minimum offour keystrokes, depending on


where label /€SS is in the program catalog. (If you have created more
than five programs subsequentto SSS, use the [¥] key to find label
S55 )

Using XEQ. When you press (XEQ), the program-catalog menu is


automatically displayed. Thus, you can execute SSS by pressing

888
This sequence requires a minimum of two keystrokes, depending on
where label SSS is in the program catalog.

Using the CUSTOM Menu. Alternately, you can assign SSS to the
CUSTOM menu by pressing

B(ASSIGN} FGM 883

and then the desired menu key.

1: Programming 19
The program can now be executed directly from the CUSTOM menu by
pressing

BCUSTOM) 5885
This sequence requires three keystrokes when you first select the
CUSTOM menu, and only one keystroke on subsequent executions if you
stay in the current row of the menu.

Example: Executing a Program from the CUSTOM Menu. Find


the angles (in degrees) of the following triangle.

83 =275t

Assign SSS to the CUSTOM menu. Set the angular mode to Degrees.
Execute PRONif you have a printer and wantto print the results. Begin
program execution.
S170.8600
Lsss [ 11|

Enter the value for S, (in feet) and continue program execution.
24 12 [ 5270, 0000
SID

20 1: Programming
calculates the
Enterthe value for S5, then for S3. The program now
executed PRON
three angles and displays 41, the first result. (If you have
ys.)
to print the results, you won’t see the next two displa
1 2.75 Al=129.8384
N

Continue program execution to see A 3.


Az2=33. 9479
.

Continue program execution to see As.


A3=16.2136
53I AT S.

Exit from the program.


v: 8,2792
x: 129.8384

Branching
to a different
A branch instruction enables program execution to jump
location in program memory. A branch can be:
» Conditional (based on a test).
on completion,
s Unconditional (used typically to call a subroutine that,
returns program execution to the main progr am).
m Menu-controlled (executed by you from a programmable menu).

1: Programming 21
Conditional Branching
The program SSA on pages 24 through 25 in this section illustrates the
use of conditional branching. SSA finds the two unknown angles and the
unknown side ofa triangle when two sides and the adjacent angle (S,
S2,and 4,) are known,

The equations used to calculate A5, 4,, and S5 are

. S2] .
Ag=arcsin =] sinAd,
Sy

A; =arccos| —cos (Ay + Ag)]

S3=S,cos A3+ S,c08A4,

Note from the drawing that two possible solutions exist if S, is greater
than S; and A3 does not equal 90°. This leadsto a fourth equation.

A" =arccos (-cosAdj)

SSA calculates both possible answersets.

Here is a flowchart for the program.

22 1: Programming
SSA
LBL
SSA

INPUT
S1.55, A
Y
CALCULATE
Ag
v
CALCULATE
Ay.S;
Y
DISPLAY
RESULTS

NO

CALCULATE
A’
3

v
CALCULATE
Ay Sy
v
DISPLAY
RESULTS

1: Programming 23
Observe from the flowchart that the program calculates the first answer
set, then compares the values of S, and S;. Depending on the result of
the comparison,the program either returns to label SSA or calculates the
second answerset. SSA accomplishes this with a conditional branch. The
corresponding keystrokes are highlighted in the following annotated list-
ing. (This conditional branch is based on a number test. Later in this
chapter, you’ll write programs that make conditional branches based on
flag tests.)

To key in SSA: Create variables S1, S2, $3, 41, A2, and A3 before pro-
gram entry. (These variables already existif you keyed in program SSS.)

Program: Comments:
86 { 157-Bute Pram 2
A1 LBL "SSA"
B2 SF 21

62 IMPUT "sS1" Lines 03-05: Input the known vari-


84 INFUT "S2" ables.
85 IMFUT “A2"
@& SIN Lines 06-23: Calculate the unknown
B? RCLx "s2" variables.
g2 RCL+ "s1v
89 ASIN
18 STO "R3"
11 RCL+ "R2"
12 Cos
13 +--
14 ACDS
15 STO AL
16 RCL "R2"
17 Cos
18 RCLx "g2¢
12 RCL "R3"
Z| cos
21 RCLx "3y"
22 +

24 1: Programming
STO "s53"
VIEW "A1" Lines 24~ 26: Display (or print) the
VIEW "S3" unknown variables.
VIEW "A3"
RCL "S1" Lines 27-30: Test if S, is less than or
s RCL “g2" equal to S, . If so, return to the begin-
5 HEY? ning of the program. If not, calculate
GTO “SSA" the second answer set.

RCL “A3" Lines 31 -48: Calculate the second


COS answer set.
+/-
ACOS
STO "A3"
RCL+ "R2"
coS
+/-
ACOS
sTO "A1"
RCL “A2"
cos
RCLx "g2"
RCL "A3"
cos
RCLx "S1"
-+

sTO 53"
VIEM "A1" Lines 49 - 52: Display the second
VIEW "53" answerset and return to the beginning
VIEW "A3" of the program.
GTO "SSA"
EMD

1: Programming 25
Subroutines

A routine is a set of program steps defined by a local or global label and a


RTN or END instruction. (Programs SSS and SSA are routines.) A rou-
tine becomes a subroutine whenitis called by (executed from) another
routine using an XEQ instruction. After the subroutine has been exe-
cuted, the RTN or END instruction at the end of the subroutine retums
program execution to the main routine.

Notice that SSA calculates the second answer set (if there is one) by first
calculating 45" . It then calculates the remaining unknowns using the
same equations that were used to calculate thefirst answer set and
displays the second answer set using the same instructions that were used
to display the first answerset. By placing these shared instructions in a
subroutine, the program becomes:

m Shorter.
s Easier to read.
= Easier to write.
m Easier to edit.

Here is a flowchart for a new program SSA2 that uses a subroutine.

26 1: Programming
SSA2

INPUT
—)
S1.8.4
Y
CALCULATE
A3
Y
XEQ

B-=<>
SSASUB

ALCULATE CALCULATE
A ’
3 Ay S
Y
XEQ
v
DISPLAY
SSASUB RESULTS

, RTN

The corresponding program lines are highlighted in the following anno-


tated listing.

To key in SSA2:

1. Create variables S1, 52, $3, 41, A2, and A3 before program entry.
2. Create label SSASUB when you begin program entry.

1: Programming 27
Program: Comments:
0e { 137-Byte Pram >
01 LBL "SsAz2"
a2 SF 21
a3 INPUT "S1"
04 INPUT "S2°
@5 INPUT "R2"

a6 SIN Lines 06 -09: Calculate 4.


as RCLx "gz2"
a8 RCL+ "51*
a9 ASIH

16 ®EQ "SSAsSUB" Line 10: Call subroutine SSASUB to


calculate A, and S5. This uncondi-
tional branch uses an XEQ instruc-
tion; the next encountered RTN (or
END)instruction will transfer pro-
gram execution back to line 11. (Now
follow the branch to line 21.)
11 RCL "sS1" Lines 11-14: If §, is less than or
12 RCL "s2" equal to S, , return to the beginning of
13 RLY? the program. If not, calculate the
14 GTO "SSAz" second answer set.
15 RCL "R3" Lines 15-18: Calculate 45" .
16 cos
17 +/-
12 ACOS

REQ "SERSUE Lines 19 -20: Call subroutine


LTO "S5A2" SSASUB to calculate 4, and S3”.
Then return to the beginning of the
program.
LEL "SSASUE" Subroutine SSASUB,lines 21 ~39:
T [0 [
03 Do

570 "RZ" Calculate the values 4; and S3 (4;”


RCL+ "R2" and S,° in the second answerset), and
Cos display the results.

1: Programming
25 +--
26 RACOS
z7 5T0 "A1"
2% RCL "A2"
29 CDsS
Ze RCLx "g2"
=1 RCL "A3"
22 COS
@3 RCLx "S1"
24 +
35 STO "S3t
36 VIEW "ALY
37 WIEW "g3"
22 VIEW "R3"
22 RTH

48 EHD

SSAZ2is 13 lines shorter than SSA and 20 bytes shorter than SSA.

Nested Subroutines. The program TRI X in the following section


organizes each ofthe five possible triangle solutions in subroutines
labeled A through E. Referto the flowchart for TRIA. on pages 30-31,
and note that subroutine B, which calculates the solution to the SSA initial
condition,itself calls subroutine SSASUB to calculate 4, and S3. In
TRI 4., subroutine SSASUB is nested in subroutine B. When subroutine
SSASUB is called by subroutine B, there are two pending subroutines.
The HP-42S can have up to eight pending subroutines.

Menu-Controlled Branching
Programmable menus enable you to make a decision during a program,
prompted by labeled menu keys that cause branches to new locationsin
program memory. Using KEY XEQ or KEY GTO instructions (which act
just like XEQ and GTO instructions), any label in program memory can
be madethetarget of a programmable menu key. When MENU and
STOP instructions are subsequently executed, program execution is
suspended, the programmable menu is displayed, and keys 1 through 9
(the six top-row keys, plus the [a], [¥], and keys) assume their
menu definitions.

1: Programming 29
The previous two programs, SSS and SSA,each calculated one ofthe five
triangle solutions. The other solutions respectively find:
® S3, Az,and Ss(when 44, S, and A, are known).
® S;, S3,and A5 (when S,, 4,, and A, are known).
B A, S3,and 43 (when S;, 4,, and S, are known).

Here is a flowchart for a program named TRIX.. TRI.X. organizes each


ofthe five solutions in a subroutine, builds a programmable menu, and
allows you to select any solution by pressing the corresponding menu key.

1A o0
TRIA
BUILD MENU

DISPLAY MENU
AND STOP FOR INPUT
KEY 1 KEY 2 KEY 3 KEY 4 KEY 5
“SSs* "SSA" *ASA" “SAA" "SAS"
XEQ XEQ XEQ XEQ XEQ

i
B Cc D E

v v v

@)
XEQ RESULTS

30 1: Programming
7
INPUT
S1,82,83
INPUT
S1,82,A2
¥ 7 7
INPUT
Aa,S1,A1
INPUT
S1,A1,A2
INPUT
S1,A1,S2

CALCULATE] CALCULATE| |CALCULATE| CALCULATE] CALCULATE


Ay A2 Ay A3 S2:A2, 83 [S2: 5343 |A2:S3: 48

RTN RTN RTN RTN


L—) SSASUB C ) ( ) ( )

@—
RESULTS
RESULTS
CALCULATE
CALCULATE AREA
F———————— e ————— -

(SSASUB) Ay’
v
DISPLAY
CALCULATE XEQ INPUTS,
Ay,S3 SSASUB RESULTS

RTN RTN
v

1: Programming 31
The triangle symbol in the flowchart indicates where the program stops to
display the menu. You choose which solution you wantto execute by
pressing the corresponding menu key.

Here are the corresponding program lines.

Program: Comments:

a3 "S55 Lines 03 -12: Build the menu keys.


84 KEY 1 XEQ A (For example,lines 03 and 04 label
85 “SsSA" menu key 1 with the Alpha string SSS
85 KEY 2 KEGQ B and define that key to execute a
g7 "RSA" branch to label A.)
92 KEY 3 XEQ@ C
as “SAR"
16 KEY 4 XEQ D
11 “SAS”
12 KEY S ¥EQ E

13 MENU Lines 13~ 16: Select the menu (line


14 STOP 13) and suspend program execution
15 XE®@ "RESULTS" (line 14). (The menu is displayed
16 GTO "TRIL" when program execution halts.) After
execution of any subroutine A through
E,call subroutine RESULTSto
display the results (line 15). Then
return to label TRIX at the start of
the program (line 16).

The complete listing of TRIX is on pages 60-65 at the end of this


chapter.

Example: A Programmable Menu. A surveyor needs to find the


area and dimensions ofa triangular land parcel. From point A, he meas-
ures the distance to points B and C, and the angle between AB and AC.

32 1: Programming
Aq=98°127

Sy=171.63m Sp=207.35m

Thisis an SAS (side-angle-side) problem.

Set the angular mode to Degrees. (Execute PRON if you want to print the
results.) Begin program execution.

B(MODES] CEG %: B.0000


(BFRNT) @ FPON ) SRNTNT
TR Iz

Select the SAS routine by pressing menu key 5.


S170.0000
iy
X
ol

IN ICHETN T.

Key in the value for S, and continue program execution.


171.63 [R/S] A170. 0600
BBTEEN ETET

Keyin the values for A, (you need to convert A, to its decimal equivalent)
and S,. The program calculates the unknowns and displays the initial
known values and calculated results.

98.12[J[CONVERT] +HF S1=171, 6300


297.35 x: 25, 256.2094

Press three times to see A,.


(R/S]) (R/S) AZ=27.8270
x: 254 256. 2094

1: Programming 33
Press again to see Sj.

53
%

Press again to see A 4.


R/S] A3=53, 9730
X: 29y 206. 2094

Press again to see AREA.


[R7S] ARER=25, 256, 2094
X: 25, 256. 2094

Press again to display the menu.


X 25 296 . 2094

End the program.


EXIT v: 27. 8270
X: 255 256. 2094

Multirow Menus. The preceding program, TRIX., builds menu labels


for five of the six top-row keys, and assigns a KEY XEQ instruction to
each labeled key.

A multirow menu has more than one row oflabeled keys. (For example,
the CLEAR menu has two rows.) When you enter a multirow menu,the
(¥) and (&) keys enable you to move to each row in the menu. (The va
annunciator appearsin the display to show you that these keys may be
used to display more rows.)

You can emulate a multirow menu in a program by assigning KEY GTO


instructions to menu key 7 (the (&) key) and menu key 8 (the [¥] key).
(KEY GTO or KEY XEQ instructions for menu keys 7 and 8 also
automatically turn on the va annunciator in the display.)

34 1: Programming
Consider the following simple menu ofcalculator functions.

VA
R

VA

KR Y
e

Hereis a program that emulates this multirow menu.

To key in ROW1:

1. Create labels ROW1, ROW2, and ROW3 when you begin program
entry.
2. Note that program lines 03, 05, 07, 16, 18, 20, 29, and 31 are Alpha
strings.

Program: Comments:
08 { 184-Buyte Pram
@81 LBEL "ROW1"

@z CLMEHNU Lines 01-13: Clear the current menu


@3 "I definitions, then build and display the
@4 KEY 3 XER @1 first row of the menu. Assign branch
@s "LoG" instructions to keys 7 and 8 (the (4]
86 KEY 4 XER 62 and (V) keys) to the previous and
a7y "LN" succeeding rows respectively (lines
a2 KEY 5 #XER @83 09-10).
B9 KEY ¢ GTO "ROW2®
18 KEY & GTO “"ROWZ"
11 HMEHU
12 STOP
12 GT0 "ROMWL"

1: Programming 35
14 LBL "ROW2" Lines 14 -26: Clear the current menu
15 CLMEHNU definitions, then build and display the
16 IIR¢II
second row of the menu. Assign
17 KEY 3 XKEQ 94 branch instructions to keys 7 and 8 to
18 "SIN" the previous and succeeding rows
19 KEY 4 XEQ 85 respectively (lines 22 -23).
z2e "cos"
21 KEY S XKEQ B8
22 KEY v GTO "ROW1™
23 KEY & GTO "ROW3"
24 MERU
25 STOF
26 GTO "ROW2"

2v LBL “ROKWZ" Lines 27-37: Clear the current menu


28 CLMENU definitions, then build and display the
29 "KLY third row of the menu. Assign branch
38 KEY 3 XEG 67 instructions to keys 7 and 8 to the pre-
3 Wy st vious and succeeding rows respectively
32 KEY 4 XEQ B3 (lines 33-34).
33 KEY 7 GTO "ROW2"
34 KEY & GTOD "ROM1"
35 MEHU
36 STOP
37 GTG "ROK3"

38 LEL @1 Subroutines 01—08,lines 38 - 61: Exe-


39 SQRT cute the calculator functions
45 RTH corresponding to each menu label.
41 LEL a2
4z LOG
-
-~ RTH
44 LEL @3
45 LN
46 RTH
47 LEL @4
45 R4
49 RTH

1: Programming
50 LBL @5
51 SIN
S52 RTH
53 LBL 96
54 COS
55 RTN
56 LBL B7
57 ROV
58 RTH
59 LBL @8
68 +/-
61 RTH
62 END

Nested Menus. In many menus, one or more ofthe six top-row menu
, in
keys bring up a new menu called a nested, or submenu. For example
a nested
the PGM.FCN menu, when you press the =¥7@ menu key,
X#0?, ..., X>0?) is display ed. To return
menu of related functions (X=0?,
to the main menu, you press the key.

You can emulate a nested menuin a program by assigning a KEY GTO


instruction to any labeled top-row menu key. Consider the following sim-
ple menu of calculator functions.

Here is a program that emulates this menu structure.

To key in LVL1:

1. Create labels LVL1 and LVL2 when you begin program entry.
2. Note thatlines 03, 05, 07, 14, 16, and 18 are Alpha strings.

1: Programming 37
Program: Comments:
ag { 188-Bute Pram >
a1 LBL "LwL1"

B2 CLMEHL Lines 01-11: Build and display the


a3 ||+II
primary level of the menu. Assign to
a4 KEY 2 ®ER 81 key 3 (labeled TRIG) a branch
a5 instruction to label LVL2 to build the
Q& KEY 2 MEQ @2 nested menu (line 08).
arv "TRIG"
a3 KEY 3 GTO “"LwLz"
a9 MENU
18 STOP
11 GTO "LwL1"

12 LEL "LWL&" Lines 12-23: Build and display the


1= CLMEHL nested menu. Assign a branch instruc-
14 "SIH® tion to key 9 (the key) back to
1S KEY 4 XE@ 11 label LVLI1 (line 20).
1 "cos"
17 KEY 3 XE& 12
18 "TARH"
KEY & RER 13
PO Ko
-0

KEY & GTO "LVL1™


MEML
STQP
M i3]
0 P

GTO "LwvLz"

LEL @1 Subroutines 01, 02, and 11-13, lines


0 [0 03 O3 [ B P P TR
FYo D0 0O N R

-+
24-38: Execute the calculator func-
RTH tions corresponding to each menu
LEL 82 label.

RTHN
LEL 11
SIN
RTH
LEL 12
Cog
o

1: Programming
35 RTHN
36 LBL 13
37 TAN
32 RTHN
39 EHND

Controlled Looping
A controlled loop is a loop that is executed a specified number oftimes.
You can build a controlled loop with a local or global label, an ISG or
DSE instruction, and a GTO instruction.

The program DISPLin this section uses a controlled loop to calculate


successive linear displacements of an object traveling at a constant velo-
city.

The equation of motion for constant velocity on a smooth surface is

X =xp+Wvt

where:

x is the total displacement.


X is the initial position.
v is the velocity.
t is the elapsed time.

DISPL calculates the displacementat successive time intervals from ¢ = 0


tot = t; . It builds a loop counterof the form .fffcc by prompting you for
the value of t;, and for the value of STEP (the value ofthe time interval).
t; becomes the fff portion of the counter and STEP becomestheii portion
of the counter.

1: Programming 39
Here is a flowchart for DISPL.

DISPL {BL
DISPL
INPUT
Xg 1V t; STEP
v
BUILD COUNTER
FROM t, , STEP

FOR EACH TIM


(0TO t/)
CALCULATE
X

VIEW
X

INCREMENT
t

=
The program segmentthat uses a controlled loop to calculate successive
values ofx is highlighted in the following annotated listing.

40 1: Programming
To key In DISPL: Create variables x, x0, v, tF, STEP,fff, ii, and COUNT
before program entry.

Program: Comments:
88 { 110-Byte Pram 2
@1 LBL "DISPL"
B2 SF 21

@2 INPUT “x@" Lines 03 -16: Prompt for the vari-


84 INPUT "u* ables. Build the counter.
85 INPUT "tF"
& INPUT "STEP"
87 RCL "tF"
88 1E-3
g9 x
18 STO “fff"
11 RCL "STEP"
12 1E-S
13 X
14 STO "ii"
15 RCL+ "ff¢"
16 STO "COUNT"®

17 LBL @1 Lines 17-27: Calculate successive


12 RCL "COUMT" values ofx in the counter-controlled
19 IP loop. (Note that the integer part of
268 RCLx "y COUNTin line 19 is the time ¢.)
21 RCL+ "x@*
22 STO "x"
22 CL¥
294 YIEW "x"
25 I8G "COUMTH
26 GTO @1
27 GTO "DISPL"

28 END

1: Programming 41
Example: Loop Control in a Program. Find successive values of
the displacement x of an object in intervals offive seconds from ¢ = 0 to
t = 15 seconds when x, = 10 meters and v = 20 meters/second.

Begin program execution.


. - D, 0
Dl 328,000
DBOD
Enter the values for xq and v.
10 20 [R78]
: 28.000
1F56: 66000

Enter the value for ¢, and continue program execution.


15 [R/S) : 15, 0000
STER0. 0000
Enter the value of STEP (thesize of the interval) and continue program
execution,
5 R/S)

The value ofx at ¢ = 0 is 10. Press again to display the value ofx at
t=35.

T
Press to see the value ofx at t = 10.

T
Press againto see the value ofx at ¢t = 15.

A
Press again to prompt for new values. Exit from the program.
[@73) [EXm) 0.0000
% 10,6000

42 1: Programming
Indirect Addressing in Programs
Indirect addressing is a useful programming tool, particularly when used
in combination with a controlled loop. The operation index in your
owner’s manual indicates which functions can use indirect addresses. In
this section, three applications of indirect addressing in programs are
presented.

Using Indirect Addressing to Initialize Data Storage


Registers. Program INIT prompts for data and storesit in successive
registers using INPUT IND in a controlled loop. Thisis a useful initializa-
tion routine if you are using registers instead ofvariables for data storage
and recall.
R { 3I7-Bute Pram *
@1 LEL "IHWIT®

Bz 1.a1 Lines 02-03: Build a counter and


B2 STO "COUMT® store it in COUNT. The counter has a
beginning value of1, a test value of 10,
and a default increment value of 1.

64 LEL 81 Lines 04—07: Promptfor data for suc-


3% IMPUT IMD "COUNT" cessive registers Rog; —Ryp.
A& ISG "COUNWT®
87 GTO a1

B2 EHD

1: Programming 43
Using Indirect Addressing to Clear Registers. The following
routine clears a specified number of storage registers using STO IND in a
controlled loop.

Program: Comments:
a0 { 74-Byte Pram >
a1 LBL "CLEARR"

a2 a Line 02: Initialize the X-register to 0.


B3 "FIRST?" Lines 03-10: Build a counter in
a4 PROMPT COUNT. The counter has a beginning
as STO "“COUNT" value equal to the first data storage
5] "LAST?" register to be cleared, a test value
a7 PROMPT equalto the last register to be cleared,
a3 1E-3 and an increment value of one.
a9 x
19 STO+ "COUNT"
11 LBL 1@ Lines 11-15: Successively set the
12 a values of the block ofspecified regis-
13 STO IND "COUNT" ters to 0.
14 ISG "COUNT"
15 GTO 1@

16 TONE 9 Lines 16-18: Sound a tone and


iv "RERADY" display the message RERDY. Press
18 PROMPT to end the program.
19 EMD

4 1: Programming
Using Indirect Addressing to Execute Subroutines. The follow-
ing routine retrieves data (telephone numbers) from subroutines using
XEQ IND.

Program: Comments:

oo { 134-Byte Pram 2
a1 LBL "PHONE"

a2 “NAME?" Lines 02-08: Prompt for the name


63 AOH (Alpha string) whose telephone
04 FROMPT numberis desired (lines 02-05) and
as AOFF store the string in the X-register (line
a6 ASTO ST X 06). (The string may be six Alpha
ar KE@ IND ST X characters maximum; the X-register
as PROMFT holds only up to six Alpha characters.)
Execute the subroutine whose label
matches the Alpha string (line 07),
then suspend program execution (line
08).

a9 LBL "JANET" Lines 09 ~23: Build the telephone


16 "@eE-555-9874" numbers (actually Alpha strings) in
11 RTH the Alpha register.
12 LBL "BRUCE"
13 "@BB-555-1356"
14 RTHN
15 LBL "PAM"
16 "@aB-555-6033"
iv RTH
18 LBL "CHRIS"
19 "B8@8-555-627E"
28 RTN
21 LBL "poB"
22 "BEa-355-2411"
23 RTH

24 EHD

1: Programming 45
Flags in Programs
Earlierin this chapter you wrote a program SSA that makes a branch
based on a numbertest; specifically, SSA uses the X<Y? function to con-
struct the branch. The program asks the question: Is S < S, ? Then it
makes a decision based on the answer —either calculate the second answer
set or end the program.

The X?0 and X?Y sets of functlons enable programsto ask questions only
concerning numbervalues.© However, programscan also make condi-
tional branches (ask questions and make decisions) based onflag tests.
Flag tests follow the "do-if-true” rule. If the testis true, the next instruc-
tion is executed. If the testis false, the next instruction is skipped.
Because flags have unique meanings for the calculator, they greatly
expand the logic control you can exercise in a program. (User flags 00
through 35 and 81 through 99 may be set, cleared and tested. System flags
36 through 80 may only be tested. Refer to appendix C in your owner’s
manualfor a complete listing of the HP-42S flags and their meanings.)

User Flags
Flags 00 through 35 and 81 through 99 are user flags; they may be set,
cleared, and tested.

General Purpose Flags. Generalpurpose flags (flags 00 through 10


and 81 through 99) are not used internally by the calculator; what they
mean depends entirely on how you define them.,

* The X=Y? and X£Y? functions are exceptions; they can compare Alpha strings.

46 1: Programming
The program LIST on pages 176 through 178 creates a matrix ZLIST
using the following instruction sequence.
31 LBL A2
32 1
33 ENTER
34 FC? 91
25 2
26 DIM “"ELIST"
37 KER I
38 Ry
39 R+
48 GTO 84

Before you execute LIST, you set flag 01 if you want ELIST to be a 1-
column matrix, or you clear flag 01 if you want ZLIST to be a 2-column
matrix. Flag 01 is defined to have a unique meaning in the program,;its
status determines the number of columnsin the matrix XLIST.
(Rememberthat currentstatus of user flags is maintained by HP-42S
Continuous Memory. This can affect other programsthat use the same
flags.)

Control Flags. Controlflags 11 through 35 have a specific meaning and


are used internally by the calculator. For example,flag 21, the Printer
Enable flag, affects the way the VIEW and AVIEW functions work in
programs. When flag 21 is set in PROFF mode, VIEW and AVIEW mes-
sagesare displayed, and program execution halts. Whenflag 21 is set and
PRONis executed, VIEW and AVIEW messages are printed and pro-
gram execution does not halt. Many programsin this manualthat use
VIEW or AVIEW also set flag 21.

System Flags
System flags 36 through 80 also have a specific meaning for the calculator.
You cannot directly set or clear these flags. However, you can test them.

The following program, MINMAX,searchesfor the maximum or


minimum element of the matrix in the X-register. In line 23,it tests the
status of system flag 77, the Matrix End-Wrap flag, to determine ifthe last
element of the matrix has been checked.

1: Programming 47
MINMAX also uses general purpose flag 09 in line 08 to determine
whetherto search for the maximum or minimum element of the matrix,
Before you execute the program, you set flag 09 to find the maximum ele-
ment, or clear flag 09 to find the minimum element.

(The annotated listing is on pages 152 through 153.)


oA L 61-Bute Pram 3
1 LEL "MIMMAZ"

g2 STO "MIHMAX"
B2 IHDEX "MIMMAR®

a4 RCLEL
B85 GTO B3

Bc LEL 01
87 RCLEL
82 FS? B9
B9 GTO &2
18 XaY?
11 GTO b4
12 GTO B3

12 LBEL B2
4 RLY?
15 GTO a4

& LEL B3
— —_ .
0 0 =g

7 RCLIJ
e RCL ST
-l

EHTER

LEL &4
Po3 o [ P M
=

R+
e

J+
Y

FC? 77
GTO a1
Ja

S END
J
i

48 1: Programming
Error Trapping
When you attempt an improper operation during function execution, the
operation is not executed and an explanatory message is displayed. For
example,if you execute the keystroke sequence

1 [E 2600(x?)
the calculator returns the message Out of Range, and leaves the value
1 x 10*° in the X-register.

If an improper operationis attempted in @ program, the calculator returns


the corresponding message, and program execution halts at the instruction
that caused the error. Consider the following program.
ge € 26-Bute Praom I
B1 LBL “TRAP"
B2 SF 21
863 INPUT "R
B84 K+2
85 STO "v"
ae VIEW "Y"
a7 GTO “TRAP"
ags END

If you execute TRAP and supply the value 1 10% for X, the program
halts at line 03 and the calculator displays the message Qut of Range.
To supply a new value for X, you must restart the program at line 01 (by
pressing “TRAFY). In a short program like TRAP,this method of
recovery from an error presentslittle problem. However, when executing
a program that performs time-consuming calculations, or that has
numerousstops for intermediate data entry,it may be inconvenient to
restart the program at line 01 each time an error occurs.

1: Programming 49
You can enable program execution to continue after an error has occurred
by setting flag 25, the Error Ignore flag. When flag 25 is set:

® One error during program execution is ignored. The instruction that


causes the erroris not performed and program execution continues at
the next instruction.
m The error clears flag 25.

Consider this revision to TRAP.

88 { S8-Bute Pram 2
@l LBL "TRAP"

a2 SF 21
863 SF 25
@4 [HPUT "X
05 ¥+2
Qe FC?C 25
By GTO pBa
B2 STO "y
a3 MIEW "y"
18 GTQ "TRAP"

11 LBL @@
12 CF 21
12 EBEEFP
14 "0Qut of Range"
15 AVIEW
16 PSE
17 PSE
12 GTO "TRAF"

1% EHD

TRAP now responds to the error condition by:

m Displaying an error message.


m Resetting flag 25 and prompting for a new value for X.

This programming technique, called error trapping, adds program steps,


but is effective when you can identify operations in a program that are
likely to generate errors.

50 1: Programming
A Summary Program
flags 00
The program FCATin this section displays the currentstatus of
ow menu in sets of six.
through 99. The flags are displayed in a multir
a flag number . You can set and
Each of the menu keysis labeled with
lag 25) and 81 throug h 99 by press-
clear user flags 00 through 35 (exceptf
"u" charact er is append ed to the
ing the corresponding menu key. The
a
menu labelif that flag is currently set. When you attempt to set or clear
system flag, FCAT beeps and display s the error messag e Restr icted
menu
Dperat ion. The previous set of six flags is displayed by pressing
key 7 ([a]), and the succeeding set is display ed by pressin g menu key 8
(V).
FCAT uses many of the programming concepts discussed in this chapter:
# Global and local labeling.
® Prompting for data input.
w Conditional branching based on:
= Numbertests.
m Flag tests.
Subroutines.
Multirow menus.
Counter-controlled looping.
Indirect addressing.
Error trapping.

1: Programming 51
Here is a flowchart for FCAT.

O
INITIALIZE

BUILD A MENU
OF SIX FLAGS

v
KEYS 1 THRU 6 KEY 7 KEY 8
(PAGE UP) (PAGE DOWN)

SET ERROR INCREMENT


IGNORE FLAG COUNTER BY 6

TOGGLE FLAG
Y
DECREMENT
COUNTER BY 6 RESET
COUNTERTO 0
YES
ERROR ?

*RESTRICTED
OPERATION"
MESSAGE
RESET
COUNTER TO 96

52 1: Programming
Here is the annotated listing.

Program: Comments:

B8 { 234-Byte Pram 2
@l LBL "FCAT"

B2 9.89686 Lines 02-03: Store the loop counter


@3 STO 8O inRg.
B4 LBL A Lines 4-17: Build menu keys 1-6.
BS RCL 60 The labelfor each menu keyis built by
Be KEQ BB calling subroutine 00. (Now go to sub-
B7 KEY 1 GTO 61 routine 00.)
a2 XEQ 66
89 KEY 2 GTO ez
18 ¥EQ 8a
11 KEY 38 GTO B3
12 REG 04
12 KEY 4 GTO 84
14 KEGQ 0@
15 KEY 5 GTO 83
16 XEQ B
17 KEY & GTO 8¢

12 KEY 7 GTO @7 Lines 18- 19: Assign GTO instructions


19 KEY & GTO 88 to menu keys 7 and 8.

28 "FLAG CATALOG" Lines 20 -25: Build the Alpha string


21 MEHU FLAG CATALOG (line 20). Display
22 6 the menu (line 21). Initialize register
23 5T0 @1 Ry, to 6 (lines 22—23). Display the
24 PROMPT Alpharegister, suspend program exe-
25 GTO A cution, and prompt for numeric input
(line 24).

1: Programming s3
LEL a8 Subroutine 00, lines 26-37; Build the
~J T B 0 Y= @D 0~
G0 0y (0 0 ) ) N M

CLA Alphastring for each menu key. First,


99.1 test to see if the current value in the
RS>y X-register (the loop counter)is
wrY? greater than 99 (lines 28-31), If yes,
RTH do not build a label for the menu key.
AIF (The highest numbered flag is 99.) If
FS? IND ST ¥ no, append the (integer portion of) the
value in the X-register to the Alpha
'_ll. n

1 register (line 32). Test the status of


+
the flag whose numberis in the X-
RTH register. If that flag is set, append the
"u" characterto the Alpha register
(lines 33~-34). (Thus, the Alpha label
for each menu key consists of a
number, and,if the corresponding flag
is set, a "u".) Increment the value of
the X-register by 1 (lines 35-36).
38 LBL a1 Lines 38 - 52 establish the flag to be
39 DSE a1 set or cleared: Successively decrement
40 LEL az Rg, by 1 (lines 38-49). (If menu key 1
41 DSE o1 is pressed, the value in Ry, is 0 when
42 LEL a3 Ry, is recalled to the X-registerin line
DsSE 01 51. If menu key 6 is pressed, the value
44 LEL 04 in Ry, is S when Ry, is recalled to the
45 DSE ai X-register.) Add the current value in
46 LEL a5 Ry (the counter) to the current value
47 DSE 21 in the X-register (line 52). (The value
48 LBL a6 in the X-registerafter execution of
49 DSE a1 line 52 is the value of the flag to be set
50 LEL 14 or cleared.)
51 RCL a1
52 RCL+ B8&

1: Programming
53 SF 23 Lines 53— 56 build the set/clear toggle
54 FC?C IND ST X and errortrap: Set the Error Ignore
55 GTO 89 flag (line 53). Test if the flag (whose
56 GTO A number value is in X) is clear, then
clear it (line 54). If the flag was clear
when tested in line 54, or the attempt
to clear causes a Restricted Operation
error, go to label 09 (line 55). If the
flag wasset, and the clear operation
does not cause a Restricted Operation
error, return to the menu-label rou-
tine to update theflag status (line 56).

57 LBL @9 Lines 57-61: If the branch to label 09


58 FC?C 25 was caused by a Restricted Operation
59 GTO 1@ error, go to label 10 (lines 57-59). 1If
69 SF IND ST X the branch to subroutine 09 was exe-
61 GTO A cuted because the flag was clear, then
set it, and return to the menu-label
routine to update the flag status (lines
60-61).

62 LBL o7 Lines 62—69: Decrement R by 6.


63 RCL 89 (Thus, when [¥] is pressed, the top-
€4 & row menu keys are each relabeled
65 with the number thatis six less than in
66 ®<@|? the previous menu. If Rog has the
&7 96.089605 value 12 when [¥] is pressed, R takes
68 STO B0 the value 6, and the menu keys are
69 GTO A relabeled 6-11.) Testif the new value
of Ry is less than 0. Ifyes,store 96 in
R (lines 66— 68). (Menu keys 1-4
will be labeled 96-99.)

1: Programming 55
’e LeL B8 Lines 70~ 73: Increment R o by 6 using
71 ISG 06 the ISG function. (Remember that the
ra GTO A number in R, is the loop counter; it
73 GTO "FCAT" has theinitial value 0.09906. When (&)
is pressed, the top row menu keys are
each relabeled with the numberthat is
six greater than in the previous menu,
When the countertest value exceeds
96, program executiontransfers to
FCAT,restoring the counter to its ini-
tial value; the menu keys are thus rela-
beled 0-5.)
74 LBL 18 Lines 74 -89: Execute the BEEP func-
7S FsS?C 21 tion, display the Alpha message
7E GTO 11 Restricted Operation, and
7 XE@ 12 transfer program execution back to
e GTO A label A.If flag 21 is set, clear it before
79 LBL 11 displaying the Alpha message, then
88 REQ 12 reset it. (Program execution continues,
81 SF 21 redisplaying the flag menu, and the
82 GTO A status offlag 21 is maintained.)
83 LBL 12
84 BEEP
g5 "Restricted "
26 F'Operation”
ar RAYIEHW
88 PSE
89 RTH

98 EMHD

1: Programming
Example: The Flag Catalog Program. Use FCAT to set flag 01.
Check the statusofflag 38. Attemptto set or clear it.

Start FCAT.

FLAG CATALOG
Lo2234]5§

Set flag 01.


|FLFIG CATALOG |
o1o2345

Check the status offlag 38.


MMM FLAG CATALOG
¥M |m:fl:lmmm|

Flag 38 is clear. Attemptto setit.


28 IFLFIG CATALOG I
363738394omN1

The calculator beeps, displays the message Restricted Operation,


and returnsto the state before the error. Exit from FCAT.
EXIT v: 42,0961
x: 6. 8000

1: Programming 57
The Triangle Solutions Program

This section contains the complete set of equations for the triangle solu-
tions,instructions for keying in TRIX., an annotated listing of TRI XA, and
instructions for using TRIX .

A4

Ag Az

Program Equations. The following equations are used in the program:

® Condition 1: S, S, and S(three sides) are known:

VP(P -5S3) ] _ +sz+s


(8 3)
Ag = 2 arc cos
° [
(5,53)
Ay = 2 arccos [
m]
(S253)
A, = arccos[ -cos (Ag + A3)]

58 1: Programming
@ Condition 2: S;, 2, and A3 (two sides and the adjacent angle) are
known:

| 1S2] .
Ag = arcsin == sinA4,|*
Sy

A, = arccos [ -cos (Az + A3)]

The problem has been reduced to the A3, 5,4, configuration.


m Condition 3: 43, S, , and A, (two angles and the included side) are
known:
A, =arccos | -cos (A3 +A4;)]

S S SinA3

S e
S3=S8,¢c084; + SycosA,

m Condition 4: S, A4,, and A, (one side and the following two angles)
are known:

Ag = arccos [ -cos (4, + A2)]

The problem has been reduced to the A3, S, 4, configuration.


m Condition 5: S, S5 (two sides and the included angle) are known:

Sa= VS12 +522 - 2SISQCOSA1

The problem has been reduced to the Sy, S, S5 configuration.


m For any triangle, the area is:

AREA = %sls3 sinA,

* Two possible solutions exist if §, is greater than S, and A, does not equal 90°. Both
possible answersets are calculated.

1: Programming 59
To key in TRIX :

1. Create variables S1, 52, §3, 41, A2, A3, P, and AREA before pro-
gram entry.
2. Create labels RESULTS and SSASUB when you begin program
entry.

Here is an annotated listing of TRI X,

Program: Comments:
08 { 573~Bute Pram 2}
81 LBL "TRI&"

82 SF 21

a3 "sss* Lines 03-12: Build the menu key


B4 KEY 1 XEQ@ A assignments,
B3 "SSA"
65 KEY 2 XEQ B
a7y "ASA"
B3 KEY 3 XEQ@ C
@3 "SAR"
19 KEY 4 XKEQ D
11 "gAs"
12 KEY 5 XEQ E

13 MENU Lines 13~-16: Display the menu keys.


14 STOP
15 KEG "RESULTS™
1 GTO "TRIg"

17 LBL A Subroutine A,lines 17-59: Calculate


18 INPUT "sS1v the SSS solution.
19 INPUT *g2"
28 INPUT "S3v
21 RCL "31"
22 REL+ g2
23 RCL+ "53"
24 Z
25+

60 1: Programming
26 STO " P "

27 Rr2
28 LASTX
29 RCLx "S2"
30
31 RCL "S1"
32 RCLx "S53"
33
34 SART
35 ACOS
36 2
37 X
38 STO "A3"
39 SIN
49 RCLx *S1"
41 STO @@
42 rRCL "P"
43 Rr2
44 LASTH
45 RCLx "S1*
46
47 RCL+ "“"s2"
48 RCL+ "&3"
49 SERT
58 ACOS
51 2
52 %
53 STO "A2"
54 RCL+ "A3"
S5 cos
56 4
57 ACOS
S8 5TO "AL"
59 RTH
68 LEL B Subroutine B,lines 60— 100: Calculate
&1 INFUT "&1" the SSA solution.
&2 INFUT “52"
63 INPUT "A2"

1: Programming 61
64 SIN
65 RCLx "g2"
66 RCL+ "St*
67 RSIN
68 STO "A3"
69 SIN
78 RCLx "si*®
71 STO 0@
72 XKER "SSAsSUB"
73 RCL "S1*
74 RCL "s2"
7S RLY?
76 RTH
77 XEQ “RESULTS"
78 RCL "A3"
79 COs
88 +-~
81 ACOS
82 STO “A3"
83 XEQ "SSAsSUB"
84 RTN
85 LBL “SsAsus*
86 RCL "RA3"
8¢ RCL+ "R2"
88 COs
89 +/~
968 ACOS
21 STO "A1"
92 RCL "“RA2"
93 CO0S
94 RCLx "g2"
95 RCL "A3"
96 COS
97 RCLx "siv
98 +
99 STO "S3"
188 RTH

62 1: Programming
181 LBL C Subroutine C, lines 101 —126: Calcu-
162 IMFUT "Az" late the ASA solution.
162 IHPUT "3S1"
184 IWFPUT "AL1"
185 RCL "R
186 RCL+ "ALY
1897 COS
188 +--
199 ACOS
116 STO "R2"
111 RCL "A3"
112 RCL "S51"
112 »REC
114 RH4xY
115 =TO S8

121 S0 "s2"
122 Rr
124 +
125 STO 53
126 RTH

127 LBEL D Subroutine D, lines 127-150: Calcu-


122 IMPUT "5t late the SAA solution.
129 INFUT “AL"
128 IHPUT "A2"
131 RCL+ "R1v
132 COs
133 +o-
134 RCOS
135 570 "Rav
126 RCL "S1

1: Programming 63
*REC
RE>Y
STO an
RCL "AZ"

1
*REC
R+

STOQ g2

R+
X
+

sTO "s3v
RTH

LEL E Subroutine E, lines 151-194: Calcu-


IHFUT "51 late the SAS solution.
IMFUT "R1"
INFUT "gzv
RDL "Hln
S
Ay
7 SREC
: RCL "S1v
0 »POL
STO noon

2 RCL+ "Slu

REL+ "SEH
3
el

" F. "
o o

b
=
-)

LASTH
e

"2
e e e
a 03 fa3 e o

RCL»
=) ]

"St®
=g =g oy

RCL

F' E:L}:: " E;E: n


e

SHRET
-

1: Programming
173 ACOS
ive 2
177 x
178 STO "A3"
179 SIN
186 RCLx "S1*
181 STO 99
182 rRCL "P"
183 xr2
124 LASTX
185 RCLx "51"
186
187 RCL+ "s2"
188 RCL+ "83"
189 SERT
198 ACOS
191 2
192 X
193 STO "R2"
194 RTH

193 LBL "RESULTS" Subroutine RESULTS,lines 195-208:


196 RCL 69 Calculate AREA anddisplay the initial
197 RCLx "gS3" known values and the results.
1938 2
199
2608 STO "ARER"
281 VIEW "51™
202 VIEW "A1"
2e32 VIEW "s2¢
284 VIEW "R2"
289 VIEW "3
286 VYIEW "“R3"
287 VIEW "RARER"
2838 RTH

283 EMD

1: Programming
To use TRIX :

1. Press TRI&.
2. Select a solution by pressing the corresponding menu key.
3. Input values as prompted. You can name any side §,. A, is the
adjacent angle. You can enter valuesin a clockwise or counterclock-
wise order. The values are displayed in the same orderas they were
entered.

66 1: Programming
2
Enhancing HP-41 Programs
In chapter 11 of your owner’s manual, you keyed in and executed a pro-
gram originally written for the HP-41 calculator. That program, named
QUAD, solves for (real number) roots of quadratic equations. Two pro-
grams Q2 and Q3 in this chapter use HP-42S features and functions to
enhance QUAD.A third program QSHORT uses only 11 linesto solve
for quadratic equation roots.

Using Named Variables


In the HP-42S, data may be stored in and recalled from data storage
registers or named variables. Programs that use named variables for data
storage and recall can be easier to write and read.

In QUAD,the values of coefficients a, b, and ¢ are stored in and recalled


from data storage registers. In Q2 these values are stored in and recalled
from named variables a, b, and c. (Q2 also storesthe values of the two
roots 7, and 7, in named variables R1 and R2. In QUAD, these values are
calculated and displayed, but not saved.)

2: Enhancing HP-41 Programs 67


Using HP-42S Data Input and Output
Functions

Prompting for Data with INPUT

The HP-42S INPUT function enables programs to prompt for data in one
program line.

QUAD promptsfor the value of &, then stores the value 2a in a data
storage register with the three-instruction sequence
n a='? 1
oo
Fh 0 R

: PROMPT
5 STO 88
Q2 uses INPUT (and the named variable @) to replace these three
instructions with one.

a2 INFUT "a*

Displaying Data with VIEW

The HP-42S VIEW function enables programs to display data in one pro-
gram line.

QUAD displaysthe labeled value of r, with the three-instruction


sequence

29 “ROOTS="
38 ARCL ¥
31 AYIEM
Q2 uses VIEW (and the named variable R1) to replace these three
instructions with one.

22 VIEW "R1I™

68 2: Enhancing HP-41 Programs


Operations with HP-42S Data Types
Programs written for the HP-41 calculators can operate on only two data
types: real numbers and Alphastrings. Programsfor the HP-42S, how-
ever, can also operate on complex numbers and matrices.

In QUAD, complex-number roots cannot be calculated; instead, if the


value b2 - 4ac is less than 0, the calculation is halted and the message
ROOTS COMPLEX is displayed. In Q2, complex number roots are calcu-
lated,stored in variables, and displayed.

Using the Two-Line Display


Programs can effectively show longer messagesin the HP-42S two-line
display. In Q2, the two-line message

Zero Input Invalid.


Fress R-5 to continue.

is displayed if 0 is supplied for variables a or c.

To key in Q2: Create variables q,b, ¢, R1, and R2 before program


entry.

Here is an annotatedlisting of Q2.

Program: Comments:
80 { 132~Bute Pram I Lines 01— 05: Display the 0-input error
81 LEL a8 message.
gz "Zero Input Inwa"
B2 F"lid.%Fress R~s3"
B4 +" to continue."
85 PROMPT

2: Enhancing HP-41 Programs 69


as LEL "n2¢ Lines 06— 15: Set the program to cal-
a7 CPXRES culate complex numbers, promptfor
az SF 21 the values of a, b, and ¢, and test if 0 is
a9 IMPUT "a" supplied for a or c. (Flag 21 is set in
16 =7 line 08 so that VIEW results are
11 GTO &4 displayed in PROFF mode, or printed
<
IMPUT "B" if PRON has been executed.)
12 INPUT "c"
n=a7
GTO @
RI::L "tl"
Lines 16 —24: Calculate
+=
12 ENTER Vb2 - 4ac
w2
4
1 RCLx "a"
RCLx "ot
SRRT

RCL "b" Lines 25-31: Calculate either


Oy W P P [l T2 Tx]
- @ oo =) n

SIGH
-b + Vb2 - 4qc
2a
or
-b - Vb? - 4dac
2a

depending on the sign of b. Lines 25—


27 ensure that the root that has the
greatest absolute valueis calculated
first. This improves the accuracy of
the results.
STO “RiM Lines 32-33: Store the calculated
Ly
WM

VYIEW "R1" value in R1 and display R1.

70 2: Enhancing HP-41 Programs


34 RCL "c" Lines 34-38: Calculate the second
25 RCL+ "a" root,store the value in R2, and display
36 RCL+ “R1" R2*
37 STO "R2"
33 VIEW "R2"

39 GTO "Q2" Line 39: Return program execution to


label Q2.

48 END

Using Menu Variables


Q2 uses the INPUT function to prompt for the values of the program
variables @, b, and c. Q3 uses a variable menu to prompt for these values.
The corresponding program lines are highlighted in the following anno-
tated listing,

The quadratic gguation ax? + bx + ¢ = 0 can be divided by a (since a cannot equal 0)


yielding x2 + = + % = 0 . This equation can be factored as (x - R,)(x - R) where
R; and R, are the roots of the equation. By definition of the factoring process,
RYRY = % Therefore, R, = @
1

2: Enhancing HP-41 Programs 71


To key in Q3: Create variables g, b, ¢, R1, and R2 before program
entry.

Program: Comments:
ae { 143-Bute Prgm ?
o1 LBL 90
a2 "Zero Input Inva"
a3 F"lid.%“Press RsS"
a4 F" to contirnue."
a5 FPROMPT

ag LEL "@3" Lines 06— 13: Declare menu variables


b7 MVYAR "a" a, b, and c,set the program to calcu-
a8 MYAR "b" late complex numbers, set flag 21, and
@9 MVYAR "c" display the variable menu.
18 CPXRES
11 SF 21
12 VARMEHU "Q3"
13 STOP

14 RCL "a"
15 X=@7
16 GTO a0
1v RCL "c"
18 K=07
12 GTO &

28 RCL "b"
+/-
P PO MY T3 P D) M M
=) o R WM —-

EMTER
®+2
4
RCLX "a"
FCLx "e*

SORT
E‘I::L Ilbll
03 03
= I O

SIGH
®

2: Enhancing HP-41 Programs


a2 -
33 2
24 =
a5 RCL+ "a"
26 STO “"R1"
37 VIEW "R1"
33 RCL "c
39 RCL+ "a"
48 RCL+ "R1"
41 STO “"R2"
2 VIEW "RZ"
43 GTO "@s"
44 EHD

Assigning a Program to the CUSTOM Menu


When you created the globallabel Q3 in program line 06, that label was
automatically placed in the HP-42S program catalog. You can now exe-
cute Q3 by pressing

oz

(requiring a minimum of two keystrokes, depending on where label


. B2 is in the program catalog).

Alternately, you can assign Q3 to the CUSTOM menu by pressing

BEASSIGN] FGH - 03
then selecting the desired row of the menu and pressing the desired menu
key in that row. The program now can be executed directly from the
CUSTOM menu with one keystroke.

2: Enhancing HP-41 Programs 73


Example: Executing an Enhanced HP-41 Program from the
CUSTOM Menu.

Part 1. Execute Q3 from the CUSTOM menuto find the roots of the
equation

x2+6x +1=0(a =1,b =6,c =1)

Assign Q3 to the CUSTOM menu using the keystroke sequence just


described. If you wantto print the results, execute PRON.Start the pro-
gram from the CUSTOM menu.
(BPRINT) (&) : POH:) x: B. 0000
WCUSTOM 03 ONTO——
Enter the values for a, b, and c. Then calculate R1. (If you are printing the
results, you won’t see this display.)
R1=-5.8284
@ =2~
OomD>

Leo & C[[|

R1is calculated and displayed. Now check R2.


5

R2=-8.1716
TN NNN.

Return to the start of the program for new data.


% -0, 1716
Innn--—l

74 2: Enhancing HP-41 Programs


Part 2. Find the complex roots of the equation
2x2+x +3=0(a =2,b =1,¢c =3)

Set the angular mode to Rectangular. Enter the values for a, b, and c.
Then calculate R1. (If you are printing the results, you won’t see this
display.)
RECT R1=-8.2500 -il.1990

1. E

R1 is calculated and displayed. Now check R2.


R2=-8.2508 i1.1990
w1&§¢[[1

Exit from Q3.


EXIT v: -9.2500 -i1.1990
x: -8,25008 i1.1990

A Short Quadratic Program. In conclusion,here is an 11-line, 26-


byte quadratic equation solver.
88 { 26-Byte Pram >
81 LBL "RSHORT"

82 -a.5
B3 x
84 ENTER
85 ENTER
Qe ¥r2
a7 RCL- ST T
83 SORT
89 STO+ ST 2
18 -

11 EMD

2: Enhancing HP-41 Programs 75


To use QSHORT:

1. Setthe calculator to Rectangular mode and to Complex Results


mode.
2. Key in the value i— , then press [ENTER].

3. Key in the value % .

4. Press ‘SHO.

' 76 2: Enhancing HP-41 Programs


The Solver
The material in this chapter builds on concepts introduced to you in
chapter 12 of your owner’s manual.

The following topics are covered:

a Basic use of the Solver.


m Providing initial guesses for the Solver.
= Emulating the Solver.
m Using the Solver in programs.
® More on how the Solver works.

Basic Use of the Solver


The general procedure for executing the Solveris:
1. Create a program that:
a. Uses MVARto define the variable(s) in the equation.
b. Expresses the equation such that its right side equals 0. (Note
that each variable in the equation must be recalled to the X-
register.)
2. Apply the Solver to the program:
a. Press B(SOLVER).
b. Select the program by pressing the corresponding menu key.
c. Enter the value for each known variable by keying in the
value,then pressing the corresponding menu key.
d. Optional: Supply one or two guessesfor the unknown variable
by keying in the guess(es), then pressing the corresponding
menu key.

3: The Solver 7
e. Find the value of the unknown variable by pressing the
corresponding menu key.

Example: Basic Use of the Solver. The equation ofstate for an


ideal gas is

PV =nRT

where:

P is the pressure of the gas (in atmospheres).


Vis the volume of the gas (in liters).
n is the weight of the gas (in moles).
R is the universal gas constant (0.082057 liter-atmosphere/Kelvin-mole).
T is the temperature of the gas (in Kelvins).

Part 1. Create a program for the Solver that declares the variables and
expresses the equation.

First, set the right side of the equation equal to 0.

PV -nRT =0
Now write the program.

Program: Comments:
@3 { 42-Bute Pram X
@1 LEL "GAS"
Bz MVWAR "P" Lines 02 ~-05: Declare the variables.
BE: r.1 I'"IHE n I.‘.I n

B4 MYAR "n"
85 MYAR "T"
A& RCL “"P" Lines 06— 12: Express the equation
BF RCLx "y such thatits right side equals 0.
83 BCL "m"
83 RCLx “T"
18 @.822857
11 =
12 -

12 EHD

78 3: The Solver
Part 2. Use the Solverto find the solution to the following problem.

Calculate the pressure exerted by .305 mole of oxygen in .950 liter at


150 °C (423 K), assuming ideal gas behavior.

Select the Solver application.


[SOLVER] Select Solve Program
u |m—---—|

Select the program you just created.


GRS x: B.0000
I A

Enter the values for the variables you know.


95 g T=423, 0000
305 H teoI~ v[ |

423 .1

Solve for the pressure.


kB P=11.1438
ev |

Part 3. Given the same volume and weight of oxygen, what is the tem-
perature of the gas at a pressure of 15 atmospheres?

Since the values of the volume and weight are unchanged, you need only
enter the value of the pressure.

5. P=15. 0000
D W T S A

Now solve for the temperature.


B T=56%.3763
(2 ST OO TO

Exit from the Solver application.


y: 963
X:
Providing Initial Guesses for the Solver
For certain functions,it helps to provide one or two initial guesses for the
unknown variable. This can speed up the calculation, direct the Solver to a
realistic solution, and find more than one solution, if appropriate.

Directing the Solver to a Realistic Solution


Often, the Solver equation that describes a system may have solution(s)
that are mathematically valid but that do not have physical significance.
In these cases, it may be necessary to direct the Solver to the realistic
solution by providing appropriate initial guesses.

Example: Directing the Solver to a Realistic Solution. The


volume of the frustum of a right circular cone is found by

V= %xh(a’ +ab +b?)


where:

V is the volume of the frustum.


h is the height of the frustum,
a is the radius at the top ofthe frustum.
b is the radius at the base of the frustum.

80 3: The Solver
Part 1. Write a Solver program that declares the variables and expresses
the equation suchthatits right side equals 0.
68 { 45-Byte Pram
B1 LBL "COHE"

g2 MVAR "v"
83 MVYAR "h"
B84 MYAR "a"
85 MVYAR "b"

g6 RCL "a"
a7y ®+2
88 LASTH
B89 RCLx "b"
18 +
11 RCL "b"
12 ¥+2
13 +
14 RCLx "h"
15 PI
16 %
17 3
18 =
19 RCL- "y

28 END

For the purposes of this example, assume that you have already created
variable ¢ and used it in a previous program. Assume that the value
-3.7765 is currently stored in a (Go ahead now andstorethat value in ¢
by pressing 3.7765

3: The Solver 81
Part 2. For a frustum of volume V' = 119.381 meters®, height 4 = 6
meters, and radius b at the base of the cone = 3 meters, use the Solver
to
find radius a .

Select the Solver application and then program CONE.

B(SOLVER] [CONE x: -3. 7765


T
Enter the values for the known variables.
119.381 b=3. 9
.

a=-3.0000
IINA

The Solver uses the current value ofvariable @ (-3.7765) as an initial


guess and findsthe solution @ = -5 meters. The answeris mathematically
valid. However, a negative radius clearly has no physical significance. Try
guesses of 0 and 5.
0' ..a |a=2. vevY I

The value 2.0000 meters for radius @ is mathematically valid and has phy-
sical significance.

Exit from the Solver.


EXIT] [EXIT
X<
-

82 3: The Solver
Finding More Than One Solution
The equation of motion for an object experiencing constant acceleration
due to gravity is

Y =Yo+vol + %8‘2

where:

y is the total displacement.


Yo is the initial position.
v, is the initial velocity.
g is the acceleration due to gravity ( -9.8 meters/second?).
t is the time.

In your owner’s manual in section "More Solver Examples" in chapter 12,


you solved several problems in which an object was dropped from an ini-
tial position; v, was equal to 0 and the direction of the object’s motion was
down at all times. The object attained a given displacementy at only one
time ¢. However, an object thrown upwards attainsa given displacement y
at two different times —once on the way up, and again on the way down.

3: The Solver 83
To find both times ¢, and ¢, you must execute the Solver twice, and at
least once provide the Solver with an initial guess to directit to the second
solution.

Example: Using the Solver to Find Two Real Solutions. A boy


throws a ball with an initial vertical velocity v, = 15 meters/second, from
an initial height y, = 2 meters. Use the Solverto find the two times ¢, and
t2 when the ball has a height y = 5 meters.

Part 1. Create a Solver program that declares the variables and expresses
the equation such thatits right side equals 0.
a8 { 353-Bute Pram 2
81 LBL "MOTION"

a2 MYAR "y"
83 MYAR "yB"
a4 MVYAR "va"
B85 MVARA "t

as RCL "QB"

ar RCL "v@"
ag RCLX lltll

a9 RCL Iltll

18 K2
11 -2.8
12 *®
13 2
14
15 +

1e +

17 RCL_ Ilgll

1a EMD

84 3: The Solver
Part 2. Exccute the Solver to find the first time ¢; . Since you know that
this time is close to 0 seconds, provideinitial guesses of 0 and 1.

Select the Solver application and then program MOTION.


SOLVER] MOTI0
B(SOLVER] MOTI( : 0, 0000 i

Enter the values for the known variables.


Vo=15. BP0
CvTwoTwa1|

Solve for time ¢, using initial guesses of 0 and 1.


t=0.2151
ITV TNAI

The Solver finds the value of ¢, = 0.2151 seconds. Now find the second
time ¢, by providing two initial guesses that you can expect to bound the
second solution. Guesses of 1 and 20 seem reasonable. (You need not
enter values for the other variables since they have not changed.)
=2.8461
v [weooT1|

The Solverfinds the value of £, = 2.8461 seconds.

Exit from the Solver.


EXIT] [EXIT

3: The Solver 85
Emulating the Solver in a Program
For certain types of functions, the Solver algorithm cannotfind solutions.
For example, the Solver cannotsolve for complex numbers. However, for
such functions, you can write a program that finds explicit solutions and
acts like the Solver during program execution.

First, consider the following simple circuit.

R
m

Ohm’s law definesthe relationship between the voltage potential E, resis-


tance R, andcurrent / for this circuit as

E=1IR

Since there are no complex termsin this equation, the Solver can be used
to find the value of any variable in the equation.

86 3: The Solver
t. For
Example: Using the Solver for a Simple Resistive Circui
the
a simple resistive circuit, use the Solver to find the resistance R when
voltage E = 10 V, and the current I=5A.
es
First, create a Solver program that declares the variables and express
the Ohm’s law equation such thatits right side equals 0.
@p { 29-Byte Pram 2
@1 LBL "CIRCUIT"

82 MVAR "E"
63 MVAR "I"
@4 MVAR "R"

8s RCL "1
@6 RCLx "R"
8?7 RCL- "E"

B8 EMD

Select the Solver application and then program CIRCUIT.


E(SOLVER] 4 %: 8, 0000
STSNN

Enter the known values for E and I, then solve for R.


R=2.0000
NTTNO.

Exit from the Solver application.


v: 2.0000
x: 2,0800

3: The Solver 87
Now consider the following circuit.

W

Application of Ohm’s law to this circuit resultsin the following expression.

E=1Z

where:

E is the circuit voltage.


I is the circuit current.
Z is the circuit impedance.

The impedance Z is the complex number(in rectangular form)

R - [—1]
wC

where:

R is the circuit resistance.


w is the circuit frequency (in radians/second).
C is thecircuit capacitance.

Because the voltage, current, and impedance are complex numbers, you
cannot use the Solverto find their values. However, the HP-42S can per-
form grithmetic operations on complex numbers. (Refer to chapter 6 in
your owner’s manual for a discussion of complex-number arithmetic.) The
following program, EIZ, solves explicitly (algebraically) for the complex
numbers E, I, and Z, and uses a variable menu to simulate the external
appearance of the Solver. (Referto the section "Using a Variable Menu"
in chapter 9 of your owner’s manual for a discussion ofvariable menus.)

88 3: The Solver
Here is an annotated listing of the program.

Program: Comments:

8o { 96-Byte Prom
a1 LBL "EIZ2"

a2 MVAR “E<" Lines 02-05: Declare variables E, I,


a3 MvAR "IL" and Z and build the variable menu.
a4 MYAR "2«
as VARMENU “"EIZ"

a6 FOLAR Lines 06— 12: Set the calculator to


av CPHXRES Polar mode and to calculate complex
a3 CLA results. Suspend program execution
@9 STOP for data entry.If a variable to solve for
18 ALENG has not been specified, return to the
11 K=07? start of the program.
12 GTO "EIZ®

13 ASTO ST A Lines 13—17: Recall the current Alpha


14 YER IND ST = string to the X-register and execute
15 STO IHD ST ¥ the corresponding subroutine. (The
16 YIEW IHD ST ¥ current Alpha string is the name of
17 GTO “EIZ" the variable for which no valueis sup-
plied.) Store the calculated result from
the subroutine in the Y-register and
view the result. Then return to the
start of the program.

ig LBL "E4£" Subroutine E 4., lines 18 —21: Calcu-


12 RCL "I&" late EX. in terms of /.4 and RA..
28 RELx “Z4"
21 RTH

LEL "I Subroutine 1., lines 22-25: Calcu-


RCL "E<" late IX in terms of EA and ZX&..
RCL+ 24"
-
= RTH

3: The Solver 89
26 LBL "24" Subroutine Z 4., lines 26 -29: Calcu-
27 RCL "Eg" late Z& interms of EX and IX.,
28 RCL+ "Ix"
29 RTN

38 END

(Line 06 setsthe calculator to Polar mode. Multimeterstypically display


complex voltage, current, and impedance values in polar form,that is,as a
magnitude and phase angle.)

Example: Calculating Complex Values In an RC Circuit. A


10-volt powersupply at phase angle 0° drives an RC circuit at a frequency
of 40 radians per second. A current of .37 A at phase angle 68° is meas-
ured. Whatis the resistance ofthe circuit? Whatis the capacitance of the
circuit?

Begin program EIZ,

|><: B.bopo I
SWNNN

Enter the known value for the voltage.


10 [ENTER) 0 lI[COMPLEX E<=10.0000 <£8.0000
LEs[14Jas[[[]

Enter the known value for the current.


.37 [ENTER) 68 I[COMPLEX I1£=0.3700 £68.9800
LEs14fad[[|

Solvefor the impedance.


2£=27.0270 £-68.0000
LEs[0Jaaf[|
The impedance ofthe circuit (in polar form) is 27 {1 at phase angle —68°.
Convert the impedance to rectangular form to find the circuit resistance
and capacitance. (Remember,R is the real term and C is one factor in the
imaginary term of the rectangular form of the impedance Z)
‘RECT % 10,1245 -125.0990

The circuit resistance is 10 . Now calculate the capacitance.


[COMPLEX] x: @.0010
40 [x) [Eaba [2a[ |

@OPFCN) 1¢x
The circuit capacitance is .001 F.

If, at the original input voltage, the impedance is now varied and measures
20 01 at phase angle —45°, whatis the current?

Return to polar mode. Then enter the new value for the impedance and
solve for the current.

W(MODES) FOLAR 12=0.5000 £45.0000


20 45 Cece [2aT L|
. 24
BCOMPLEX)

The current is 0.5 A at phase angle 45°.

Exit from EIZ.


NP
EXIT
x: 8. 5000 £45.0000

3: The Solver o1
Using the Solver in Programs

Using the Solver and Explicit Solutions in a


Program
The Solver uses an iterative method to find solutions for the variables in
an equation. You must use an iterative method to find the solution for a
variable that cannot be isolated (cannot be expressed uniquely in terms of
the other variables in the equation). However, in cases where the
unknown variable can be isolated by algebraic manipulation, an explicit
solution for that variable is always faster than an iterative solution using
the Solver.

Somefunctions may contain a variable whose value must be found itera-


tively, and other variables whose values can be calculated explicitly. In
your owner’s manual,in the section "More Solver Examples” in chapter
12, you worked an example in which the Solver was used to find the solu-
tions to time-value-of-money (TVM) problems. The TVM equation is

0= -PV + (1 +ip) PMT 1-Q@+i)™


li” _"] +FV (L + i)
where:

N is the number of compounding periods or payments,


i is the decimal form of the periodic interest rate.
PV is the present value. (This can also be an initial cash flow or the
discounted value of a series offuture cash flows.) PV always
occursat the beginning ofthefirst period.
PMTis the periodic payment.
FV is the future value. (This can also be a final cash flow or the
compounded value of a series of cash flows.) It always occurs at
the end N* period.
p is the paymenttiming. Ifp = 1, payments occur at the beginning
of the period. Ifp = 0, payments occur at the end ofthe period.

92 3: The Solver
In the example in your owner’s manual, you wrote a program TVM that
declares each of the TVM variables and expresses the TVM equation.
The Solveris used to find the solution for each of the function variables.
Notice, though,that the variables PV, N, FV, and PMT can each be iso-
lated. For example, PV can be expressed as

PV = -(1+ip) PMT 1-@a+07


li” -N]—FV(1+1')'”

Only the variable i cannot be isolated; you need to use the Solver only
when you want to find the value of i.

The following program, TVM2, calculatesthe solutions to PV, N, FV, and


PMTexplicitly, and calls the Solver to find the solution for i. The pro-
gram uses a programmable menu and flag 22, the Numeric Data Input
flag, to simulate the external appearance of the Solver application.

To key in TVM2: Create variables P/YR, p, CNTRL, N, FV, MODE,


PMT, i, I%YR, and PV.

Here is an annotated listing.

Program: Comments:
88 { 533-Bute Pram ¥
@81 LEBL "Tvmz"

A2 REALRES Lines 02— 15: Ensure results are real


a2 CF 21 numbers. Display AVIEW messages
a4 12 and continue program execution. Call
65 SF 25 subroutine 21 to set the default pay-
@6 RCL “PoyYRY ments per year to 12. Set the default
a7 XER 21 payment mode to End mode.Call sub-
@s SF 25 routine 20 to display the payments per
@3 RCL “p" year and the payment mode.
18 CF 25
11 1
12 B=2¥7?
12 8
14 STO "p*
15 HKEG z8

3: The Solver 93
LBL 99 Lines 16 -35: Build the main menu,
QO 0x D) G Q)WM M M o M N M o —_ s e e
N oF 0 Mo @D 0w =~ o [V I~ O 0N

CLMENU display it, and wait for data input


(lines 17-31). Display the value of the
llhlfl

KEY 1 XEG @1 entered or calculated variable (lines


32-34).
n IZYRII

KEY 2 XERQ 82
H plv! n

KEY 3 XEQ 83
"PMT"
KEY 4 XER B4
"Fll'll "

KEY S XERQ B35


"MODES"
KEY & GTOD @&
MENU
STOP
ASTO "“CHTRL"
STQ IMD “CHTRL®
MIEM IMD "CHTRL™
GTO 99

LEL 28 Subroutine 20, lines 36— 48: Build and


b B £ Lo D) Q) LD
£ M — T W g

CLA display the payments-per-year and


RCL "P~YR" payment-mode message.
AIF
" PoYRY
RCL "p"
K=07?
" EHD MODE"
X=07?
45 +" BEGINH MODE"
46 AVIEMW
47 CLMEHU
43 RTH

94 3: The Solver
49 LEL @6 Lines 49 -62: Build and display the
S50 XER 28 payments-per-year and payment-mode
51
" P/YR LU
menu.
‘52 KEY 1 XE@ 21
23 "BEG"
o4 KEY 2 XEQ 22
S5 "EMD"
56 KEY 3 XER 23
o7 "TVHM"
58 KEY 4 GTO "Tv¥mMz"
59 MENU
&g RCL "Ps¥R"
61 STOP
62 GTO @6

63 LEL 21 Subroutine 21, lines 63 -73: Check if


64 AES the specified number of payments per
€5 IP year is valid. If not, substitute 12 pay-
&5 1806 ments per year.
&7 ROOY
68 Hay?
69 12
74 R=07
7l 12
= STO "PsYR"
3 RTH

74 LBL 22 Subroutine 22, lines 74-77: Set pay-


[= 1 ment mode to Begin by supplying 1 for
76 STO 1 p 1 p.
7 RTH

78 LBL 23 Subroutine 23, lines 78 -81: Set pay-


e a ment mode to End by supplying 0 for
en STD Ilpll p-
81 RTH

3: The Solver 95
82 LBL @1 Subroutine 01, lines 82-107: If
83 IINII numeric input is made for N, return to
84 FS?C 22 the main menu and display the value
85 RTHN of N. If not, calculate N in terms of
86 1 the other variables. If i = 0, go to label
8¢ STO “H" 00 to calculate N (lines 93-95).
88 XEQ 18
89 RCL "Fy"
98 RCL+ "MODE"
91 +/=
92 RCL "PMT"
93 RCL "i"
94 ®=a7
95 GTO o8
26
97 +
28 LASTX
99 RCL "Pv"
108 RCL+ "MODE"
161 +
182
183 LN
184 RCL "i"
1835 LN1+X
106
187 RTH

188 LBL @@ Lines 108 —113: Calculate N if i is 0.


189 RCL “"PY"
110 RCL+ "Fy¥"
111 RCL+ "FMT"
112 +/-
113 RTH

3: The Solver
114 LBL @2 Subroutine 02, lines 114-123: Use the
115 " I:,:YR n
Solverto calculate I%YR. Specify the
116 FS?C 22 Solver subroutine "i". Supply initial
117 RTH guesses of 0 and 20 for I%YR.
118 PGMSLY "i"
1139 8
120 sSTO “IXYR"
121 28
122 SOLVE "IxYR"
123 RTH

124 LBL "i" Subroutine "i", lines 124 -131: Express


125 XEQ 10 the TVM equation for the Solver.
126 RCLX "PMT"
127 ROV
128 RCLx "Fy"
129 +

138 RCL+ "PY"


121 RTHN
132 LBL B3 Subroutine 03, lines 132-142: If
133 "P'I|l|"
numeric input is made for PV, return
134 FS?C 22 to the main menu and display the
135 RTH value of PV. If not, calculate PV in
136 XKER 18 terms of the other variables.
137 RCLx "“PMT"
128 BN
139 RCLX llFl'.'III

148 +

141 +/ -
142 RTH

143 LBEL 84 Subroutine 04, lines 143 —-154: If


144 "PMT" numeric input is made for PMT,
145 FS?C 22 return to the main menu and display
145 ETH the value of PMT. If not, calculate
147 XER 18 PMTin terms of the other variables.
148 Ry

3: The Solver 97
149 RCLx "Fy"
158 RCL+ "PV"
151 XC>Y
152
152 +/-
154 RTN

155 LBL a5 Subroutine 05, lines 155-165: If


156 llFl.',lll
numeric input is made for FV, return
157 FS?C 22 to the main menu and display the
158 RTH value of FV. If not, calculate FV in
153 XEQ 18 terms of the other variables.
166 RCLx "PMT"
161 RCL+ "P¥"
162 ROy
162
164 +/-
163 RTH

166 LEL 18 Subroutine 10, lines 166 — 188: Calcu-


167 RCL "IxwR" late terms of the TVM equation based
168 RCL+ "P-YR" on the value of I%YR. Calculate i; the
169 168 decimal form ofthe periodic interest
178 rate (lines 167 - 171). Calculate
171 sSTO "i" MODE (1 + ip) (lines 172-175).Cal-
ire RCLx "p" culate the FV coefficient (1 +i )™¥
173 1 (lines 176 -182). Calculate the PMT
174 + coefficient. If i = 0, go to line 189
175 STO "MODE" (lines 183 -188).
176 1
177 ENTER
173 RCL+ "i"
172 RCL "H"
188 +-
Y
b
00
oFa 2 P o

STo 5T 2
b
20
ek
0D

RCL= “MODE"
ek
O

SF 25
Pt bk
COO0
T N

F:I:L_:_ n i "

3: The Solver
187 FS?C 25
182 RTHN

189 1 Lines 189-191: If i = 0, then the FV


196 RCL “"H" coefficient is 1 and the PMT
191 EHD coefficient is N.

To use TVM2:

1. Press TUME .
2. Supply values for the known variables. For example, press 60
H
3. Solve for the unknown variable by pressing the corresponding menu
key.
4. TVM?2uses the variable I%YR to prompt for and display the
interest rate. I%YR is the percent form of the annualized interest
rate.

5. The default payment period is one month (12 payments per year).
The default payment timing is the end of each period. To specify a
different payment period or payment timing,first select the MODE
menu. Then, for example,to specify six payments per year, press 6
EoYER

To specify payment timing at the beginning of each period, press


BEG.

To return to the main menu, press “TYH .

Example: Executing Algebraic Solutions for TVM Problems.


In the section "More Solver Examples"in chapter 12 of your owner’s
manual, Penny of Penny’s Accounting wants to calculate the monthly pay-
ment PMT for a 3-year loan financed at a 10.5% annual interest rate,
compounded monthly. The loan amountis $5,750.
In that example, you executed the program TVM to calculate the value
PMT = -186.89. TVM uses the Solverto calculate PMT. Thecalculation
takes about three seconds with initial guesses of 0 and —500.

Part 1. Use TVM2 to calculate the value of PMT explicitly.

3: The Solver 99
Set the displayformat to FIX 2. Then execute TVM2.
12 P/YR END M
-:-m

Enter the known values.

5750 PV FV=0.00
10.5 1%YR IKBTA TNRS
36N
0 F¥

Solve for the payment.


PMT PMT=-186,89
[N_[ivR]PyPHT]Fu_[HOCE]

The explicitly calculated value is —186.89 (the same as when you used
TVM) and the calculation takes less than one second. Also note that the
calculation time is independent of the previously calculated value PMT.
(The Solver interprets the previously calculated value as a guess if two
guesses are not supplied. The explicit solution does not use guesses.)

Part 2. Another bank has offered to loan Penny’s customer $5,750, to be


paid in monthly installments of $200. What interestrate is this bank
charging?
200 - PHMT

TVM uses the Solverto calculate the new interest rate. The Solver uses
the guesses 0 and 20 (supplied by the program) to startits iterative search.
The calculation takes about 11 seconds.

Exit from TVM2 and return the display format to FIX 4.


EXIT 15.
15.2393
BOISP)

100 3: The Solver


Using the SOLVE and PGMSLYV Functions with
Indirect Addresses

In the previous section, you used the SOLVE function in TVM2to find
the value of the interest rate i in the TVM equation:

122 SOLVE "IXYR"

You used the PGMSLYVfunction to specify the routine that expresses the
TVM equation:

118 PGMSLY "i*

In TVM2, the SOLVE and PRGSLYVinstructions directly address the vari-


able and the subroutine. Such use of direct addressing enables you to
specify only one Solver routine and, within that routine, only one variable.
However,the use ofindirect addressing expands the utility of the Solver by
enabling you to specify any of multiple routines, and any of multiple vari-
ables.

Example: Using SOLVE with an Indirect Address. Restating the


ideal gas equation of state:

PV -nRT =0

The "van der Waals" equation ofstate refines the ideal gas equation to

[+ P+ 2w 2
-m)
2 (v -nb)|-nRT =0

where a and b are constants characteristic of the gas in question.

Part 1. Write a program that enables you to solve for the value of any of
the variables using either the ideal gas or van der Waals equation ofstate.

3: The Solver 101


Here is a flowchartfor the program, named GAS?2.

(GAS2)

v
DECLARE MENU
VARIABLES

v
DISPLAY VARIABLE MENU
FOR DATA INPUT
KEY 1 iKEYZ ¢KEY3 iKEY4 ¢KEY5 KEY 6
V llPlI Ivll -nl ITI Ial V Ibl

STORE NAME OF
UNKNOWN VARIABLE
FROM ALPHA REGISTER
TO VARIABLE CONTROL

Y
SPECIFY SOLVER
PROGRAM WAALS

y
SOLVE FOR
UNKNOWN VARIABLE
¢

VIEW SOLUTION
EXPRESS THE
VAN DER WAALS
EQUATION

& v

102 3: The Solver


Here is an annotated listing of the program.

Program: Comments:
88 { 129-Byte Pram
@81 LBL "GRS2"

A2 MYAR “P" Lines 02-08: Build the variable menu.


@2 MYAR "y
a4 MVYAR "n"
a5 MVAR "T"
ac MVYAR "a"
a7 MVAR "b"
82 YARMENU "GRS2"

83 CF 21 Lines 09-16: Clear flag 21 to continue


18 REALRES program execution after a VIEW
11 STOP instruction. Set to calculate real results
12 ASTO "COWTROL" only. Display the menu. Store the
12 PGHMSLY "MWAALS" name of the unknown variable in
14 SOLVE IND "COWTROL" CONTROL (line 12). Specify Solver
15 VYIEW IND “CONTROL®" routine WAALS (line 13). Indirectly
16 GTO "GRASz2" specify the variable to be solved (line
14). View the solution and return to
label GAS2 (lines 15-16).
17 LBL "MWAALS" Lines 17-34, the Solver routine
12 RCL "P*" WAALS: Express the van der Waals
1% RCL "R" cquation such thatits right side equals
28 H+2 0.
21 RCL= "g“
22 RCL e
22 He2
24
25 +
26 RCL "y
27 RCL "n“
28 RCLx "m"
29 -
38 x

3: The Solver 103


31 8.e82857
32 RCLx "n"
33 RCLX “T"
34 -
25 END
Part 2. Use the van der Waals equation of state to calculate the pressure
exerted by 0.250 mole of carbon dioxide in 0.275 liter at 373 K, and com-
parethis value with the value expected for an ideal gas. For CO,,
a = 3.59 liters? - atmosphere/mole?, and b = 0.0427 liter/mole.

Execute GAS2.

GHE2 %: 8. 0000
Ill:lllflllnllllllllnllmlfl

Enter the values for the known variables.

250 H b=0.08427
2750y (PvN¥|E]

359 A
0427 B

Enter guesses of 10 and 30 for P, and solve for P.


10 P P=25.9816
30 P (P[¢[N[T[#]E|
e

Using the van der Waals equation ofstate, the predicted pressure is
25.9816 atmospheres.

Now use the ideal gas equation to predict the pressure. Simply supply the
value 0 for @ and b and solve for P. The previously calculated value for P
serves as an initial guess.
0 H P=27.8248
0. B f » N7 #E]

104 3: The Solver


The ideal gas equation predicts a pressure of 27.8248 atmospheres. (The
actual observed pressureis 26.1 atmospheres.)

Exit from GAS2.

EXIT

More on How the Solver Works

The Root(s) of a Function


To use the Solver, you have learned that you first create a program that
expresses the equation such thatits right side equals 0 (by subtracting the
termson the right side from both sides of the equation). If the equation
has more than one variable, you must,after selecting the Solver applica-
tion, supply values for all but the one unknown variable. At this point,
your equation has taken the form f(x) = 0, where x is the unknown vari-
able, and f(x) is a mathematical shorthand for the function that defines x.
Consider the equation

2x2 +xy + 10 =3xz + 22

Setting the equation equalto 0 by subtracting the termson the right side
from both sides gives

2x2+xy +10-3x2 -2z =0

To use the Solver, you now write a program that declares the variables x,
y, and z and expresses the equation. When you select the Solver applica-
tion and,for example, supply the value 2 for y, and 3 forz, by substitution
the equation becomes

2x2-7x -2=0

where:x is the unknown variable and f(x) = 2x% - 7Tx - 2. Each value x
for which f(x) = 0is called a root of the function. The Solveriteratively

3: The Solver 105


seeks a root forf(x) by evaluating the function repeatedly at estimates of
x, and comparing the results to previous estimates. Using a complex algo-
rithm, the Solver intelligently "predicts” a new estimate of where the graph
off(x) might cross the x-axis. Here is a graph of the function
f(x) = 2x% - 7x — 2. The graph shows two roots. (The example on pages
110-112 calculates these roots.)

f(x)

All except one of the functions in the examples in this section are func-
tions of one variable x only. Remember, though,that the situations
described in the examples apply equally to multivariable functions, since
multivariable functions become single variable functions when, in the
Solver application, you supply values for the known variables.

106 3: The Solver


The Solver’s Ability to Find a Root
For the Solver to find a root, the root has to exist within the range of
numbers of the calculator, and the function must be mathematically
defined where theiterative search occurs. The Solver always finds a root
if one or more of the following conditions is met:

m Two estimates yieldf(x) values with opposite signs, and the function’s
graph crosses the x-axis in at least one place between those estimates
(figure 3-1a).
® f(x) always increases or always decreases as x increases (figure 3-1b).
m The graph off(x) is either concave everywhere or convex everywhere
(figure 3-1c).
= Iff(x) has one or more local minima or maxima, each occurs singly
between adjacent roots off(x) (figure 3-1d).

f(x) f(x)
A A

.
|
"
1
b X e X
)

a - b
f(x) f(x)

Figure 3-1. Functions for Which a Root Can Be Found

3: The Solver 107


In mostsituations, the calculated root is an accurate estimate of the
theoretical, infinitely precise root of the function. An ideal solution is one
for which f(x) exactly equals 0. However, a nonzero value for f(x) is often
also acceptable, because it results from approximating the root with lim-
ited (12-digit) precision.

Interpreting the Results of the Solver


The Solver returns data to the stack registers on completion ofits iterative
search for a root of the specified function, and in four conditions, returns
a message to the display. These messages and data can help you interpret
the results of the search:

m The X-register contains the best guess. This guess may or may not be
a root ofthe function.
m The Y-register contains the previous guess.
s The Z-register contains the value ofthe functionf(x) evaluated at the
best guess.
m The T-register contains a code 0~4 that indicates the Solver’s
interpretation ofits search for a root. (This code is displayed in the
current display mode; in FIX 4, code 0 is displayed as 8.@0880.).

108 3: The Solver


Code in
Interpretation
T-register

0 The Solver has found a root.


1 The Solver has generated a sign Sian Reversal
reversal in f(x) at neighboring
values of x, but f(x) has been
strongly diverging from 0 as x
approaches the two neighbors
from both sides.
The Solver has found an approxi- Extremun
mation to a local minimum or
maximum of the numerical abso-
lute value. If the solution is
+0.999999999999 x 10, it
corresponds to an asymptotic
extremum.
One or both initial guesses lie out- Bad Gues=s(es)
side the domain of f(x). Thatis,
f(x) returns an error when
evaluated at the guess points.
f(x) returns the same value at Constant?
every point evaluated by the
Solver.

When a Root Is Found. There are two cases in which a root is found:

® In case 1,the calculated rootsets f(x) exactly equal to 0 (figure 3-2a).


® In case 2, the calculated root does notset f(x) exactly equalto 0, butis
a 12-digit number adjacent to the place where the function’s graph
crosses the x-axis (figure 3-2b). This occurs when the final two esti-
matesare neighbors (they differ by 1 in the 12th digit) and f(x) is posi-
tive for one estimate and negative for the other. In most cases, f(x)
will be relatively close to 0.

3: The Solver 109


f(x) f(x)

a b

Figure 3-2. Case When A Root Is Found

In bothcases, the code in the T-register is a 0 and no message is


displayed. You can differcntiate between the two cases by:

w Viewing the contents of the Z-register (the value off(x) at the calcu-
lated root). For a case 2 solution,it will be a nonzero number.
m Comparing the best guess (the contents of the X-register) and the
previous guess (the contents of the Y-register). For a case 2 solution,
the guessesdiffer by 1 in the 12th digit.
w Immediately solving again for the variable. For a case 2 solution, the
Solver will return the message Sian Reversal on the second
attemptto find the root.

Example: A Case 1 Solution with Two Roots. Find the two roots
of the equation

2x2-7x -2=0

Express the function in program AA.


L 25-Bute Pram
10
,_
M
Iz

81 LEL "AR"
B2 MYAR "R"
83 RCL e

110 3: The Solver


B4 X+2
a5 2
B6 X
er 7
88 RCLx "X"
89 -
18 2
a1 -
12 END

Set the display format to ALL. Select the Solver application and then pro-
gram AA,
BODISP) ALE :@
BSOLVER |n-——--|

X=3.769556443708
NIIANANI

Roll the stack contents down to see the previous guess.


Ry x: 3. 76556443708
NDNY

The estimatesare the same in all 11 decimal places. Roll the stack con-
tents down to see the value off(x) at the root.
Ix: 0 |
INDT

ftx) is exactly 0. Now enter guesses of ~0.1 and 1 for the second root
and solve.
A fwe =-2.659564437075E- 1
164

3: The Solver 11
Roll the stack contents down to see the value off(x) at the root. Again,
f(x) is exactly 0.
RY) RY x: @
|“-----l

Exit from the Solver and return the display format to FIX 4,
EXIT v: 8. 0000
H(DisP) 4 x: 0. 0000

Example: A Case 2 Solution. In the example on pages 101-105 in


this chapter, you found the value of the pressure P in the ideal gas equa-
tion ofstate given values for the other variables V, n, and T,

Using the same valuesfor the variables V, n, and T, solve again for P.

Set the display format to ALL.


ADisA AL |Se1ect Solve Program |
EI N

Start program GAS2. (Reenter the program if you have cleared it from
the calculator.)
GASZ2 |><= 0 I
NYOB

Enter the values for the known variables and solve for the pressure.
P=27,8247827273
(Pv[NT&]E|

Roll the stack down to see the previous estimate.


x: 27, 8247827272
[PvWT&E|

112 3: The Solver


The estimates differ by 1 in the last decimal place. Roll the stack down to
see the value off(x).
/D %: 0. 00DP0POBOD]
|nn.:--:-u|
The value off(x) at the root is a very small nonzero number. The root is
not an exact root, but it is a very good approximation. Exit from the pro-
gram and return the display format to FIX 4.
EXIT - 0. 0000
@05P) F1X 4 [ENTER x: 1.0000e-11

Problems That Require Special Consideration. Some types of


problems require special consideration. The following function has a
discontinuity that crosses the x-axis.

7 \_ >x

The Solver will return an x-value adjacentto the discontinuity. The value
off(x) may be relatively large.

3: The Solver 113


Example: A Discontinuous Function. Find the root of the equation
IPx) -15=0
Express the function in program BB.
88 { 18-Byte Prom
81 LBL "BB"
82 MVAR "X"
@3 RCL "R"
P4 IP
85 1.5
96 -
87 END

Select the Solver, select program BB, provide guesses of 0 and 5, and
solve forx.
B(SOLVER) BB |X=2 . pBPO l
ENE DRNNS

The Solver finds a root at x = 2.0000. Now check the value off(x).

BY RY E -9.5000 I
1t{1

The value off(x) seems relatively large. This indicates that you should
further evaluate the function. By plotting the function, you find that the
root atx = 2.0000 is in fact a discontinuity, and not a true zero crossing.

Exit from the Solver.

ExiT] EXIT) v: B, 0000


x: -8.50008

Finally, consider the following function. This function has a very steep
slope in the area of the root. Evaluation of the function at either neighbor
may return a very large value even though the function has a true root
between the neighbors.

114 3: The Solver


f(x)

o
Use care in interpreting the results of the Solver. The Solver is most
effective when used in conjunction with your own analysis of the function
you are evaluating.

A Sign Reversal. The values ofthe following function are approaching


infinity at the location x, where the graph changes sign.

Thefunction has a pole at x,. When the Solver evaluates such a function,
it returns the message Sian Rewsr=zal.

3: The Solver 115


Example: A Pole. Find the rootof the equation

—x
(x* - 6)
Asx approaches V6,f(x) becomes a very large positive or negative
number.

Express the function in program CC,


B8 { 23-Bute Pram 3
@1 LBL "CC"
Bz MVAR "X"
892 RCL "X"
84 RCL "R"
g3 K12
BE 6
8y -
az +
a9 1
18 -
11 EHND

Select the Solver and then select program CC.


[SOLVER) © CC |><: 0.06800 |
. L&[11|

Provide guesses of 2.3 and 2.7, and solve for x.


2. K=2.4495
Sian Reversal

116 3: The Solver


Theinitial guesses yielded opposite signs for f(x). The interval between
successive estimates was then narrowed until two neighbors were found.
These neighbors made f(x) approach a pole instead of the x-axis. The
function does have roots at -2 and 3, which can be found by entering
better guesses.

Exit from the Solver.

~3 .« 4495
oK 4495

An Extremum. When the Solver returns the message Extremunm,it


has found an approximation to a local minimum or maximum ofthe
numerical absolute value of the function. If the solution (the value in the
X-register) is + /-~ 9.99999999999 x 10*®, the Solver has found an asymp-
totic extremum,

ft)

NN
Relative minimum Asymptote
PX
Relative maximum

3: The Solver 117


Example: A Relative Minimum. Find the solution of the parabolic
equation

x2-6x+13=0
(It has a minimum atx = 3.)

Express the function in program DD.


B8 { 23-Bute Pram 2
a1 LeL "DD"
B2 MYAR "X"
B3 RCL "wr"
B4 K+2
0S5 &
B6 RCLx "R"
a7y -
gge 13
89 +
1a EHND

Select the Solver application and then program DD.


WEOLVER) ©oh - 0. 0000
E IIIB

Provide guesses of 0 and 10 and solve for x.


%=3. 0008
Extremum

Exit from the Solver.

[EXIT] [EXIT] : 3. 0008


(ExIT) (EXIT] ;: 3. 06000

118 3: The Solver


Example: An Asymptote. Find the solutions for the equation

10 - 10
x
Express the function in program EE.
pa { 17-Byte Prgm 2
p1 LBL "EE"
92 MVYAR "X
a3 18
B4 RCL "X"
B85 1-/X%
96 -
a7 END

Select the Solver application and then program EE.

(SOLVER] |x= 0.0000 |


. La111|

Enter guesses of 0.005 and S, and solve for x.


.00 |X=B . 1000 I
IE(SDUNN

The Solver finds a root atx = 0.1000. Now enter guesses that have nega-
tive values.
1 R=-1.0D00E 500
2 Extr-emum

The Solverfinds an asymptotic extremum. (Press [J[SHOW] to verify that


the solution is actually —9.99999999999 x 10*® ) It’s apparent from
inspecting the equation thatif x is a negative number, the smallest that
Jx) can be is 10; f(x) approaches 10 as x becomes a large negative number.

Exit from the Solver.

v: 9. 9246E498
x: -1, 0000E 560

3: The Solver 119


Bad Guess(es). The Solver returns the message Bad Guess(es)
when one or both initial guesses lie outside the domain of the function. (If
a guesslies outside the domain of the function, the function returns a
math error when evaluated at that guess point.)

Example: A Math Error. Find the root of the equation

" X -
W-O.S—O

Express the function in program FF.


ga ¢ 2&e—Bute Pram
n1 LEL “FF"
B2 MVAR "R
g3 RCL "H"
B4 B.32
8S RCL+ "R"
[e +
By SEET
HE B.5
B3 -
16 END

Select the Solver application and then program FF.


BSOLVER]) FF x: 8.08000
IINNN

First attemptto find a positive root, using guesses 0 and 10.


0 K ®=0.1008
10 ¥ I NN TI

120 3: The Solver


The Solverfinds a root atx = 0.1. Now attempt to find a negative root
using guesses of —0.1 and —0.2. Note that the function is undefined for
values ofx between 0 and —0.3, since those values produce a positive
denominator but a negative numerator, causing a negative square root.
Although the HP-42S can execute arithmetic operations with complex
numbers, the Solver cannot find a complex number solution. If evaluation
off(x) returns a complex number, the Solver considers the function
undefined at that x-value.
RETAE %=-0, 2000
o Bad Guess(es)

Exit from the Solver.

EXIT v -g. vpg


X: =Y. Boov

A Constant. The Solver returns the message Constant 7 when it


finds that f(x) returns the same value at every sample point x. Such a
situation can occur if guesses are confined to a local "flat" region of a
function.

Example: A Local Flat Region. Find the root of the equation

1 _10-0
X

Express the function in program GG.


g8 £ 17-Bute Fram
LBL "GG"
" I I oo =
=d 0 0N oy P o

MWAR *&"
P RCL "R
174
14

" EHD

3: The Solver 121


Select the Solver and then program GG.
W(SOLVER]) GG |x= 8. 06000 |
LaL1[1

Supply guesses of 10 and 10%,


(E] 20 %=1, B006ESOD
Constant?

In this region of the function, the value off(x) is, within the 12-digit preci-
sion ofthe calculator, the same at every sample point. Hereis a graph of
the function.

f(x)


Try guesses of 0 and 10.
0 X=0. 1000
LsT[[|

The Solver finds the root ati = 0.1. Exit from the Solver.

v: 8. lfigg
X

122 3: The Solver


Round-Off Error and Underflow

Round-Off Error. The 12-digit precision ofthe calculator is adequate


for almost all cases. However, round-off errors can sometimes affect
Solver results. For example,

[(lx] +1)+10%2 - 10 =0
has no roots because f(x) is always positive. However, given initial guesses
of 1 and 2, the Solver returns the answer 1.0000 because of round-off
error.

Round-off error can also cause the Solverto fail to find a root. The equa-
tion

[x2-7| =0
has a root at v'7 . However, no 12-digit numberexactly equals v'7so the
calculator can never make the function equal to 0. Furthermore, the func-
tion never changes sign. The Solver returns the message Extt-zmun.
However, the final estimate ofx is the best possible 12-digit approxima-
tion of the root when the routine ends.

Underflow. Underflow can occur when the magnitude of a numberis


smaller than the calculator can represent; in such a case,it will substitute
the number 0. This can affect the Solver’s results. For example, consider
the equation

—1 =0
x2

whose rootis infinity. Because of underflow, the Solver returns a very


large (finite) value as a root. (The calculator cannot represent infinity,
anyway.)

3: The Solver 123


Integration
In this chapter, the following topics are covered:

= Basic use of the Integration application.


m Approximating an integral that has an infinite upper or lower limit.
m Using Integration and the Solver interactively.
m More on how Integration works.

Basic Integration

The procedure for execution of the Integration applicationis:


1. Create a program that:
a. Uses MVARto define the variable(s) in the integrand (the
function to be integrated).
b. Expresses the integrand. (Note that each variable in the
integrand must be recalled to the X-register.)
2. Apply the Integration application to the program.
a. Select the Integration application (press BZT(x))).
b. Select the program bypressing the corresponding menu key.
¢. Specify the values for any known variablesin the integrand.
Select the variable of integration.
d. Specify the values for LLIM, ULIM, and ACC.
e. Press o begin the calculation.

124 4: Integration
Example: Basic Integration. The angle of twist in a round shaft
undertorsional loading is calculated by evaluating the following integral.

where:

§ is the angle of twist of the shaft (in radians).


L is the length of the shaft (in meters).
T is the torque applied to the shaft (in Newton-meters).
J is the polar moment of inertia ofthe shaft (in meters*).
G is the shear modulus of the shaft material (in Newtons/meters?).

Torque T increases along


the length of the shaft
as a function of x .

Considera solid steel shaft (G = 83 x 10° N/m? ) that has a constant


diameter of 0.03 meters (J = 7.9521x 10"8 m*) and a total length L of 2
meters. Find the angle of twist in the shaft when loaded by a torque that
varies along the length x of the shaft as a function ofx:

T =13x*+8x3+15x2+9x + 6

For programming purposes, use Horner’s method to expand the polyno-


mial.

T=(((13x +8)x +15)x +9)x +6

4: Integration 125
Substituting this expression for T, the equation becomes
_ 2 (((13x +8)x +15)x +9)x +6
6=[ G dr

Expressthe integrand in the program TORQUE.

Program: Comments:
81 { S3-Bute Fram 2
@1 LEL "TORGQUE"

A2 MVAR MRY Lines 02-04: Declare thevariables.


B2 MVYAR "J"
a4 MYAR "G
a5 12 Lines 05-19: Express the integrand.
BE RCLx "R
gy =
HE +
B9 RCLx "R"
18 15
11 +
12 RCL¥ "x"
12 9
14 +
15 RCLx "®"
152 &
1V +
18 RCL+ "d"
13 RCL+ "G"

28 EMD

Select the Integration application.


Bfx) Select ff{x) Program
L) III

Select program TORQUE.


TORR Set VYars; Select Jfvar
IN AA.

126 4: Integration
Supply the known values for J and G,and specify the variable of integra-
tion X.
7.9521 E] 8 4]

Specify the lowerlimit (0), the upperlimit L (2), and an accuracy factor of
0.01.
ECC=0 . 0100 |
STWTNTEEBTNNNNN

Start the calculation.

S=0.8281
OTEEETHTERTSNNNR

The shaft twists through an angle # = 0.0281 radians (1.6077 degrees).


Exit from the Integration application.

[X: ¥

Approximating an Integral That Has an


Infinite Limit

It is often of interest to evaluate an improper integral (an integral that has


an infinite upper or lowerlimit). An improperintegral with an infinite
upper limit

[fee) de
is calculated "by hand" by evaluating the equivalent expression

lim,oo, fG&) dx

4: Integration 127
You cannot use the HP-42S to directly evaluate such an expression. You
can, however, approximate an answer by substituting a large number for
the infinite limit.

Example: Evaluating an Integral That Has an Infinite-Upper


Limit. Calculate the integral
* dx
',;’ 1+x2
by hand. Then approximate the integral with the HP-42S.

Part 1. The result is calculated by hand as follows.


® dx . ¢ dx
5 1+x2 TR 1 4 42
= lim,_,, (arctana)
r
2

Use the HP-428 to calculate /2 to 12-digit precision.


DISP} -ALE : @
=B % 1.5707963268

Part 2. Use the Integration application to evaluate the same integral,


using the value 1,000 to approximate the upper limit. First, express the
integrand in the program INFIN.
B8 { 28-Bute Pram X
81 LBL "IMFIN"
B2 MVYAR "X"
a3 RCL "R"
A4 ¥+2
as 1
as +
BY 1-¥
83 EHD

128 4: Integration
Select the Integration application and then program INFIN.
WA1 ‘N. Set Varsj; Select Sfvar

Select the variable of integration.


|x: 1.5707963268 |
ISVTSRTSNN

Specify the lower limit (0), the upper limit approximation (1,000), and an
accuracy factor of 0.01.
ACC=06.861
|mmmnnmnnlmnllllllllllllfl

Calculatethe integral.
S=1.57620935993
tumfunifwce[&

Using an upperlimit of 1,000, and an accuracy factor of 0.01, the calcula-


tor returns the result 1.57020935993. The calculation takes about 36
seconds andis correct to three decimal places.

Exit from the Integration application and return the display format to FIX
4
EXIT] [EXIT] (EXIT v: 0.0156
B(0ISP) x: 1.57082

The following table summarizes results and calculation times for upper
limit approximations of 100, 1,000, and 10,000, and accuracy factors of
0.01 and 0.0001.

4: Integration 129
Acc. Calc. Time
Factor uLIM Result (seconds)
( % actual) 1.5707963268
0.01 100 1.57518831857 5
1,000 1.57020935993 36
10,000 1.57088603739 140
0.0001 100 1.5607891695 18
1,000 1.56979476064 69
10,000 1.57069673168 279

Notethat the principle determining factor in the accuracy ofthe result is


the value of the upper-limit approximation, not the accuracy factor. Also
note that the calculations using an accuracy factor of 0.0001 require about
twice the time of those using an accuracy factor of 0.01.

In general, when you are approximating an integral, assess the extent to


which you are constraining the accuracy ofthe true integral with the
approximation of the limit, and choose an accuracy factor wisely. If the
limit that you substitute results in only a rough approximation of the true
integral, it makeslittle sense to calculate the approximation to a high
degree of accuracy.

130 4: Integration
Using the Solver and Integration
Interactively

In the first example in this chapter, you found the twist angle 6 at the end
ofa shaft by integrating the applied torque with respect to x. (The torque
varied as a function of the position x along the shaft.) You were limited, in
that example, to solving specifically for the twist angle 6. In general, for
the equation
ULIM
I-= fLLIM f(x) dx (calculated to accuracy ACC)

the Integration application enables you to solve only for the value 7 of the
integral. To solve for I, you:

® Write a program P that definesthe integrand f(x).


® Specify valuesfor the known variablesin the integrand.
m Specify the variable of integration.
» Specify values for the variables LLIM, ULIM, and ACC.

However, by writing a program S for the Solver that declares each vari-
able in the equation and invokes the Integration application on program P,
you can solve for any of the variablesin the equation:
m/
m The variables in the integrand f(x).
s LLIM, ULIM.
In the following example, you'll solve for the length L ofa shaft (the vari-
able ULIM in the Integration application) in the angle-of-twist equation.

Example. Using the Solver and Integration Interactively.


Restating the equation for twist in a shaft undertorsional loading:

4: Integration 131
Consider again the solid steel shaft of the first example in this chapter.
Forthis shaft, G = 83x10° N/m? andJ = 7.9521 x 108 m*. The shaft
is subjected to the same torsional loading T as in thefirst example. That
loading varies along the length x ofthe shaft as a function ofx.

T =13x* + 8x% + 15x2 + 9x + 6.

Find the length L thatresults in a twist angle ¢ of 0.1396 radians (8


degrees).

The variables in the equation are §, L, T,J, and G. The unknown variable
L is the upper limit of integration ULIM.

Part 1. Write a Solver program SHAFT that:

® Declares each variable in the equation.


m Expresses the equation such that its right side equals 0.
LT
j; 7G—dx—o-0

Program: Comments:
88 { 68-Bute Prgm X
gl LBL "SHARFT"

92 MVAR "THETA" Lines 02— 08: Declare the variables in


A3 MYAR "G" the equation.
64 MVYAR "J"
63 MVAR "LLIM"
08 MVAR "ULIM"
a7 MvAR "ACCY
B2 MYAR "X

89 PGMINT "TORGUE" Lines 09-11: Express the equation


18 INTEG "X* such thatits right side equals 0. First,
11 RCL- "THETR" calculate thefirst term of the equation
(the integral) (lines 09-10). The
value of the integral is returned to the
X-register. Subtract the second term
(THETA) (line 11).
12 END

132 4: Integration
In lines 09 - 10, the integralis calculated using the current value of ULIM,
which is iteratively supplied by the Solver as it searches for a solution.
Notethat the specified integration program is TORQUE from the first
example in the chapter.If you've deleted this program, you need to keyit
into the calculator now.

Part 2. Select the Solver application and then program SHAFT.


WEOLVER] SHAET bLTIITDT
@ ooz l

(Thevariable X is on the second line of the menu.) Enter valuesfor the


known variables.
ACC=0.0100
TST ITTRT

Now solvefor the upper limit L, providing initial guesses of 1 and 10.
ULIM=2.9528
(TBT ITRTRT

The shaft must be 2.9528 meters long to twist through an angle of 0.1396
radians.

Exit from the Solver application.

4: Integration 133
More on How Integration Works

The Accuracy Factor and the Uncertainty of


Integration
The Integration algorithm calculates the integral of a function f(x) by
computing a weighted average of the function’s values at many values ofx
(sample points) within the interval of integration. The accuracy of the
result depends on the number of sample points considered; generally, the
more the sample points, the greater the accuracy. There are two reasons
why you might want to limit the accuracy of the integral:
1. The length of time to calculate the integral increases as the number
of sample points increases.
2. There are inherent inaccuracies in each calculated value off(x):
a. Empirically-derived constants in f(x) may be inaccurate.,If, for
example, f(x) contains empirically-derived constants that are
accurate to only two decimalplaces,it is oflittle value to cal-
culate the integral to the full (12-digit) precision of the calcu-
lator.
b. Iff(x) models a physical system, there may be inaccuracies in
the model.
€. The calculator itself introduces round-off error into each com-
putation off(x).

To indirectly limit the accuracy of the integral, specify the accuracyfactor


of the function, defined as

true value of f(x) - computed value of f(x)


ACC =
computed value of f(x)

134 4: Integration
The accuracy factor is your estimation of the (decimal form of the) per-
cent error in each computed value off(x). This value is stored in ACC.
The accuracy factoris related to the uncertainty of integration (a measure-
mentof the accuracy of the integral) by:

uncertainty of integration = accuracy factor x'f | fix)] dx

f(x)
A

Thestriped area is the value of the integral. The orange-shaded area is


the value of the uncertainty of integration. It is the weighted sum of the
errors of each computation off(x). You can seethat at any pointx, the
uncertainty of integration is proportional tof(x).

The Integration algorithm uses an iterative method, doubling the number


of sample points in each successive iteration. At the end of each iteration,
it calculates both the integral and the uncertainty ofintegration. It then
compares the value of the integral calculated during that iteration with the
valuescalculated during the two previousiterations.If the difference
between any oneof these three values and the other two is less than the
uncertainty of integration, the algorithm stops. The current value of the
integral is returned to the X-register, and the uncertainty of integration is
returned to the Y-register.

It is extremely unlikely thatthe errors in each ofthe three successive cal-


culations of the integral - that is, the differences between the actual
integral and the calculated values —would all be larger than the disparity
among the approximations themselves. Consequently, the error in the
final calculated value will almost certainly be less than the uncertainty of

4: Integration 135
integration.

Example: The Accuracy Factor and the Uncertainty of


Integration. Certain problems in communications theory (for example,
pulse transmissions through idealized networks) require calculating an
integral (sometimes called the sine integral) of the form
¢
Si(t) = J:, S':x dr

Find Si (2).

First, write a program that expresses the function.


B0 { 1é-Byte Pram %
81 LBL "SI"
a2 MVYAR "X
83 RCL "&"
84 SIN
B85 RCL+ "X"
86 EMD

Set the display format to ALL. Set the angular mode to RAD.
B0OIsPF]HALL v: O
R(MODES] RAD x: ©
Select the Integration application and then program SI.

Bix) 8t Set Yars; Select Jvar


Ls11TT 1T |

Select the variable of integration X,then enter a lowerlimit of 0 and an


upperlimit of 2.
IULIM=2 I
(LUfuLibRoc]]]&

136 4: Integration
Since the function

xXx) =
sinx

f&x) *

is a purely mathematical expression containing no empirically-derived


constants, the only constraint on the accuracy of the function is the
round-off error introduced by the calculator.It is,therefore,at least
analytically reasonable to specify an accuracy factor of 0.00000000001
(1x10711),
(€] 11 “RACE ACC=0. 00PODPOOO0 1
TNTNTIIN

Calculatethe integral.
Ly S=1,6054129768
Lifuiiafncc|o

Check the uncertainty of integration.


[xxy] %: 2. 1094221 BD26E-11
TNNITNIS

The uncertainty of integrationis significant only with respectto the last


digit of the integral. The calculation took about 19 seconds. If you can
accept a less accurate answer, you can shorten the calculation time. Try an
accuracy factor of 0.001.
001 ACC JS=1.68541531589
TN ITATE TN R N

Check the uncertainty of integration.


[xzy] %: 1.6D60P0822892E-3
DOTNTRIT

4: Integration 137
The errorof integration is much larger now. However,it is still relatively
small compared to the value of the integral, and the calculation takes only
3 seconds.

Exit from the Integration application and return the display format to FIX
4
EXIT) [EXIT) [EXIT y: 1.6054
|[PIEIRE x: 0.0016

Example: A Problem Where the Uncertainty of Integration Is


Relatively Large. In the previous example, the uncertainty of integra-
tion was relatively small compared to the value of the integral. This is
because the value of the function was always positive within the interval of
integration. Now consider the simple function

fx) = sinx

Integrate the function from x = 0 tox = 6 (radians).

f(x)
A

By inspection, you can see that the value of the integral is a small positive
number, since the area with positive value from 0 to x is almost cancelled
by the area with negative value from = to 6.

138 4: Integration
Write the program that expresses the function.
66 { 14-Bute Pram >
@1 LBL “"SIN"
82 MVYAR "X"
83 RCL "»r"
84 SIM
85 EHND

Set the angular mode to RAD.Select the Integration application and then
program SIN.
BMODES] © RAD Set Vars; Select Jfvar
B/fx) TIDA
SIH

Select the variable of integration X, enter the lower and upperlimits (0


and 6), and an accuracy factor of 0.01. Then integrate with respect to x.
Gz =0, 0398
0 LLIM RTRTOIW
6 ULIM
01 ACC"

Now check the uncertainty of integration.


(xxy) x: B.8398
T TGATIN

The uncertainty of integration is large compared to the value of the


integral.

Exit from the Integration application.


EXIT] [EXIT] [EXIT

4: Integration 139
Conditions That Can Cause Incorrect Results

Although the integration algorithm in the HP-42S is one ofthe best avail-
able, in certain situations it - like all algorithms for numeric integration —
might give you an incorrect answer. The possibility of this occurring is very
remote. The integration algorithm has been designed to give accurate
results for almost any smooth function. Only for functions that exhibit
extremely erratic behavioris there any substantial risk of obtaining an
inaccurate answer. Such functions rarely occur in problems related to
actual physical systems,

Example: A Condition That Causes an Incorrect Result. Con-


sider the approximation of

j:oxe" dx

Since you’re evaluating this integral numerically, you mightthink that you
should represent the upperlimit of integration with a large number,say
100,000. Try it and see what happens. First write a program that expresses
fx).
08 { 17-Byte Pram 3
81 LBL "XEX"
82 MYAR "R®"
@3 RCL "X"
84 ENTER
a5 +/-
86 E+¥
arv x
83 END

Now select the Integration application and then program XEX.


B mER Set Vars; Select JSfvar
T RNNN

140 4: Integration
Select the variable of integration X, then enter the lower and upperlimits
and an accuracy factor of 0.001.
ACC=06.8010
STATTATEN TOB

Integrate with respect tox. (Stay in the Integration application after exe-
cuting this calculation. You will integrate this function again in the next
section.)
S=0,00008
(LbJutia] wic][|-]

The answeris clearly incorrect,since the actual integral off(x) = xe ~*


evaluated from 0 to oo, is exactly 1. But the problem is not that you
represented oo by 100,000, since the actual integral of this function from 0
to 100,000 is very close to 1. The reason you obtained an incorrect answer
becomes apparentif you look at the graph off(x) overthe interval of
integration.

f(x)
A

= »X

The graph has a spike (illustrated here with a greatly exaggerated width)
very closv.: to the origin . Because no sample point discovered thespike,
the algorithm assumed that f(x) was equal to 0 throughout the interval of

4: Integration 141
integration. Even if you increased the number of sample points by specify-
ing an accuracy factor of 1x 10! | none ofthe additional sample points
would discover the spike when this particular function is integrated over
this particular interval.

Subdividing the Interval of Integration. If you suspect the validity


of the approximation of an integral, subdivide the interval of integration
into two or more subintervals, integrate the function over each subinter-
val, then add the resulting approximations. This causes the function to be
evaluated at a new set of sample points, more likely revealing any previ-
ously hidden spikes. If the initial approximation is valid, it equals the sum
of the approximations over the subintervals.

Example: Subdividing the Interval of Integration. Consider


again the integral

[0 xe™®ax
Approximate the integral by subdividing the interval of integration into
three subintervals, one from 0 to 10, the second from 10 to 100, and the
third from 100 to 100,000.

First, integrate between 0 and 10. If you arestill in the Integration appli-
cation, simply supply the new value for ULIM.
10 ULIH 7=9.9595
mog RTINS ON

The answer is very close to 1. Now integrate between 10 and 100.


10 ELINM S=0.08005
100 ULIM TNTNT Y

The answer is very close to 0. The sum ofthe approximations over the two
subintervals is 1. Finally, integrate between 100 and 100,000. (Stay in the
Integration application after executing this calculation. You will integrate
this function again in the next section.)
100 L S=0.0000
EI
TN TN TR IA

142 4: Integration
The integral overthe third subinterval is 0. The sum of the integrals over
the three subintervalsis 1.

Conditions That Prolong Calculation Time


In the first example in the preceding section,the algorithm gave an
incorrect answer because it never detected the spike in the function
f(x) = xe * . This happened because the variation in the function was too
quick relative to the width ofthe interval of integration. In the second
example, you obtained a very good approximation by subdividing the
interval of integration into three subintervals between 0 and 100,000.
However,for this function,there is a range ofintervals that is small
enough to obtain the correct answer, yet result in a very long calculation
time.

Example: An Upper-Limit Approximation That Prolongs


Calculation Time. Consider again the integral

foc,xe “*dx
o
Approximate the integral by calculating it over the interval (0, 1,000).

Enter the new values for LLIM and ULIM. Then integrate with respect to
x.
OLLIM 7=1.0000
1000 M LLLIMJULwis |-

This is the correct answer, but it took a long time to calculate. To under-
stand why, compare the graph of the function betweenx = 10 andx = 10°
(which looks about the same as that shown on page 141) with the follow-
ing graph ofthe function betweenx = 0 andx = 10.

4: Integration 143
f(x)

0 10

You can see that the function is "interesting" only at small values ofx. At
greater values ofx, the function is not interesting sinceit decreases
smoothly and gradually in a predictable manner.

The algorithm samples the function at increasing numbers of sample


points until it has sufficient information about the function to provide an
approximation that changes insignificantly when further samples are con-
sidered. In the previous section, when you evaluated the integral between
0 and 10, the algorithm needed to sample the function only at values
where it was interesting butrelatively smooth. The sample points,after
the first few iterations, contributed no new information about the
behavior of the function and the algorithm stopped.

In the last example, most of the sample points capture the function in the
region where its slope is not varying much. The algorithm finds that the
few sample points at small values ofx return values of the function that
change appreciably from one iteration to the next. Consequently, the func-
tion has to be evaluated at additional sample points before the disparity
between successive approximations becomessufficiently small.

144 4: Integration
Forthe integral to be approximated with the same accuracy over the larger
interval as over the smaller interval, the density of sample points must be the
same in the region where the function is interesting. To achieve the same
density of sample points, the total number of sample points required over
the larger interval is much greater than the number required over the
smaller interval. Consequently, several more iterations are required over
the largerinterval to achieve an approximation of the same accuracy, and
the calculation requires considerably more time.

4: Integration 145
S
Matrices
This chapter builds on material introduced to you in chapter 14 of your
owner’s manual. The following topics are covered:

m Using the matrix editor and indexing functions.


m Vector solutions.
m Solving simultaneous equations.
m Using the Solver with simultaneous equations.
= Matrix operations in programs.

Using the Matrix Editor and Indexing


Functions
In the following example, you'll:

m Create a matrix.
m Use the matrix editor to manipulate data.
m Use indexing functions and statistics functionsinteractively.

Example: Accumulating Meteorological Data. Dr. Steven


Stormwarning, noted meteorologist, has accumulated the following data
and wishesto store it in a matrix in the HP-428.

146 5: Matrices
Day # Temp Wind Humid
1 67 8 54
2 69 14 36
3 74 4 72

Creating a Named Matrix

Create a 4 x 4 matrix "WTHR".

4 BMATRIX] (W]DIM = 4.0000


WTHR (LOT JcRO:STUVEL DI INDESIECITN)

Using the Matrix Editor

Enter the matrix editor and select the matrix you just created.
EDITH NTHR 1:1=0.0060
GOTOD

Fill element 1:1 with the Alpha string DAY #. (Remember,to execute
(ASTO], press in ALPHA mode.)
B(ALPHA] DAY # U 1:1="DAY #"
Lejoe+4[oOTO]»
EXIT
Fill the remaining clements in row 1 with the corresponding Alphastrings
from the table. (The keystrokes for element (1:2) are shown here.)

W(ALPHA] TEMP 1T4="HUMID"

5: Matrices 147
Now fill the remaining elements with the corresponding data.
qi14=72_

Stormwarning finds that his assistant has incorrectly recorded the tem-
perature on day 1; it was 77, not 67.
GOTO2 [ENTER] 2 [ENTER] 77 [EXIT) x: 77 . 00008

Several days later the doctor has more data to add: on day #4, the tem-
peratureis 77, the windspeed is 5, and the humidity is 76. First,set the cal-
culator to Grow mode to create a new row in the matrix.
EDITN WTHR ¢« S:1=0. 0000
(v] GROW. (&)

Fill in the new data.

5:4=76_
ITTT

Stormwarning now realizes he has entered the data for day #5, not day
#4. For day #4, the temperature was 68, the windspeed was 12, and the
humidity was 41. First change the value in element 5:1 to 5.
5:1=5_

Now insert the new row.

(v] IHER D 1=0.6000


UN:RJUELR] [WRAPIGROs]

148 5: Matrices
Enter the actual data for day #4.
(a) 4 Dt4=41_
[+Joc]++Jooto]+

Exit from the Matrix application.


EXIT] [EXIT

Using Indexing Utilities and Statistics Functions


Interactively

Dr. Stormwarning now wants to execute statistical operations on segments


of his accumulated data. He would like to find the mean temperature and
windspeed for the five days. He’ll execute GETM to create in the X-
register a 5 x 2 submatrix that contains the temperature and windspeed
data. He’ll then execute £+ to store the data from this submatrix in the
summation (statistical) registers, select the STAT menu, and find the
mean. (Remember that the £+ function automatically stores the data
from an n-row x 2-column matrix into the currently defined summation
registers. Referto the discussion of the £+ function in chapter 15 of your
owner’s manual for more information.)

Specify WTHR as the indexed matrix.


BMATRIX] (V]THDER x: 41,6060
00T [CROSS[UNEC] D1[INDES[ECITN]

Set the index pointers to element 2:2 (thefirst temperature data entry).
2 [ENTER) (V] 5TOLY . 7.0000

Now get the 5 x 2 submatrix that contains the temperature and windspeed
data.
5 2.GETH % [ Sx2 Matrix ]
STOI[RELI[TOEL[RCLEL|PUTH[GETH]

5: Matrices 149
Clear the summation registers, then store the data from the matrix in the
summation registers. (If the calculator returns the message
Nonexistent, the current SIZE allocationis insufficient.)
B(CLEAR] ‘CLY X 5. 0000
B(TOPFCN) 3%

Select the STAT menu and find the mean of the temperature data.
B(STAT] MEAN x: 73,0000
LZeJUM[HEANJHIMNTSOEY]CFIT]

Find the mean of the windspeed data.


x% x: 8. 6000
B ETN TRE

The mean temperature for the five days is 73. The mean windspeed is 8.6.

Exit from the STAT menu.


EXIT

Matrix Utilities
The following routines use existing matrix functions to build useful matrix
utilities.

Finding the Column Sum of a Matrix. CSUM calculates the


column sum of the matrix in the X-register. (The column sum of a matrix
A is a row matrix, each element of which is the sum of the elements of the
corresponding column of matrix 4.) The resultant matrix is returned to
the X-register.
88 { 14-Byte Pram 2
81 LBL "Csum»
82 TRANS
A3 RSUM

150 5: Matrices
04 TRANS
a5 END

Finding the Column Norm of a Matrix. CNRM calculates the


column norm of the matrix in the X-register. (The column norm of a
matrix A is the maximum value (over all columns) of the sums ofthe
absolute values of all elements in a column.) The result is returned to the
X-register.
08 { 12-Bute Pram
91 LBL “"CHRM"
B2 TRANS
83 RHRM
84 END

Finding the Conjugate of a Complex Matrix. To find the conju-


gate of a complex matrix:
1. Place the matrix in the X-register.
2. Press l[COMPLEX].
3. Press [*4].
4. Press [J[COMPLEX].

The conjugate is returned to the X-register.

Finding the Matrix Sum of a Matrix. MSUM calculates the matrix


sum (the sum ofall the elements) of the matrix in the X-register. The
result is returned to the X-register.
B3 { 18-Byte Pram
a1 LBL "MSUM"
B2 XER "Csum"
83 RSUM
84 DET
@3 END

5: Matrices 151
Finding the Maximum and Minimum Elements of a Matrix.
MINMAX finds the maximum or minimum element of the real matrix in
the X-register. The elementis returned to the X-register. The indexed
location of the elementis returned to the Y- and Z-registers (column
number in Y, row number in Z). Set flag 09 to find the maximum ele-
ment. Clear flag 09 to find the minimum element.

Program: Comments:

ae { 61-Byte Pram
a1 LBL "MINMAR"

az STO "MIHMAX" Lines 02-05: Store the matrix


B3 INDEX "MIHMAX" currently in the X-register in
a4 RCLEL MINMAX, index MINMAX, and
a5 GTO @z establish element 1:1 as the current
maximum or minimum element.

a6 LBL 61 Lines 06—12: If flag 09 is clear,test if


a7z RCLEL the current element is greater than the
B FsS? 69 current minimum.If yes, go to label 04
a3 GTD @2 (to maintain the current minimum). If
18 nay? no, go to label 03 (to make the current
11 GTO a4 element the new minimum).
12 GTO 83

13 LBL 82 Lines 13-15: If flag 09 is set, test if


14 REN? the current elementis less than the
15 GTC B4 current maximum. If yes, go to label
04 (to maintain the current max-
imum). If no, make the current ele-
ment the new maximum.

16 LBL B2 Lines 16— 19: Make the current ele-


17 RCLIJ ment the new maximum or minimum.
18 RCL ST
rJ

19 EHTER

28 LEL B4 Lines 20 —24: Maintain the current


21 E+ maximum or minimum element.
22 J+

152 5: Matrices
23 FC? 77
24 GTO B1

25 END

Sorting a Matrix. SORTsorts the rows of the matrix in the X-register


in ascending order by the values in column 1. The sorted matrix is
returned to the X-register.

Program: Comments:
B3 { 81-Bute Pram 2
@1 LBL "SORT"

@2 STO "SORTHAT"
63 IWDEY “SORTHMAT"

g4 LBL &1 Lines 07-10: Establish the row


85 I+ numberto sort. (On thefirst pass, row
@& F57 76 2 is the row to sort, against row 1. On
B7 GTO B4 the second pass, row 3 is the row to
83 RCLIJ sort, against rows 1 and 2.) Continue
89 ROY until all rowsare sorted.
18 RCLEL

11 LBL B2 Lines 11-24: Successively move the


12 1- "sort row" up the matrix until its
13 RCLEL column 1 value is greater than the
14 F37 76 column 1 value of the previous row.
15 GTO B2
16 ¥2Y?
17 GTO 832
18 Ry
19 RCLIJ
28 RCL+ 5T ¥
21 ROR
22 Rv
23 R+
24 GTO 82

5: Matrices 153
25 LBL 93 Lines 25-32: Increment the *sort-row"
26 R+ number. If the increment causes the
27 R+ index pointer to wrap, return the
238 1 sorted matrix to X and end the pro-
29 STOIJ gram.
38 GTO 91
31 LBL B4
32 RCL "SORTMAT"

33 EMD

Vector Solutions
Vectors are a special subset of matrices. You can describe a vector with
either a 1-row X n-column matrix, or a 1-column X n-row matrix.

Geometry
The area of a parallelogram can be determined by the equation

A = Frobenius norm (magnitude) of ( V'V; x V)

where ( 'V, X V;) is the vector cross product V; and V.

154 5: Matrices
Example: The Area of a Parallelogram. Findthe area of the fol-
lowing parallelogram.

(0,0,0)

Create vectors V; and V5 .


BMATRIX] x: 3.0000
1 [ENTER)3 (V] DIM 00TJCROZE[UVECDItINDER[ECITN]
(ENTER] V1 [ENTER]
1 [ENTER] 3 DIM
[ENTER] V2 (ENTER]

Enter values for each element in V; .


x: 2.00008
007 [CROSS[UVEC DIk [INDER[EDITH]

2 [EXIT

Enter values for each element in V, .


x: 3.0000
00T[RO:E[UMEC]Bitd[INDERJETH]

Calculate the area.

! 1[RcC) |x: 15. 0000 |


CR CATALOG] & 007 [CROS2fUMECDMINBER[EDITN]
Kl

5: Matrices 155
The area ofthe parallelogram is 15.0000.

Exit from the Matrix application.


EXIT

Coordinate Transformations

It is often necessary in dynamics or mechanical design problems to per-


form coordinate transformations. Coordinate transformations require you
to:

Calculate a unit vector.


Add vectors.
Calculate a vector dot product.
Multiply vectors.
Calculate a vector cross product.

156 5: Matrices
ORIGINAL
SYSTEM

o x
i W~ NEWSYSTEM
6

Notes: AXIS (the rotation axis vector)


is pointing out of the page
atpoint T .

The rotation is relative to the


translated origin.

The equation for a coordinate transformation of a point from the old sys-
tem to a new system is

P°=[(P-T)'n]n(1 -~ cosf) + (P - T)cosé + [(P - T)xn]sind


The equation for a coordinate transformation of a point from a new sys-
tem to the old system is

P=[(P"*n)n(1l - cosf) + P cosé + (P"xn)sin(-6)]+T

where:

P’ is the coordinates ofthe point in the new system.


P is the coordinates of the pointin the old system.
T is the origin of the new system.
n-is the unit vector of the axis about which the rotation is to be done.
6 is the rotation angle.

5: Matrices 157
Note that the translation occurs before the rotation. The rotation is rela-
tive to the translated origin.

The following program, COORD,enables you to fill the vectors P,


(or P), T, and AXIS with data by programmatically invoking the matrix
editor and enables you to specify either an old-to-new or new-to-old
transformation. (AXIS is the rotation axis vector. COORD storesthe data
you supply for AXIS in the variable #, then calculates the unit vector n.)

To key in COORD: Create variables P, T, P*, n, and & before pro-


gram entry.

Here is an annotated listing of COORD.

Program: Comments:
B8 { 216~Buyte Pram >
gl LBL "COOGRD®

62 EXITALL Lines 02 - 11: Build the main menu.


H#3 CLMEHU
B4 P
@35 KEY 1 GTO
[

@Y KEY 2 HERQ
=
M

as "AXIs"
89 KEY 2 XEQ
1)
1

16 "g"
11 KEY 4 XEQ 84

1z LBL 98 Lines 12—-15: Display the main menu.


12 MEHU
14 STOP
15 GTO 58

& LBL @1 Lines 16~22: Display the submenu to


et

“pr edit vector P ( or P* ) and choose the


b
=~

HEQ 39 direction ofthe transformation.


e
o
O

"He0®
ea
o0

KEY S GTO 83
[
&0

158 §: Matrices
21 IIO_)HII
22 KEY & GT0 Bé&
23 LBL 97 Lines 23—-27: Display the submenu.
24 MEHU
29 CF B8
26 STOP
27 GTO 37

28 LBL @2 Lines 28 -32: Place the vector names


29 IITII T and n in the Alpha register to create
28 GTO 39 the vector.
31 LEL @3
32 n

33 LBEL 29 Lines 33-46: Create a 1 x 3 vector P,


34 CLMENU T, or n and open it for editing. Build
35 ASTD S TL matrix editor menu labels and prompt
26 1 for data input.
37 ENTER
38 2
39 DIM IMD ST L
40 EDITH IND ST L
41 II(_II

42 KEY HEC 11
-

43 II_}II

44 KEY ®ERQ 12
o

45 KEY GTO "COORD"


46 RTH

47 LEBL 11 Lines 47-52: Execute the matrix edi-


43 £
tor functions.
49 RTH
o248 LBL 12
51 -

32 RTH

53 LEL B84 Lines 53-55: Promptfor the value of


54 IHPUT II“-:II A.
=kl RTH

5: Matrices 159
LBL 83 Lines 56— 57: Set flag 00 for a new-to-
SF a8 old transformation.,
LBL 86 Lines 58 -90: Evaluate the transfor-
EXITALL mation equation. If flag 00 is clear,
RCL "“P" calculate the old-to-new transforma-
FC? 08 tion.If flag 00 is set, calculate the
RCL- "T" new-to-old transformation.
STD IIP "

RCL "n"
UVEC
sTO "n"
DOT
1
RCL "&"
cos
RCLX "n"
X
RCL “&"
cos
RCLx “P'"
+

RCL "P'"
RCL "n"
CROSS
RCL "<"
FS? 89
+/-
SIN
®
+

F5? @@
RCL+ “T"
sTO "P"
GTO @1
END

160 5: Matrices
To use COORD:

1. Press COORD.
2. Press | then supply values for the elements of T using the
matrix editor labels in the menu. Press ([EXIT] to return to the main
menu.
Press (A% 185 ,then supply values for the elementsof the rotation
axis using the matrix editor labels in the menu. Press to
return to the main menu. Note that COORD stores the rotation
axis in variable n, calculates the unit vector of the rotation axis, and
stores the unit vector back in n. If you press 'AXISafter executing
a three-dimensional transformation, you will see the newly calcu-
lated elementsof the unit vector, not the original rotation axis.

For a two-dimensional transformation, set the rotation axis to


(0,0, 1).
Press | “ then supply a value for X and press [R/S].
Press . F , then supply values for the elements of P (or P”)
using the matrix editor labels in the menu. Then press ~ §*H to
convert from the old system to the new system, or press N=*0 to
convert from the new system to the old system. The calculation is
now executed.

Example: A Three-Dimensional Translation with Rotation. A


three-dimensional coordinate system is translated from (0, 0, 0) to (2.45,
4.00, 4.25). After the translation, a 62.5° rotation occurs about the (0, -1,
-1) axis. In the original system, a point had the coordinates (3.90, 2.10,
7.00). What are the coordinates of the pointin the translated, rotated sys-
tem?

Forthis problem:

P = (3.90, 2.10, 7.00)


T = (245, 4.00, 4.25)
AXIS = (0, -1, _1)
& = 62.5°
Set the display format to FIX 2. Set the angular mode to Degrees. Exe-
cute program COORD.
[DISP) Fi® 02 : 0.00
= :,5555:{) g xnmu-

COORD

Enter the elements of T.

e X 2.949
.45 g GBETEA

x: 0.00
fv [es] &«]|

Enter the value of X..

Loa x: 62.50
62.5 lnnmgul
Enter the elements of P.

Calculate the transformation.

Element 1:1 of P” is 3.59. Check element 1:2.

Ce12|[N>0]0-N]

162 5: Matrices
Check element 1:3.

The coordinates of the point in the new system are (3.59, 0.26, 0.59). Exit
from program COORD and return the display format to FIX 4.
v: 1.0000
BOISF) F1x4 x: 8.5891

Solving Simultaneous Equations


Evaluation of an electrical circuit by the technique of loop currents gen-
erates a system of simultaneous equations. The number of equations in
the system is equal to the number of loopsin the circuit. The first example
in this section finds the currents in a four-loop, purely resistive circuit (the
termsin the system of equations are real numbers). The second example
finds the currentsin a four-loop circuit that has complex impedances (the
terms in the system of equations are complex numbers).

Example: Solving Real-Number Simultaneous Equations.


Considerthe following four-loop circuit.

Ry Rg Rs Rz

W W—MN—7"W

Apply the technique of loop currentsto find the currents I, I,, I3, 1,.

5: Matrices 163
The equations to be solved are (in variable form):

1. (Ry+R3)(I1) - (R3)(I3) =V
2. -(R3)(11) + (Rz+ Rs + R)(I2) - (Ry)(13) =0
3. -(R)(I2) + (R¢+Rs+ Rg)(I3) - (Rg) (1) =0
4. -(Rg)(I3) + (Re+R7+Rg)(14) =0
Put the equations in matrix form, substituting the following values for the
variables: V' = 34 V and R, through Rg = 111

2 -1 0 of |1

OOQ%
-1 3-1 0 I,
0 -1 3-1| [,| =
o o0-1 3| [g,

Select the Simultaneous Equation application, and specify the number of


unknowns.
BMATRIX] .SIMQ 4 [ENTER x: B.0800
GEHTSTRIS

Enter the values for the elements of the coefficient matrix MATA. (The
keystrokes for the entering the first row data are shown here.) After
entering all the values, return to the main menu.
x: 3.0000
(NITRTSNN

EXIT

Enter values for the constant matrix MATB.

MATB %: 0.0000
2 RCTXT3TAA

0 EXIT)

164 5: Matrices
Calculate the unknowns.
HATR. 1:1=21.0000

1, is 21 A. Now check I.
g 2: 1=8, 0000

Check I.
3t 1=3.0000

4:1=1.060060
€lop ++[GOT0{-

Leave the matrix editor. (Stay in the Simultancous Equation application


for the next example.)
EXIT x: 1.08000
IATGRSIN.

5: Matrices 165
Example: Solving Simultaneous Equations That Have Com-
plex Terms. Now consider the following circuit.

R4 R3 Rg R7

W—TW
IODF-OLT $Q$’”
)| AY
/1 /1 /1 JI
o C, Cg Cy

The capacitor in each loop ofthe circuit introduces a complex term into
cach loop equation:

1. [(Rl +Rg)- i(wc%)] (L) - (R)(I3) = V


2. - (Ry)(I2) + Ry +R3+ Ry - i(%;)](lz) -(Ry)U3)=0

3. -(R)(U2) + Ro+ R+ R- i(w%s)](ls) - (Re)(1) = 0


4. - (Re)(I3) + [Re + Ry + Rg - i(wci‘)](h) =0

166 5: Matrices
Put the equations in matrix form, substituting the following values for the
variables: V = 34V, R, through Rg = 511, w = 100 radians/second,
and C; through C,=1F.

10 - i0.01 -5 0 0 I, 34
-5 15 - i0.01 -5 0 I3 0
0 -5 15-i001 -5 I;) T |o
0 0 -5 15-i001| |f, 0

Set the coordinate mode to Rectangular. Make MATA a complex matrix.


BW(MODES]) RECT %: 0. 0000 10.0000
0 @(COMPLEX] ()RNTOWB
BM
Enter the values for the elements of the matrix. (The keystrokes for the
entering the first row data are shown here.) After entering all values,
return to the main menu.
: x: 15.0000 -i0.0100
10 01 EEECEEGRSIT

W(COMPLEX]

EXIT

Solve for MATX. (MATB has the same value as in the previous example.)
1:1=4.2000 i8.00861

I, is 42000 + i0.0061 A. Now check I, .


2:1=1.6000 i@.0037

5: Matrices 167
Check I3-

G 311=0.6000 10,00
=foww]+4+Joorn]

Chcck I4

4:1=0.2000 10.0008

Exit from MATX.


EXIT x: 0. 2000 i0.8008
UARTAJMATE[HATR]||

Make MATA and MATX real matrices. Exit from the Matrix application.
MATA B(COMPLEX)
MATA
v: [ 4x1 Hatrix 1
x: [ 4x1 Matrix 1]

(RCL) MATXWMCOMPLEX]
MATR
[EXIT) [EXIT)

Using the Solver with Simultaneous


Equations
In the examples in the previous section, you found the loop currents I,
through I, by dividing the constant matrix MATB bythe coefficient matrix
MATA. You were limited in that example to solving specifically for the
loop currents in the solution matrix MATX.

In the following example, you’ll use the Solver and matrix division to find
the value of one elementof the coefficient matrix, MATA, given:

m Values for the other elements of the coefficient matrix.


m Values for the elements of the constant matrix.
® A specified relationship between two values of the solution matrix.

168 5: Matrices
Example. Using the Solver to Find the Value of an Element
of the Coefficient Matrix. Consider again the circuit from the previ-
ous section in this chapter.

R4 Rga Rs Rz

M——W W W
_D Ro I R4 Iy

<) =
[+

Rg
T/ S/
I
<

Find the resistor value R; such that loop current I, is 20 A greater than
loop current I, (I; = I;+20), when V' = 40 V, and R, through Rg = 111.

These conditions generate the following matrix equation.

R -1 0 0 I,+20
QOOS

-1 3-1 0 I,
0 -1 3 -1 I,
0 0-1 3 1,

5: Matrices 169
Part 1. Write the program for the Solver.

Program: Comments:
a0 { 82-Byte Praom 2>
a1 LBL "SIMUL"

a2 MVAR “R* Lines 02-05: Declare the variables R,


a3 MYAR "ROW" ROW, COL, and D.
B4 MVAR "COL"
85 MVAR "D"

a6 INDEX "MATA" Lines 06 —11: Index the coefficient


ar RCL "ROW" matrix, and set the index pointer to
A RCL "COL" the element specified by the current
a9 STOIJ values of ROW and COL (lines 05—
14 RCL "R" 08). Store the current value of R (sup-
11 STQEL plied first by you as initial guesses, and
then iteratively by the Solver) in the
specified element (lines 09-10).

12 RCL "MATB" Line 12-14: Solve for MATX. MATA


13 RCL+ "MATA" has the current value of R in the
14 STO "MATR" specified element.
15 INDEX "MATX" Lines 15-20: Index the just-calculated
16 RCLEL solution matrix (line 14). Calculate
17 I+ I, - (I; + D) (lines 15-20). The
18 RCLEL Solveriteratively supplies values for R
19 RCL_._ IIDII
untill, - (I; + D) = 0.
20

21 EHD

170 5: Matrices
Part 2. Enter the Matrix application, and specify a system of equations
with four unknowns.
BMATRIX] &IM @4 [ENTER x: 0. 0000
atalttaTeltnrs]||

Fill MATA with the known coefficients. Element 1:1 contains the
unknown resistor value R. You can leave this elementat its current value.
(The keystrokesfor the first two rows are shown here.) After entering all
the data, return to the main menu.
x: 3.00008
EEIEELETRI

Fill MATB with the known constants, then exit from the Matrix applica-
tion.

0
EXIT] [EXIT] [EXIT

Select the Solver application, and then program SIMUL.


W(SOLVER] : % 40, 0000
ITTTA

Specify element 1:1 ofthe coefficient matrix.


1 COL=1.0000
ITTON

Enter 20 for D.
20 |D=28. B0oA l
ITNTTT

5: Matrices 17
Enter guesses of 0 and 10 for R and solve for R.
=1.6190
ITT

Verify that element 1:1 of the coefficient matrix (R) is 1.6190.


BMATRIX] (V]
EDITH MRATH

Ry =R - Rz = 0.619 Q. Check the values for I, and I, .


EDITH MATH 1:1=32.3077

I, is 323077 A. Check I,
2:1=12.3677

I is 12.3077 A.Exit from the Matrix application.


[EXIT] [EXIT) v: 1,6190
x 12.3077

Matrix Operations in Programs


All matrix functions except GOTO are programmable. The programs for
advanced statistical operations in the following chapters use matrices
extensively.

The program LIST on pages 176 - 178 enables you to accumulate statisti-
cal data in a matrix with the same keystroke sequence that you use in nor-
mal data entry into the summation registers.

The program MLR on pages 186 — 192 uses matrix and statistical functions
to calculate a linear regression for data sets of three independentvari-
ables. MLR creates a coefficient matrix MATA and a constant matrix
MATB. It executes matrix editor functions to fill them with data, then exe-
cutes matrix division to calculate the solution matrix MATX,

172 5: Matrices
The program PFIT on pages 218 —222 plots the statistical data from the
matrix currently in the X-register, then fits and plots a curve to the data
using the currentstatistical model. It plots the curve and the data points
using x-y data pairs from complex matrices.
6
Statistics
This chapter presentsfive programs for statistical operations. The pro-
gramsuse statistical functions introduced in chapter 15 of your owner’s
manual, and integrate matrix operations presented in the previous chapter
and in chapter 14 of your owner’s manual.

» Three programs enable you to accumulate data in a matrix for subse-


quentstatistical operations:

m LIST enables you to fill an n x 2 matrix ZLIST with x- y data


pairs with the same keystroke sequence that you use to enter data
into the summation registers.
m SFORM stores an n X m matrix in ELIST and redimensions
LLIST to nm x 2. Each elementof the original matrix becomes
an element of column 2 of ZLIST. Column 1 is filled with zeros.
a XVALS fills column 1 of BLIST with x-values 1, 2, 3, ..., n for
linear or exponential curvefitting.

m MLR calculates a multiple linear regression for two or three indepen-


dentvariables using the £+ function and matrix operations.
m PFIT plots the x-y data pairs from LLIST and uses FCSTY to plot a
curve to the data according to the currently selected statistical model.
(The annotated listing of PFIT is in chapter 7 on pages 218-222.)

174 6: Statistics
List Statistics
To supply a set ofx-y data pairs to the calculator for subsequent statistical
operations, you use the keystroke sequence
y-value [ENTER] x-value

for each data pair. The summation cocfficients in the 6 (or 13) summation
registers are automatically recalculated each time you press (Z+]). The cal-
culator does not, however, maintain a list of the individual data pairs.

To update the summation registers and maintain a list of the x-y data
pairs, you:

1. Create a 2-column matrix.


2. Use matrix editor functionsto fill the matrix with the data pairs.
3. Place the matrix in the X-register.
4. Execute T+ to accumulate the data in the summation registers.

(You did this in chapter 5 in the section "Using Indexing Utilities and
Statistics Functions Interactively”.)

6: Statistics 175
The LIST Program. The following program, LIST, enables you to fill a
1- or 2-column matrix LLIST with x-y data pairs using the keystroke
sequence

y-value x-value L.18T+ (for each data pair).

where [187T# is one of three menu keys built by LIST. Note that this is
the same keystroke sequence that you use to enter statistical data into the
summation registers.

To key in LIST:

1. Create variable ELIST before program entry.


2. Assign functions J+ and J- to the CUSTOM menu before program
entry.
3. Create labels LIST, LIST +, LIST -, and CLIST when you begin
program entry.

Hereis an annotated listing of LIST.

Program: Comments:

BE { 197-Bute Pram >


@1 LBL "LIST®

B2 CLMENU Lines 02-11: Build and display the


83 "LIST+" menu keys.
a4 KEY 1 ¥EGQ "LIST+"
as “LIST-"
KEY 2 ®E& "LIST-"
a7 "CLIST®
a5 KEY & ®EQ "CLIST"
B3 MEHU
1@ STOF
11 GTO "LIsT"

176 6: Statistics
12 LBL "LIST+" Lines 12-20: If ZLISTexists, index it
13 SF 23 and make it grow by one row. If it
14 XE@ I doesn’t exist, create and index it (in
15 FC?C 23 lines 32-42).
16 GTO 82
17 GROM
18 ‘J_

19 J+
28 WRAP

21 LBL 08 Lines 21 -28: Store the x-value into


22 STOEL the matrix. If flag 01 is clear, then also
23 Fs? @1 store the y-value.
24 GTO a1
23 J+
26 REY
=rd STOEL
28 ROV

29 LEL &1 Lines 29-31: View the LLIST matrix.


28 VIEW "ZLISTY
31 RTHN

a2 LBL @2 Lines 32—-42: Create the 1- or 2-


33 1 column matrix BLIST.
34 Fs? at
35 1
36 FC? @1
37 2
28 DIM “ELIZST"
29 #ER I
48 F+
41 R4
42 GTO a8

6: Statistics 177
43 LBL "LIST-" Lines 43— 53: Recall the element(s) in
44 SF 25 the last row of ZLIST to the X- (or X-
45 KEQ@ I and Y-) register(s).
46 FC? 25
47 RTN
48 J-

49 RCLEL
50 FS? B1
51 GTO @3
52 J_

53 RCLEL

o4 LBL 83 Lines 54 -57: Delete the last row of


35 DELR LLIST.
96 FS?C 25
37 GTO a1

58 LeL "cCLIST" Subroutine CLIST, lines 58 - 60: Clear


59 CcLy "ZLIST" the variable ©LIST.
68 RTH

61 LEL I Subroutine I, lines 61—63: Index


62 INDEX "ZELIST" LLIST.
63 RTH

64 EMND

178 6: Statistics
To use LIST:

1. For two-variable statistics (x- and y-values), clear flag 01. For one-
variable statistics (x-values only), set flag 01; the program makes
TLIST a 1-column matrix.
2. Pross (XEQ) [LIST.

3. Clear ZLIST by pressing £


4. Enter data pairs by pressing y-value x-value LIST# (for
each data pair).

Example: Accumulating Statistical Data in a Matrix. Use pro-


gram LIST to accumulate the following x-y data pairs in the matrix BLIST.
Then find the mean of the x- and y-values.

x-value y-value
6 2
5 3
9 5
12 6
21 11
7 4

Clearflag 01 for two-variable statistics. Start LIST.


B(FCAGS) 0 %: 0, 0000
IRN2INNAV

Clear XLIST.
x: 8. 8000
(LisTeuist=-f|| JCLIET)

6: Statistics 179
Enter the first data pair.
2 6LIST+ ZLIST=[ 1x2 Matrix ]
ISERRY[WETT INNY

Keyin the next data pair.


3 S5LIST+ ZLIST=L 2x2 Matrix 1]
NEZIVEEII N D

Key in the remaining data pairs (the keystrokes are not shown here). Exit
from LIST.
EXIT

Clear the summation registers. Recall ZLIST to the X-register.


BCLEAR) cCL= v 7.0000
[RCL) ZLIST x: [ 6x2 Matrix 1

Accumulate the data from LLIST into the summation registers.


Y: 7. 0000
x: 6.0000

Find the mean ofthe x- and y-values.


WSTAT) HERH x: 10. 0000
3o0tHEnNTbtNSENCFIT

The mean of the x-values is 10. Check the mean of the y-values.
(xxy] x: 5. 1667
E+ 3Ut4 [MERNTWMN]Z0EVCRIT

Exit from the STAT menu.

EXIT v: 16,8040
X: 9. 1667

180 6: Statistics
Redimensioning the £L/ST Matrix to nm x 2. In the previous exam-
ple, you used LIST to create a 6 x 2 matrix ELIST. You then recalled
SIIST to the X-register, and executed £+ to accumulate the x-y data
pairs from the matrix into the summation registers. To execute L+ when a
matrix is in the X-register, that matrix must have a column dimension equal
(by
to 2. If, for example, you use LIST to create an n X 1 matrix ZLIST
setting flag 01), you must redimen sion it before executi ng £+,

The following program, ZFORM,redimensions any matrix BLIST of


dimension 7 x m to dimension nm x 2. All of the elements in the input
with 0’s
matrix are moved to the second column. Thefirst column is filled
(zeros).
88 { 58-Bute Pram 3
91 LBL "ZFORM"

az 2
A3 RCL “ELIST"
a4 DIM?
A5 X
86 DIM “"ZLIST"
@7 INDEX "ZELIST"
ag 1
a9 ENTER
18 2
11 ROR
12 RCL "ZELIST"
13 TRANS
14 STO "ZELIST"

15 END

Filling Column Two of £L/ST with Evenly Spaced Integers.


You may wantto fit a linear or exponential curve to a set of one-variable
statistical data. Thefollowing program, XVALS,fills the first column of
the £LIST matrix with integers 1,2, 3, .., n. Il ELIST is a 1-column
matrix, XVALS automatically creates the new column.

6: Statistics 181
Program: Comments:
80 { 46~Byte Pram
a1 LBL "XVALS"

82 RCL "ZLIST" Lines 02-08: Recall ELIST. If it is a


@z DIM? 1-column matrix, execute ZFORM to
64 1 make it a 2-column matrix. Then index
g5 - it.
HE X£@7
a7 HER "ZFORM"
88 IMDEX “ZELIST"

B9 LBL a8 Lines 9-14: Fill column 1 with


18 RCLIJ integers 1, 2, 3,..., n. Continue to the
11 H<>y end of the column.
12 +
12 FC? 7é
14 GTO B4

15 END

Using the Summation-Coefficient Functions


(X+, ¥-, and CLY)) in Programs

The program MLRin this section uses the £+ function and matrix opera-
tionsto calculate a multiple linear regression for three independent vari-
ables.

For a set of data points { (x;,y;,2;,4),i =1,2,..,n },MLR fits a


linear equation of the form

t=a+bx+cy+dz

bythe least squares method.

182 6: Statistics
Regression coefficients a, b, c, and d are calculated by solving the follow-
ing set of equations.
n &t Wi &t
a 21',-

o D)2 Bxy; Exz b x4


o Iy D) Eyiz ¢ Lyt
% Ly Sny D@)?| U Zz
The coefficient of determination R?2is defined as

alt; + bIx; t; + cTy; t; +dDz t; - 1 )?


R2 = n

23 - "17(2‘.')2

Hereis a flowchart for MLR.

6: Statistics 183
sansnels ;9 181
Caw Cwey Ca
1
SH31S193Y
1
13S viva 1Sv13HL
!
|'44302 IVOILSILVLS
NOILVWWNS TV LOVHLENS OL—-X ANV| 3Lvadn OL-+X ANV
Hv370 Ol X110 3sn HLIHV MOVLS 3sn HLIHV XOV.LS 38N
€D &
&
@ [ eroax|| zroax|| rroax ]
uO1VOl
”3101/ II_ZII 44"'3//
€A €A 2 AN b ATN
1NdNI 404 dOLS ANV
NN3W NIYW AV1dSIa
f
SAIN NN3INW
NIVN @1ing
00
147
13S viva M3aN
HLIM SIN3IDI44300
IvOILSILVYLS 31vadn
01 00 ODv14 HY31D
A
XLYW ‘G1VIN YiVW
S30I14H1VW a1ing
HIN
FILL MATA, MATB
WITH SUMMATION
COEFFICIENTS

v
CALCULATE MATX
AND R2

y
BUILD SOLUTION
MENU

DISPLAY SOLUTION MENU


AND WAIT FOR DATA INPUT
KEYE@
¢KEY1 ¢KEY2 lKEYS lKEY4 lKEYS KEY 6 N2
IDI
"R2" "T?"
DISPLAY
R2
LOAD ALPHA REGISTER
WITH VARIABLE NAME CALCULATE
AND X-REGISTER WITH AND DISPLAY T
CORRESPONDING COLUMN
NUMBER OF MATX

y
INDEX MATX AND
DISPLAY VARIABLE

6: Statistics 185
To key in MLR:

1. Assign functions —, 1, +—, |, 1- and J+ to the CUSTOM menu


before program entry.
2. Create variables MATA, MATB, MATX, R2, and T before program
entry.

Here is an annotated listing of the program.

Program: Comments:
B8 { 460-Bute Prgm 2}
81 LBL "MLR"

82 REALRES Lines 02-12: Set to calculate real


@3 4 results only. Create 4 x 1 matrices
@4 ENTER MATX and MATB. Create 4 x4
@5 1 matrix MATA. Clear flag 00 (set to
86 DIM "MATX" L+ mode). Set to Linear (statistics)
a7 DIM "MATB" mode (calculate six summation
a8 4 cocfficients).
B9 ENTER
16 DIM "MATA"
11 CF B8
12 LINZ

13 LBL @8 Lines 13-27: Bui


14 CF 21 menu keys @8
15 CLMENU ;, and
16 "Z+"
17 KEY 1 XKE@ 11
18 llz_ll

19 KEY 2 XE@ 12
28 "CL=z"
21 KEY 3 XEQ 13
22 "CALc"
23 KEY 6 GTO 14
24 MENU
25 CLD
26 STOP
27 GTO BB

186 6: Statistics
28 LBL 11 Subroutine 11, lines 28 - 58: Emulate
29 RCLx ST I+ (or Z- if flag 00 set) to update the
30 FS? 88 following summation coefficients: Ixz
31 +/- in Rys, Bt in Ry5, Tyz in Ryy, Tyt in
32 STO+ 13 R 6. Execute £+ to update the follow-
33 CLX ing coefficients: £z in Ry, 22 in R g,
34 LLASTX Tt in Rog, ¥2in Ry, X2t in Ry, 1 in
35 RCLx ST Ry
36 FS? @8
57 +/=
28 STO+ 15
29 CLX
49 LASTH
41 E+
42 RCL® ST
43 FS? @8
44 +-
45 STO+ 14
46 CLX
47 LASTH
48 RCLx ST
]

49 FS? ag
58 +/—
51 STO+ 16
52 CLX
53 LASTX
54 R+
55 ZREG 87
56 FS? 68
57 RTH
58 Z+

G: Statistics 187
59 LBL 81 Subroutine 01, lines 59 - 68; Execute
e CLX I+ to update the following
61 LASTX coefficients: £x in Ro;, Zx?in Rgy, Ty
62 R+ in Reg, y? in Ry, Ty in Reg, and 1 in
63 R+ R . (Note that n is also calculated in
64 ZREG 81 subroutine 11.)
65 FS?C B84a
66 RTH
67 Z+
£3 RTH

69 LBL 12 Subroutine 12, lines 69-75: Emulate


va SF b@ L~ (set flag 00) to update the
71 ®ER 11 coefficients calculated in subroutine
re 2_
11. Execute - to update the remain-
73 XER @1 ing coefficients.
4 )

7S RTH

e LBL 13 Subroutine 13, lines 76 - 83: Execute


77 ZREG 11 CLX to clear all defined summation
8 CLZ registers.
79 ZREG @7
€8 CLZ
81 ZREG a1
82 CL=
83 RTH

g4 LBL 14 Lines 84 - 147, calculation of


85 "Calculatinag" coefficients a, b, ¢, d, and R? : Fill
B AVIEN MATA with x, y, z summation
a7 a coefficients. Fill MATB with t summa-
83 STOxX "MATH" tion coefficients. Calculate MATX
a9 IHDEY "MATA" (MATB + MATA). Calculate R2
94 J+
21 RCL 81
22 +
932 RCL 83

188 6: Statistics
94 »
95 RCL 87
96 +
97 RCL 13
98 €
99 RCL @5
109 +
181 J+
1862 RCL 14
183 +
194 RCL "MATA"
185 TRAHNS
186 STO+ "MATA"
197 RCL 88
168 +
169 «
118 RCL 84
111 +
112 «
113 RCL 82
114 +
115 <
116 RCL RA6
117 STOEL
112 INDEX “MATE"
119 RCL a9
128 4+
121 RCL 15
122 «
123 RCL 16
124 4
125 RCL 11
126 STOEL
127 RCL "MATE"
128 RCL+ "MATA"
129 STO "MATH®
128 LASTH
131 TRANS
132 KOV
133 x
134 FHRM

6: Statistics 189
135 RCL 89
136 X+2
137 RCL+ @6
138 -
139 LASTX
148 RCL 1@
141 X<>Y
142 -
142 +
144 STO "R2"
145 CLD
146 FS? 53
147 SF 21

1428 LBL B2 Lines 148 - 164: Build and display the


143 "R" solution menu,
156 KEY 1 HER
[
o

151 "g"
152 KEY 2 HER &
[
P

152 "C»
154 KEY KER :
03

M
L)

155 "D
156 KEY 4 EQ &
P
£

157 “"R2"
153 KEY 5 XER
T
n

159 »T?"
160 KEY & RER
[
T

161 KEY 9 GTO


.,.
L
e
)

162 MENU
163 STOP
164 GTO @2

165 LBL 21 Subroutines 21-25, lines 165-192:


fd

166 1 Display the calculated coefficientsa,


167 "a" b, c, d, and R2, If PRON has been exe-
168 GTO B3 cuted, print the coefficients (lines 187
P I
M

169 LBL and 191).


178 2
171 "b"

190 6: Statistics
ive GTO 03
173 LBL 23
174 3
175 IICII
176 GTO B3
177 LBL 24
178 4
179 Ildll
120 LBL 83
181 1
182 IHDEX "MATR"
183 STOIJ
184 RCLEL
185 =
186 ARCL ST X
187 AVIEM
188 RTN
189 LBL 25
1909 RCL "R2"
191 VIEW "R2"
192 RTN

192 LBL 26 Subroutine 26, lines 193 -205: Fore-


194 INDEX "MATH" cast T based on the calculated
193 KEQ 94 coefficients a, b, ¢, and d. Display T
196 KEG 94 and, if PRON has been executed,print
197 XEQ 84 T.
198 +

199 +

288 I_

201 RCLEL
282 o+

283 sTO "T"


284 VIEW "T*
285 RTH

6: Statistics 191
286 LBL a4 Subroutine 04, lines 206 -210: Calcu-
287 I- late terms bx,cy, and dz.
288 RCLEL
209 RCLx ST T
218 RTH

211 END

To use MLR:

1. Press XEQ) MLR


2. Press .CLE to clear the summation registers.
3. Enter each dataset, using the keystroke sequence t-value [ENTER
z-value [ENTER] y-value [ENTER) x-value = T+.
4. Press CHLC..
S. Press the corresponding menu keys to see the valuesof variables a,
b,c,d, and R2,
6. To forecast T, use the keystroke sequence Z-value [ENTER] y-value
ENTER] x-value .
7. To return to the main menu, press [EXIT).

Example: A Linear Regression For Three Independent Vari-


ables. Find the regression equation for the following set of data.

if112|3|4]|5
x| 71 1]11|n| 7
v |25 29|56 |31]52
z| 6|15| 8| 8| 6
t, [60|52|20]47 |33

.
e MLR
Execut

192 6: Statistics
Clear the summation registers. Enter the first data set, starting with the
t-value.

R] 6 (ENTER] 25 [ENTER]

Enter the second data set.


52 [ENTER] 15 [ENTER] 29 [ENTER]
-

Enter the remaining data sets (the keystrokes are not shown here). Now
calculate the regression coefficients and the coefficient of determination.
HLC x: 8. 9989
Lo&¢oJr2 Ty

Check the value of a.

Check the value of b.

Check the value of c.

Check the value of d.

d=-1.3395
o & ¢o [rRa |71y

Check the value of R2.

6: Statistics 193
Calculate T (the forecasted value of ¢ given values for x, y, and z). Use the
values from data set #4.
8 [ENTER] 31 [ENTER] 11
T?

(The actual value of ¢ in data set #4 is 47.) Return to the main menu and
clearthe statistics registers for new data.
cL2

Exit from MLR,

Curve Fitting in Programs


The curvefitting functions FCSTX, FCSTY, SLOPE, YINT, CORR,
LINF, LOGF, EXPF, PWRF, and BEST are programmable.

Refer to program PFIT on pages 218 —222 in the following chapter. PFIT
uses FCSTY in line 89 to forecast a y-value based on the currently
selected statistical model for each of 110 x-values. A curve is then plotted
with the 110 data pairs.

194 6: Statistics
Graphics and Plotting
The following topics are coveredin this chapter:

m Building graphics patterns.


s Multifunction plotting,
m Plottingstatistical data from a complex matrix.

Graphics
The program HPLOGO in this section uses the XTOA and AGRAPH
functions to build the Hewlett-Packard company logo in the center of the
display.

To key in HPLOGO:

1. Assign the functions XTOA, CLA, ARCL, and XEQ to the


CUSTOM menu.
2. Create the variable BLOCK.

7: Graphics and Plotting 195


Here is the annotated listing.

Program: Comments:
08 { 441-Byte Pram >
at LBL "HPLOGO"

0z CLLCD Lines 02-04: Clear the display for


a3 CF =24 graphics. Clear flags 34 and 35 so that
a4 CF 35 graphics placed in the display with
AGRAPH are merged with any
graphics already in the display. (The
top and bottom halves of the logo are
built separately and merged in the
display.)
as ®EQ “"TOP" Lines 05—-09: Call subroutine TOP to
a6 1 build the top half of the logo. Then
ar ENTER display the top half of the logo, start-
a2 448 ing at pixel (1, 40).
69 AGRAPH

18 ®ER "BOT" Lines 10-15: Call subroutine BOT to


11 9 build the bottom half of the logo.
12 ENTER Then display the bottom half of the
13 44 logo, starting at pixel (9, 40).
14 AGRAFH
15 RTH

16 LEL “TOpP" Subroutine TOP,lines 16—91: Build


17 CLA the Alpha string that represents the
18 233 top half of the logo. (Begin by building
19 ®TOR the Alphastring that represents an 8 X
2a »TOR 6 block of on-pixels and storing that
21 ®TOR string in the variable BLOCK.)
22 ®TOA
23 “TOA
24 ®TOAR
25 ASTO "BLOCK"
26 CLA
27 254

196 7: Graphics and Plotting


28 XTOR
29 ARCL "BLOCK"
30 2595
31 KTOA
32 63
33 XTOA
34 15
35 XTOA
36
37 XTORA
38 XTOA
39
40 XTORA
41
42 XTOA
43 129
44 KTORA
45 224
46 XTOA
47 120
48 XTOR
49 62
Sa XTOA
51 39
52 XTOA
53 161
54 XTOR
55 224
56 KTOA
57 B
58 XTOA
59
66 ATOAR
61
62 XTOR
63 129
64 »TOR
65 225
66 XTOAR

7: Graphics and Plotting 197


67 97
€8 XKTOA
€9 33
70 XTOAR
71 XTOA
72 35
73 XTOA
74 163
7S XTOR
76 231
77 KTOA
78 1.3
79 KTORA
88 15
81 XTOR
8z 31
82 KTOR
84 62
85 XTOA
86 ARCL "BLOCK"
8¢ 255
g2 KTORA
29 254
98 XTOR
21 RTH

92 LLBL "BOT" Subroutine BOT,lines 92— 156: Build


93 CLA the Alpha string that represents the
94 127 bottom half of the logo.
93 XTOA
96 ARCL “BLOCK"
9¥ 255
98 XTOR
29 252
188 XTOAR
181 248
182 XTOA
183 224
184 XTOA

198 7: Graphics and Plotting


661 Sumoid pue saydwiy) 2
tec2 E€p1
HOL1X el
se2 +1
HoLX ev1
661 6€E1
HO1¥X 8€1
861 281
HOLX 9e1
HO1X GET
HoLX reT
2e1 gel
HOLX 2El
I€T
HOLX Bel
621
HolX 8ct
ag 221
HOLX 921
6ec1 sel
HOL1X ¥21
ree ezt
HOLX 2ct
621 121
HOLX ac1
611
HOLX 811
211
BOLX art
HOLX ST
P11
HOLX ET1
6cl 211
HoLX 111
Ssel a1l
HOL1X 601
86l 881
HolX 481
261 901
HOLX cat
144 XTOR
145 248
145 XTOA
147 248
145 XTOA
149 252
1568 XKTOR
151 ARCL "BLOCKE"
152 255
152 XKTOA
154 127
155 XTOR
155 RTH

157 EHD

Example: Building a Logo. Display the Hewlett-Packard logo. If you


have a printer, modify HPLOGO to print the logo. Then printit.

Execute HPLOGO.

2
Insert the instruction PRLCD afterline 14 of HPLOGO to print the logo.
B(PRGM] B(GTO] (] 14 v: 9, 0000
(V] FRLCD [EXIT x: 40,0000
Print the logo. 4 x
BERINT] (4] FOH D
HFLO

Using Binary Data to Build a Graphics Pattern. To build the


logoin the previous example, you had to calculate the column print
number for each of 91 columns — a time-consuming effort. The following
program, BINDATA, calculates the column print number when you input
the equivalent sequence of binary numbers in a column pattern.

200 7: Graphics and Plotting


Program: Comments:

(5%} { 68-Byte Pram


a1 LBL "BIMDATR"

az CF 34 Lines 02-04; Clear flags 34 and 35.


a3 CF 35 Set the calculator to Binary mode.
a4 BINNM

a5 LBL B0 Lines 05-15: Clear the X-register and


as CLX suspend program execution for binary
a? STOP data entry (lines 06—07). Build an
83 Alphastring of five spaces (line 08).
B89 126 Testif the binary data (converted to
18 BnE>Y decimal form) is greater than 126. If
11 YT 50, go to label 01. If not, enclose the
12 GTO 81 corresponding HP-42S Alpha charac-
13 ter in quotes and append two spaces
14 “XTOR to the Alpha register.
15 }_ nn n

1g LEL &1 Lines 16 -25: Append the number in


17 RIFP the X-register (the decimal equivalent
18 AYIEW of the binary data) to the Alpha regis-
19 CLA ter and display the current contents of
28 wTORA the Alpha register (lines 17-18). (The
21 1 Alpharegister contains the decimal
22 ENTER number equivalent ofthe binary data.
23 &8 If that numberis less than 128, the
24 AGRAFH Alpha register also contains the
25 GTO @\ corresponding HP-42S character,
enclosed in quotes). Build the
equivalent column pattern and display
it, beginning at pixel (1, 66) (lines
20-24). Return to label 00 for the
next data entry (line 25).
26 EHL

7: Graphics and Plotting 201


To use BINDATA:

1. An on-pixel has value 1. An off-pixel has value 0.


2. Enter digits beginning at the bottom ofthe column.
3. If, for example, you enter only six digits, the bottom two digits are
interpreted to be zeros.
4. Press after data entry to see the calculation. After the calcula-
tion is displayed, simply key in the next sequence of numbers when
you are ready.

Example: Using Binary Data to Build a Logo. Columns 1618 of


the Hewlett-Packard logo in the previous example have the following pixel
patterns.

O 0O DO LastDigitEntered
O O nm
O O =n
O B =nu
O B N
H B B
m B 0O
M O 0O FistDigit Entered
Column# 16 17 18

Use BINDATA to calculate the column print number for each column.

Start the program.

Enter the binary data for column 16.


11100000 224

202 7: Graphics and Plotting


The column print number for column 16 is 224. There is no equivalent
Alpha character. The column pattern is at the right of the display. Now
enter the binary data for column 17.
01111000 "x" 120

The column print numberfor column 17 is 120. The equivalent HP-42S


character is "x". (You can therefore either accumulate 120 in the X-
register and execute XTOA,or accumulate character "x" in the Alpha
register. The column pattern is at the right of the display. Enter the
binary data for column 18.
00111110 [R/S] " oe2 1

The column print numberfor column 18 is 62. The equivalent HP-428


Alpha characteris ">". Now exit from the program.
[EXIT] : 1.0060
;: 0. 00688

(Refer to the character table in your owner’s manual (appendix E) and


notethatfive of the first 127 characters cannot be typed from the HP-42S
keyboard. The character codes are 4, 6, 13, 27, and 30. Program
BINDATA shows you the character corresponding to each of these codes el
but because these characters cannot be typed, you must accumulate the
corresponding character code in the X-register and execute XTOA.)

Multifunction Plots
The program PLOT3 in this section enables you to plot up to three func-
tions concurrently on the HP 82240A Infrared Printer. It is based on the
program PLOTin the section "Example Programs” in chapter 10 of your
owner’s manual. As in PLOT, you supply to the program the name of the
routine that defines the function you wish to plot. However, in PLOTS3,
you can supply upto three routine names.

7: Graphics and Plotting 203


Hereis a flowchart for PLOT3.

&
PLOT3

USE VARIABLE MENU TO (YMIN, YMAX, AXS,


STORE PLOT PARAMETERS XMIN, XMAX, XINC)
v
INPUT FUNCTION
ROUTINE NAMES

v
PLOT HEADER INFO
AND INITIALIZE

v
SET INITIAL x-VALUE
LBL
00

CLEAR DISPLAY

Y
G NO
S

|{ABEL AXIS

YES
NO |DRAW AXIS
i(—’

204 7: Graphics and Plotting


l
OR EACH PIXEL ROW
1T0O 16

___.___._________________.________.)
FOR EACH FUNCTION
PRINT DISPLAY
EVALUATE f(x)
INCREMENT]
X-VALUE

v
PRINT FINAL
PLOT PIXEL

DISPLAY ~—=-(_NEXT FUNCTION

STOP

=——(NEXT PIXEL ROW

To key in PLOTS3: Create variables YMIN, YMAX, AXIS, XMIN,


XMAX, XINC, FCN1, FCN2, and FCN3 before program entry.

Here is an annotated listing of the program.

Program: Comments:
88 { 424-Bute Pram
A1 LEL “PLOTZ"

62 MYAR "YHMIHW® Lines 02-07: Declare the menu vari-


83 MYAR "YMAH" ables.
B4 MVAR “RAKISY
865 MVAR "EMINY
8& MVYAR "HMAN®
BY MVAR "HIHC"

7: Graphics and Plotting 205


a8 LBL A Lines 08 - 14: Display the menu and
89 VARMENU "PLOT3" suspend program execution for data
16 CF 24 input.
11 CF 35
12 CLA
12 STOP
14 EXITALL

15 "FCH1" Lines 15-20: Promptfor the function


16 XE® @7 names (the subroutine labels).
17 “FCH2"
183 ¥EQ @7
19 "FCH3"
28 HER 87

ADY Lines 21-43: Print the header infor-


B e B 0O 00 0D 00 00 00 03 Q0 0 0y T B P P T PRI R
0 = T N B 03 P o= 5 o0 00 ) b U] e 00 PO e

"Plot of:" mation. (In line 42, there are seven


FrA spaces in the Alpha string before
ADY YMAX.)
SF 12
RCL "FCH1"
HER B3
FCL "FCHz"
REQ 88
RCL "FCH2"
KER@ B8
ADY
CF 12
FREY "YHMIN"
PEM "YHARY
FRY "RXIS"
FEY "HMIN"
FEM "HMAR"
S FRENM "KIHC!
8 ALY
1 "« YMIN"
2 k" THAN +L"
2 PREA

206 7: Graphics and Plotting


44 130 Lines 44 —-48: Calculate the relative y-
45 RCL "YMAXR" value of one pixel.
46 RCL- "YMIH"
47
48 STO 00

49 RCL "RKMIN" Lines 49 - 50: Store the first x-value.


58 STDO 81

3 LBL @8 Lines 51— 58: Clear the display. If flag


s52 CLLCD 00 is clear, label the x-axis. If flag 01 is
53 FC? @0 clear, draw an axis. Build a loop
54 XEQ B85 counter corresponding to the 16 rows
95 FC? 61 in the display.
o6 XEQ @86
o7 1.016
52 STO @2

59 LEL @81 Lines 59-61: Build a loop counter for


68 49,651 the three possible functions. (The
&1 STO @z character codes for characters "1°, "2",
and "3" are 49, 50, and 51 respectively.
Routine 02 uses these numbers to
create the variables.)
&2 LBL @2 Lines 62-83: Create the Alpha strings
62 "FCH" FCN1, FCN2, and FCN3 successively.
64 RCL A3 Call each string to the X-register, then
&5 XTOA recall to the X-register the variable
66 ASTO ST # that matchesthat string. Test if the
&7 RCL IMD ST X variable has an Alpha string (a func-
65 STR? tion program name) in it (lines 62 -
&9 ®EQ B4 68). If so, plot a pixel for each func-
78 ISG a3 tion. Incrementthe x-value.If the plot
7l GTO @z is complete (ifx-value > XMAX), go
e RCL "XIHC® to label 03. If the current display is
73 16 complete (if rows 1-16 are filled),
74 then print the display and start a new
73 STO+ a1 one.

7: Graphics and Plotting 207


76 RCL "XMAX"
7 RCL @1
73 R>y¥?
v9 GTO @3
86 ISG @2
81 GTO a1
82 PRLCD
83 GTO @9

24 LBL B3 Lines 84 -87: Print the final display


85 PRLCD and stop. (Line 87 enables you to res-
86 RTN tart the program by pressing [R/S).)
87 GTO A

88 LBL 94 Subroutine 04, lines 88— 101: Evaluate


89 RCL @1 the function at x and plot the
L ¥EQ IND ST ¥ appropriate pixel.
31 SF 24
92 RCL- "YMIN"
93 RCLXx @9
94 1
s +
96 CF 24
97 RCL 82
98 alcy
99 n>a7
188 PIXEL
181 RTH

162 LBL @5 Subroutine 05, lines 102-108: Label


183 CF 21 the x-axis.
184 CLA
183 ARCL &1
1865 AYIEW
187 SF 21
183 ETH

7: Graphics and Plotting


189 LBL 056 Subroutine 06, lines 109~ 123: Draw
118 1 the axis. (In line 120, the Alpha string
111 RCL "AXIS" is five "multiply” characters: press
112 RCL- "YMIN" BACPHA] (x] ] (x] (x] B [ENTER].)
113 RCLX 88
114 +s-
115 1
116
117 PIRXEL
118 +/-
119 2
1208
121 MR K"
122 AGRAFH
123 RTH

124 LBL @7 Lines 124-146: Promptfor an Alpha


125 CF 21 string (function name). If the variable
12¢ ASTO ST L already contains an Alpha string, that
127 CLx string is recalled to the Alpharegister
128 AVIEM as the default.
129 FSE
130 CLA
131 FS? 55
132 SF 21
133 SF 25
124 RCL IND ST
135 CF 25
126 STR?
137 ARCL ST ¥
132 AOH
132 CLD
148 STOP
141 ACFF
142 ALEHG
143 R=QAT?
144 ASTO ST A

7: Graphics and Plotting 209


145 STO IND S

£
-

r
146 RTH

147 LBL @8 Subroutine 08, lines 147 - 153: Print


142 CLA the function names.
STR?
—_ . —_
noan Fcs
0T e b 0

ARCL ST ¥
STR?
FRA
ETH

EHD

an
£

To use PLOT3:

Execute PRON and turn on your Infrared Printer.


wh
.

2. Write a routine for each function that you wantto plot. The current
x-valueis in the X-register when the program calls the function rou-
tines. The routines need not recall the current x-valueto the X-
register.
3. Setthe display format to ALL.
4. Start the program (press FLOTS).
5. Supply the plot parameters. For example, specify 20 for YMIN by
pressing 20 “WHIH .
6. After supplying values for the plot parameters, press [R/S].
&. As prompted, store the name of each function routine in a
function variable. For example, to supply the name TAN for
FCNI, press TAN at the first prompt.
b. If you have already supplied a routine name for a function
variable, that nameis displayed at the prompt. If you want to
leave that namein the variable, simply press [R/S].
¢. If you wantto plot only two functions, supply names for only
two variables. Leave the Alpharegister clear for the third
variable (just press when prompted). If a nameis
displayed for the third variable, press to clear the Alpha
register, then press [R/S]. If you want to plot only one func-
tion, supply a name for only one variable and leave the Alpha
register clear (or clear it) for the other two variables.

210 7: Graphics and Plotting


the fol-
Example: Plotting Multiple Functions. Use PLOT3 to plot
lowing functions.
1. y = sinx
2. y = 0.35(Inx) (cosx)

First, write routines to describe the functions.


Ge { 9-Bute Prom
@1 LBL “"SINE"
Bz SIN
62 END

Program: Comments:

pa { 27-Byte Pram 3 Lines 04 —05: Ensurethat the program


@1 LEL "LHCOSY does not attempt to execute In (0).
gz cos
a3 LASTH
A4 @.860)
(S
ae LM
67 B8.33
Ba
863 x
18 EMD

Set the Display format to ALL. Execute PRON. Clear flags 00 and 01 to
draw and labelthe x-axis. Start PLOT3.
)
PRINT) &) FOH
|m AI II TRAT
lm Im

Plot y-values between —3 and 3, and set the axis aty = 0.


AXI1S=8
I TTTPAT

7: Graphics and Plotting 211


Plot x-values between 0 and 720 in increments of 60 per display.
|XINC=60 |
TNKSRWCRRFBTNSTAT

Supply the program name SINE forthe first function variable.


SINE SINE_
TRWLAT [NDP[RETUR]2

Supply the program name LNCOSforthe second function variable.


LNCOS LNCOS_
LTTSITTTes(T(R

212 7: Graphics and Plotting


Leave the Alpha register clear for the third function variable and start the
plot. The printer output is shown here.
R/5) B/S)

J
Plot of:

om
- DD T
nz

OTO®WW
==

OOXIZIUXCZ
nunuwan

-
[=aAt]
YMAX 2

X
;



"

Exit from the program. Return the display format to FIX 4.


EXIT v: 720.6080
B0isP) ENTER x: 723.7500

7: Graphics and Plotting 213


Plotting Data from a Complex Matrix

In previous programs, you have used:


s PIXEL to turn on individual pixels in the display. You specify the
pixel number in the X- and Y-registers (row number in Y and column
number in X).
m AGRAPH to display a graphics pattern. You specify the location of
the pattern in the display by placing a pixel numberin the X- and Y-
registers (row number in Y and column numberin X).

PIXEL and AGRAPH operate on the numbers in the X- and Y-registers.

Theefficiency of these functions is enhanced by enabling them to operate


on a complex matrix in the X-register, where each element of the complex
matrix has the form

x-value + iy-value

When such a matrix is in the X-register, PIXEL turns on each pixel in the
displayas specified by the elements in the matrix. For example, consider
the following complex matrix.

1+i10 5+i20
10+i30 16+i40

If you execute PIXEL when this matrix is in the X-register, pixels (1, 10),
(5, 20), (10, 30), and (16, 40) are each turned on.

214 7: Graphics and Plotting


n thatis encoded in the
Similarly, AGRAPH places the graphics patter
by the elements
Alpha register at each position in the display as specified
in the matrix,
form of the
Note that PIXEL and AGRAPH operate on the rectangular
rs into the compl ex matrix , set the
complex matrix. Before entering numbe
angular mode to Rectangular.
from the
The program PFIT in this section plotsthe individual data pairs
a curve to that data
real n X 2 matrix in the X-register,then fits and plots
PFIT create s one compl ex
using the currently selected statistical model.
data point with a " +" charac -
matrix and executes AGRAPH to mark each
and execut es PIXEL to
ter. PFIT then creates a second complex matrix
plot the forecasted curve.

7: Graphics and Plotling 215


PFIT

STORE THE (DATA)


MATRIX IN DATAMTX

v
XEQ MM TO FIND MIN
AND MAX VALUES, THEN
CALCULATE SCALING
FACTORS

v
PLOT
AXES

v
STORE DATA FROM
DATAMTX IN SUMMATION
REGISTERS

v
BUILD PLOTTING
MARKER

216 7: Graphics and Plotting


¥
SCALE EACH
x AND y VALUE

v
IC?EATE COMPLEX MATRIX
OF x AND y VALUES

PLOT THE DATA POINTS

CREATE 1 X 22 TEMPORARY
MATRIX AND FILL IT WITH
x -VALUES 1-22

FOR EACH SET 1-6


OF 22 x -VALUES
0 [FOReCAsT 22 y VALUES |
|
1
PRINT THE |
!

[ SCALE EACH x, y -VALUE|


|
DISPLAY i
|
!
|
:

i COMBINE x, y MATRICES
|
|
|
INTO A COMPLEX MATRIX
v
l
|
|
|
' PLOT 22 PIXELS
(DRAW THE CURVE)

To key in PFIT:

1. Create variable DATAMTX before program entry.


2. Create label MM when you begin program entry.

7: Graphics and Plotting 217


Here is an annotated listing of PFIT.

Program: Comments:
B8 { 295-Byte Prgm 3
61 LBL "PFIT"

6z CF 34 Lines 02-06: Clear flags 34 and 35.


83 CF 35 Store the matrix thatis in the X- regis-
04 RECT ter in DATAMTX and index
835 STO "DATAMTX" DATAMTX,
06 INDEX "DATAMTX"

a7 XEQ@ "MM" Lines 07-13: Call subroutine MM to


88 STO B2 find the minimum and maximum x-
B9 - values. Then calculate the x-value scal-
18 128 ing factor.
11 +
12 STO 61
13 STO+ @2

14 XKEQ “MM" Lines 14 -25: Call subroutine MM to


15 XKOY find the minimum and maximum y-
16 STO 94 values. Then calculate the y-value scal-
17 - ing factor.
18 13
19 XY
28 +
21 STO @3
22 STOx 94
23 2
24 STO- 94
25 STO- B2

218 7: Graphics and Plotting


26 CLLCD Lines 26-33: Plot the axes.
27 RCL ©4
28 ®>87?
29 RCL- ST X
28 RCL B2
31 R>a?
32 CLX
33 PIXEL

34 ZREG 11 Lines 34-37: Store the data in


35 CLE DATAMTX into the summation regis-
36 RCL "DRTAMTX" ters.
ar =+

35 CLA Lines 38— 44: Build the "+" character


39 2 (used to mark each data point in the
40 XTOA plot).
41 7
42 XTOA
43 BEY
44 ®TOA

45 RCL "DATAMTX" Lines 45-55: Make the matrix 2 xn


46 TRAMS and index it (lines 45-48). Make two
47 STO "DATAMTR" 1 x n matrices, where the matrix in the
48 INDEX "DATAMTR" X- registeris the x-values, and the
49 DINM? matrix in DATAMTX is the y- values
S5a 1 (lines 49-53). Convert the x-values to
51 B>y screen coordinates for plotting (lines
32 GETHM 54-56).
33 DELR
54 RCL+ 81
53 RCL- B2

7: Graphics and Plotting 219


56 RCL "DATAMTX" Lines 56 -59: Convert the y-values to
rd RCLx @832 screen coordinates (lines 56— 58).
S2 RCL- @4 Convert the matrices in X and Y to
59 COMPLEX one complex matrix in X, each ele-
ment of which is: x-value + iy-value
(line 57).
&4 1 Lines 60—-64: Subtract 1 + i1 from
61 EHTER each value (to set the center of the "+"
&2 COMPLEX character at the data point) (lines
63 60-63). Place the center of the "+" at
&4 AGRAFH the coordinates defined by each ele-
ment of the matrix (plot the data
points) (line 64).
&3 RCL "REGS" Lines 65-69: Recall the registers
€6 1 matrix to the X-register, and redimen-
&7 ENTER sion it to a 1 x 22 temporary matrix.
&8 22
&3 LIM "REGS™

7a 21 Lines 70-75: Fill the temporary


71 LEL &1 matrix with values 0 through 21.
va STO IND 57 X
72 DSE ST ¥
74 GTO 81
7S STO @@

TE Rt Lines 76— 80: Store the data from the


7 RCL "REGS™ registers back into REGS,then clear
72 RnOERY the X-register.
e STD "REGS™
28 CL=X

220 7: Graphics and Plotting


81 Lines 81 —84: Establish a loop counter
82 REY 6.00000 in the Y-register. Change the
a3 values in the temporary matrix to 1
84 through 22. (These values represent
thefirst set of 22 x-values.)

85 LBL 82 Lines 85-102: Forecast y-valuesfor a


g6 ENTER set of 22 x-values, make a complex
87 RCL+ @2 matrix ofx-y data pairs, and plot each
88 RCLx @81 data pair. Repeatfor five more sets of
89 FCSTY x-values.
30 RCLX B3
91 RCL- 64
92 COMPLER
93 PIXEL
94 COMFPLEA
a5 R+
6 22
av +
98 DSE ST ¥
99 GTO 62
180 PRLCD
181 CLY "DRTAMT=R"
182 RTH

183 LBL "Mm® Subroutine MM,lines 103 -120: Find


184 RCLEL the maximum and minimum elements
185 ENTER of one column of the matrix for scal-
18¢ LBL 8% ing. Atthestart of the subroutine, the
187 I+ matrix DATAMTX is indexed with the
182 F3? 76 index pointerat the top of a column.
189 RTH At the end of the subroutine, the
110 RCLEL minimum element of the column is in
111 oy X, the maximum element is in Y, and
112 By the index pointeris at the top of the
113 R next column.
114 R+
115 wov?

7: Graphics and Plotting 221


116 XY
117 Re
118 RCL ST 2
119 GTO B89
120 RTH

121 END

To use PFIT:

1. Select a statistical model. For example, press M[STAT] (CF1T:

2. Place a 2-column real matrix of data pairs in the X-register.


3. Press PFIT

Example: Plotting Data from a Compression Process and


Fitting a Power Curve to the Data. Many compression processes
can be correlated using the power curve

P =gVt

where:

P is the pressure.
V is the volume.
~b is the polytropic constant.

Enter the following pressure-volume data in the ELIST matrix.


Then use PFIT to plot the data and to plot a power curveto the data.

VP
10 210
30 40
50 12
70| 9
% 6.8

222 7: Graphics and Plotting


Execute program LIST. (If you've deleted the program, you need to keyit in
again. Thelisting is in section "List Statistics" in chapter 6.)
x: 8, 0000
[ER(W)NS

ZLIST=L S5x2 Matrix 1


LeveJust-f—[[letizTd
10LI8T+
40 30LIST+
12 50L1ST+
9 70L18T+
6.8 9 LISTH

Exit from LIST. Recall ZLIST to the X-register.


. 90,0000 .
BIIRT x: [ 9x2 Matrix 1]

Setthe statistical model to a powerfit. Execute PRON if you have a


printer. Execute PFIT.
BETAT
(BPRINT
.
B(TOPFCN
Exit from PFIT. Check the correlation coefficient for the data.

EXIT x: ~0.9939
FLiTyd

The correlation coefficient is —0.9939. Check the value of -b.

eLOPE %: -1.6152

The value of —b is —1.6252. Exit from the STAT menu.

EXIT] [EXIT v: -8.9939


x: ~1.6152

7: Graphics and Plotting 223


Index

Special Characters addressing


2+ function AGRAPH function
emulating in LIST program, 176 in HPLOGO program, 195
in programs,182 operates on complex matrices,
stores data from 2-column 213
matrix to summation regis- Algebraic solution. See Explicit
ters, 149, 181, 175 solutions
ZFORM program,listing of, 181 Angle of twist equation, 131, 125
LLIST matrix Approximating an integral that has
filling column 2 with evenly an infinite limit, 127 -130
spaced integers, 181 Asymptote, Solver results with,
in curve fitting example, 220 117
in LIST program, 176
redimensioning to nm x 2, 181
Ead Guess{=s) message, 120
A Binary data, building a graphics
ACC variable. See Accuracy factor pattern with, 200-203
Accuracy factor BINDATA program,listing of,
affects Integration calculation 201
time, 130 Branching, 21-39
definition, 134 conditional, 22 -25
effect on calculation time, 137 emulating a multirow menu with
in basic integration, 124 KEY GTO, 34-37
related to uncertainty of emulating a nested menu with
integration, 135 KEY GTO, 37-39
Addressing. See Indirect menu-controlled, 29-39
types of, 21

224 Index
C Controlled looping, 39-43
definition, 39
Calculation time DSE function in, 39
for an explicit solution, 100 GTO function in, 39
for Integration approximations, indirect addressing with, 43
129-130
INPUT IND in, 43
for the Solver, 99
ISG function in, 39
Integration conditions that pro- STO IND in, 44
long, 143145
XEQ IND in, 45
Case 1 and 2 (Solver) solutions, COORD program,listing of],
how to differentiate
158-160
between, 110
Coordinate transformations,
Case 1 (Solver) solution,
156-163
definition, 109
Correlation coefficient, 221
Case 2 (Solver) solution,
Curvefitting in programs, 194
definition, 109
CUSTOM menu, executing pro-
CIRCUIT program, listing of, 87
grams from, 73, 19
CLEAR program,listing of, 44
Coefficient matrix. See MATA
Column norm of a matrix, 151 D
Column sum of a matrix, 150 -151
Data input, prompting for in a
Complex numbers. See Emulating
program, 68, 15
the Solver; HP-41 programs,
Data output, displaying in a pro-
enhancing with HP-42S data
gram, 68, 16
types; Simultaneous equa-
Declaring variables. See MVAR
tions, complex-number
function
Compression process equation,
Directing the Solverto a realistic
220
solution, 8082
Conditional branching, 22 -25
Discontinuous function, Solver
based on a number test, 24
results with, 113-114
CONE program,listing of, 81
DISPL program
Conjugate of a complex matrix,
flowchart for, 40
151
listing of, 41
Constant matrix. See MATB
Displaying program results. See
Const ant ? message, 121
Data output
Constant velocity equation, 39
DSEfunction, in a controlled
Control flags, 47
definition, 47
loop, 39
flag 21 used to control VIEW
and AVIEW functions, 47,
16

Index 225
E trapping, 50
Error trapping, 49 -50
EIZ program,listing of, 89-90
Electricalcircuits. See Simultane- Examples, displays in the manual
may differ from your
ous Equations; Emulating
the Solver displays, 10
Executing a program
Emulating
from the CUSTOM menu, 73,
a multirow menu, 34-37
19
a nested menu, 37-39
from the program catalog, 19
T+ function, 176
the Solver, 86-91
with the XEQ function, 73, 19
END function, 15
Explicit solutions
calculation time, 100
Enhancing HP-41 programs, 67—
faster than iterative solutions, 92
76
for complex numbers, 88
Equation(s)
using with the Solver in pro-
angle of twist, 131, 12§
asymptote, 119 grams, 92 -100
Extremum message, 117
compression process, 220
constant acceleration due to
gravity, 83 F
constant velocity, 39
FCAT program
idealgas, 101, 78
flowchart for, 52
local flat region, 121
listing of, 53 -56
loop current, 166, 169, 163
uses programming concepts dis-
math error, 120
cussed in chapter 2, 51
multiple linear regression,
Finding more than one solution
182183
with the Solver, 83 -85
Ohm’s law, 86, 88
Flag 21
pole, 116
and PROFF function, 16
relative minimum, 118
and PRONfunction, 16
setting equal to O for the Solver,
effect on VIEW and AVIEW
105, 77
instructions, 47, 16
sine integral, 136
Flag 25, used in error trapping, 50
SSA (triangle solution), 22
Flag 77, used in MINMAX pro-
SSS (triangle solution), 13
gram, 47
time-value-of-money, 92
Flag tests, follow do-if-true rule,
triangle solutions, 58 - 59
46
van der Waals, 101
Flags, 4657
volume of the frustum of a right
control, 47
circular cone, 80
current status maintained by
Error Ignore flag, used in error
Continuous Memory, 47
Error Ignore, 50 GTO function,in a controlled
general purpose, 46-47 loop, 39
have unique meanings for the
calculator, 46 H
listing of in appendix C of
owner’s manual, 46
Horner’s method, 125
Matrix End-Wrap, 47 HP 82240A Infrared Printer
Numeric Data Input, 93 some examples include optional
Printer Enable, 47, 16 instructions for, 11
system, 47 - 48 HP-41 programs, enhancing, 67—
user, 4647 76
Flat region, Solverresults with, with HP-42S datatypes, 69
121 with INPUT function, 68
Flowchart with menu variables, 71-73
definition of, 13 with named variables, 67— 68
for DISPL program, 40 with the two-line display, 69
for FCAT program, 52 with VIEW function, 68
for GAS2 program, 102 HPLOGO program,listing of,
for MLR program, 184 196-200
for PFIT program, 214-215
for PLOT3 program, 204 —-205
for SSA program, 23
for SSA2 program, 27 Ideal gas equation, 101, 78
for SSS program, 15 Improperintegral, definition of,
for TRIXA program, 30-31 127
symbols for, 15 Incorrect results in Integration,
140-143
Indexing (matrix) functions, 146 —
G 154
GASprogram,listing of, 78 Indirect addressing, 43 —45
GAS?2program clearing storage registers with,
flowchartfor, 102 4
listing of, 103 -104 controlled looping with, 43
General purpose flags, 46-47 executing subroutines with, 45
definition of, 46 initializing data storage registers
in LIST program, 47 with, 43
in MINMAX program, 48 INPUT function with, 43
Global label, definesstart of a SOLVE and PGMSLY func-
program, 15 tions with, 101-105
Graphics, 195-203 STO function with, 44
binary datato build, 200203 XEQ function with, 45

Index 227
Infinite limit, approximating an and Integration, 131-133
integral that has an, 127 - and Simultaneous Equations,
130 168-172
Infrared Printer. Interpreting the results of the
some examples include optional Solver, 108 -122
instructions for, 11 ISG function,in a controlled loop,
See also Printing 39
INIT program,listing of, 43
Initial guesses, for the Solver,
80-85
K
INPUT function, 15 KEY GTO function
brings up variablecatalog in emulating a multirow menu
Program-entry mode, 17 with, 34-37
enhancing HP-41 programs emulating a nested menu with,
with, 68 37-39
indirect address with, 43 to build programmable menu,
Integration, 124-145 29
ACC variablein, 124 turns on VA annunciator when
accuracy factor and uncertainty assigned to menu key 7 or 8,
of integration, 134-139 34
approximating an integral that KEY XEQ function
has an infinite limit, 127 - to build programmable menu,
130 29
basic use of, 124-127 turns on VA annunciator when
calculation time for approxima- assigned to menu key 7 or 8,
tions, 129-130 34
conditions that can cause Keying in programs, helpful hints
incorrect results, 140-143 for, 17
conditions that prolong calcula- Keystrokes, required to execute a
tion time, 143 - 145 program, 19-20
limiting the accuracy of, 134
LLIM variable in, 124
more on how it works, 134-145
L
MVARfunction in, 124 LIST program
Solver and, 131 -133 accumulatesstatistical data for
subdividing the interval of plotting, 220
integration, 142-143 emulating £+ function in, 176
ULIM variable in, 124 fills ©2.IST matrix with x-y data
uncertainty of. See Uncertainty pairs, 176
of integration general purpose flag in, 47
Interactive use of the Solver listing of, 176 -179

228 Index
matrix operations in, 172 geometric calculations with vec-
List statistics, 175-182 tors, 154-156
LLIM variable interactive use of indexing utili-
in basic integration, 124 ties and statistics functions,
solving for with the Solver, 131 149-150
Local maximum or minimum, matrix editor and indexing func-
Solver results with, 117 tions, 146154
Loop current equations, 166, 169, matrix operations in statistics
163 and graphics programs,
LVL1 program, listing of, 38 -39 172-173
matrix utility programs, 150-
154
solving simultaneous equations,
MATA matrix 163-168
in MLR program, 172 sorting a matrix, 153 -154
in Simultaneous Equations vector solutions, 154—-163
application, 164 Matrix editor, 146 —154
solving for an element of, 168 Matrix End-Wrap flag, in MIN-
MATB matrix MAX program, 47
in MLR program, 172 Matrix sum of a matrix, 151
in Simultaneous Equations MATX matrix
application, 164 in MLR program, 172
Math error, Solver results with, in Simultaneous Equations
120 application, 165
Matrices, 146-173 Maximum and minimum elements
coordinate transformations with of a matrix, 152-153
vectors, 156-163 Menu
creating a named matrix, 147 multirow, emulating in a pro-
filling a matrix element with an gram, 34-37
Alpha string, 147 nested, emulating in a program,
finding the column norm of a 37-39
matrix, 151 programmable, 29
finding the column sum of a MENU function, 29
matrix, 150-151 Menu keys, 29
finding the conjugate of a com- Menu variables
plex matrix, 151 enhancing HP-41 programs
finding the matrix sum of a with, 71-73
matrix, 151 to simulate the Solver, 88
finding the maximum and Menu-controlled branching, 29—
minimum elements of a 39
matrix, 152 -153 Messages

Index 229
Bad Guess(ez), 120 0
Constant?, 121
Ohm’s law equation, 86, 88
Extremumn, 117
Out of Range message, 49
Out of Range, 49
Restricted Operation, 56
Sign Rewersal, 115 P
MINMAX program, flags in, 47 Parabolic equation. See
MLR program
Equation(s), relative
flowchart for, 184
minimum
listing of, 186— 192 PFIT program
matrix operationsin, 172
flowchart for, 214-215
MOTION program,listing of, 84 listing of, 216-220
Multifunction plotting, 203 -213
matrix operations in, 173
Multiple linear regression, 182 -
PGMSLYVfunction, indirect
194
address with, 101 — 105
Multiple-linear-regression
PHONE program,listing of, 45
equations, 182- 183
PIXEL function, operates on com-
Multirow menu
plex matrices, 213
VA annunciator in, 34
PLOT3 program
{¥] and (4] keysin, 34 flowchart for, 204 - 205
emulating in a program, 3437 listing of, 205-210
MVARfunction
Plotting, 203 -222
defines variables in Integration
multifunction plotting, 203 -213
programs, 124
plotting data from a complex
defines variables in Solver pro- matrix, 213 -222
grams, 77
Pole, Solver results with, 115
Printer Enable flag, 47, 16
Printing
HPLOGO program results, 200
Neighbors, 109
optionalinstructionsfor, 11
Nested menu, emulating in a pro-
PLOT3 program results, 212
gram, 37-39
Q3 program results, 74
Notations, consistent with owner’s
SSS program results, 33
manual, 10
PROFF function, and flag 21, 16
Numeric Data Input flag, 93
Program catalog
executing a program from, 19
global labels placed in, 19
Program listing
for BINDATA,201
for CIRCUIT,87

230 Index
for CLEAR, 44 programs, 194
for CONE,81 defining the program, 15
for COORD, 158 -160 displayingresults, 16
for DISPL, 41 error trapping, 49-50
for EIZ, 89-90 flags, 46— 57
for FCAT, 53-56 helpful hints for keying in pro-
for GAS, 78 grams, 17
for GAS2, 103-104 indirect addressing, 43 —45
for HPLOGO, 196 -200 prompting for data input, 15
for INIT, 43 simple programming, 12-21
for LIST, 176-179 Solver and explicit solutions in
for LVL1, 38-39 programs, 92-100
for matrix utility programs, Solver in programs, 92-105
150-154 subroutines, 2629
for MLR, 186-192 summation-coefficient functions
for MOTION, 84 in programs, 182 —194
for PFIT, 216-220 Programs
for PHONE,45 executing from the CUSTOM
for PLOT3, 205-210 menu, 19
for Q2, 69-71 executing from the program
for Q3,72-73 catalog, 19
for QSHORT, 75 executing with XEQ function,
for ROW1, 35-37 19
for ZFORM,181 keystrokes required to execute,
for SHAFT, 132 19-20
for SIMUL, 170 Prompting for data input. See
for SSA, 24-25 Data input
for SSA2,28-29 PRONfunction, and flag 21, 16
for SSS,17-18 Providing initial guesses for the
for TORQUIE, 126 Solver, 80 -85
for TRAP (revised), 50
for TRIA, 6065
for TVM2, 93-99
Q
for XVALS, 182 Q2 program,listing of, 69-71
Programmable menu Q3 program,listing of, 72-73
definition of, 29 QSHORT program,listing of, 75
in TRIA program, 32
Programming, 12-66
branching, 21-39
controlled looping, 39-43
curve fitting functions in

Index 231
nonzero, 108
RCL function, brings up variable Bad Guess(es) message, 120
catalog in Program-entry basic use of, 77-80
mode, 17 calculation time in TVM pro-
Realistic solution, directing the gram, 99
Solver to, 80— 82 cases when a root is found,
Redimensioning £LIST matrix, 109-115
181 codes returned to the T-register,
Regression, multiple linear, 182 - 108-109
194 Const ant ? message, 121
Festricted Operation mes- differentiating between Case 1
sage, 56 and Case 2 solutions, 110
Root(s) of a function directing to a realistic solution,
approximations of, 108 80-82
definition of, 105 emulating in a program, 86 -91
ideal solutions for, 108 explicit solutions and, 92-100
multivariable function roots, 106 Extremur message, 117
Solver’s ability to find, 107-108 finding more than one solution,
Round-off error, can affect Solver 83-85
results, 123 ideal solution, definition, 108
ROWI1program,listing of, 35-37 Integration and, 131-133
interpreting the results of,
108-122
S more on how it works, 105-123
SHAFT program, listing of, 132 MVAR function in, 77
Sion Rewversal message, 115 providing initial guesses for,
Simple programming, 12-21 80-85
SIMUL program,listing of, 170 results may be affected by
Simultaneous equations round-off error or
complex-number, 166 —168 underflow, 123
real-number, 163 -165 results with a discontinous func-
Simultaneous Equations, 163 -172 tion, 113-114
Solver and, 168-172 Sign Reversal message, 115
Sine integral equation, 136 Simultaneous Equations and,
Solution matrix. See MATX 168-172
SOLVE function, indirect address using in programs, 92105
with, 101 -105 Sorting a matrix, 153-154
Solver, 77-123 SSA program
ability to find a root, 107 -108 flowchart for, 23
approximations for which f(x) is listing of, 2425
SSA (triangle solution) equations,

232 Index
22 coefficient functions
SSA2 program Summation-coefficient functions,
flowchart for, 27 using in programs, 182 - 194
listing of, 28 -29 System flags, 47 - 48
SSS program in MINMAX program, 47
flowchart for, 15
listing of, 17-18
SSS (triangle solution) equations,
T
13 Time-value-of-money equation, 92
Stack registers, contain results of TORQUE program,listing of, 126
the Solver, 108 Translations, coordinate. See
Statistics, 174-194 Coordinate transformations
calculating a multiple linear TRAP program,listing of, 50
regression, 182 -194 TRIX. program
correlation coefficient, 221 flowchart for, 30-31
curve fitting in programs, 194 listing of, 60-65
linear or exponential curve Triangle solutions equations, 58—
fitting for one-variable data, 59
181 TVM?2program,listing of, 93-99
list statistics, 175-182
matrix indexing utilities and,
149-150
U
redimensioning X.LIST matrix to ULIM variable
execute X+, 181 in basic integration, 124
summation-coefficient functions solving for with the Solver, 131
in programs, 182 -194 Uncertainty ofintegration
STO function definition, 135
brings up variable catalog in is greater than error in finalcal-
Program-entry mode, 17 culation, 135
indirect address with, 44 may be relatively large, 138 -
STOP function, 29 139
Subdividing the interval of integra- returned to the Y-register, 135
tion, 142143 Underflow, can affect SolverV
Subroutines, 26 -29 results, 123
advantagesof, 26 Userflags, 46-47
called with XEQ,26
definition, 26
end with RTN or END,26
in SSA2 program, 26
Summation registers. See T+
function; Summation-

Index 233
v
Valid solution. See Directing the
Solverto a realistic
van der Waals equation, 101
Variable menu
enhancing HP-41 programs
with, 71-73
to simulate the Solver, 88
Variables
ACC, 124
keying in in programs, 17
LLIM, 124
MATA, 164
MATB, 164
MATX, 165
LLIST, 176
ULIM, 124
Vector solutions, 154 -163
VIEW function, 16
brings up variable catalog in
Program-entry mode, 17
enhancing HP-41 programs
with, 68
Volumeof frustum of rightcircu-
lar cone, equation, 80

X
XEQ function
executing a program with, 73, 19
indirect address with, 45
XTOA function
in HPLOGO program, 195
used if corresponding character
cannot be typed, 203
XVALS program, listing of, 182

234 Index
Programming Examples and Techniques
for Your HP-42S Calculator
____________________________________________

Programming Examples and Techniques contains examples in mathe-


matics, science, engineering, and finance to help you more fully
utilize the built-in applications in your HP-42S calculator. Programmed
solutions are emphasized. Graphics and plotting with the HP 82240A
Infrared Printer are also addressed.

8 Programming
Simple Programming ¢ Branching ¢ Controlled Looping « Indirect
Addressing in Programs e Flags in Programs * Error Trapping
B Enhancing HP-41 Programs
Using Named Variables « Using HP-42S Data Input and Output
Functions ¢ Operations with HP-42S Data Types * Using the Two-
Line Display » Using Menu Variables * Assigning a Program to the
CUSTOM Menu
B The Solver
Basic Use of the Solver ¢ Providing Initial Guesses for the Solver
» Emulating the Solver ¢ Using the Solver in Programs ¢« More on
How the Solver Works
B Integration
Basic Integration » Approximating an Integral That Has an Infinite
Limit « Using the Solver and Integration Interactively s More on
How Integration Works
H Matrices
Using the Matrix Editor and Indexing Functions « Vector Solutions
* Solving Simultaneous Equations ¢ Using the Solver with
Simultaneous Equations « Matrix Operations in Programs
B Statistics
List Statistics » Using the Summation-Coefficient Functions in
Programs « Curve Fitting in Programs
8 Graphics and Plotting
- Graphics » Multifunction Plots + Plotting Data from a Complex
Matrix

HEWLETT
fifi PACKARD
Reorder Number
00042-90020
00042-90019 English
Printed in US.A. 7/88 0""88698"00036" 6

You might also like