(41) Jet fuel Density calculator
06-25-2022, 03:47 AM
Post: #2
 Thomas Klemm Senior Member Posts: 1,770 Joined: Dec 2013
RE: (41) Jet fuel Density calculator
(02-23-2022 05:38 AM)WrongWay Wrote:  … the code I'm sure could easily be optimized and constructive feedback is always welcome.

if-else Statements

In general an if-else statement like this:
Code:
if predicate:
# true-case
...
else:
# false-case
...

… can be translated into:
Code:
predicate?
GTO 00
# false-case
...
GTO 01
LBL 00
# true-case
...
LBL 01

This uses only two labels instead of three:
Code:
33 FS? 00
34 GTO 00
35 ├"KG/M3"
36 GTO 01
37▸LBL 00
38 ├"LB/GAL"
39▸LBL 01

Since we use only forward jumps, both labels can be reused in other occurrences as well:
Code:
52 FS?C 00
53 GTO 00
54 ├"L"
55 GTO 01
56 ├"G"
57▸LBL 01

This also avoids using the expensive global labels "K" and "L".

Polynomial Evaluation

A quadratic polynomial can be rewritten using Horner's method:

\begin{align} ax^2 + bx + c = (ax + b)x + c \end{align}

This avoids calculating powers of $$x$$.

If we first fill the stack with $$x$$ it will be copied from register T down the stack with each operation.
Since the coefficients are not used elsewhere we don't have to store them in registers:
Code:
12 ENTER
13 ENTER
14 ENTER
15 -2.987077809ᴇ-07
16 ×
17 -9.200271003ᴇ-04
18 +
19 ×
20 1.013879343
21 +

Saving Results

I decided not to save the density in a register but leave the result on the stack for further computations:
Code:
43 "FPL FUEL?"
44 PROMPT
45 "FOB?"
46 PROMPT
47 -
48 X<>Y
49 ÷
50 "NEED: "
51 ARCL ST X
This allowed me to remove the CLRG command at the beginning of the program.
Of course the user might mess with the stack which may lead to wrong results.

This leaves us with the following program for the HP-42S:
Code:
00 { 191-Byte Prgm }
01▸LBL "FDENSTY"
02 CLST
03 CLA
04 CF 00
05 FIX 03
06 "LB: 0, KG:1"
07 PROMPT
08 X=0?
09 SF 00
10 "OAT C?"
11 PROMPT
12 ENTER
13 ENTER
14 ENTER
15 -2.987077809ᴇ-07
16 ×
17 -9.200271003ᴇ-04
18 +
19 ×
20 1.013879343
21 +
22 FS? 00
23 GTO 00
24 .8
25 ×
26 GTO 01
27▸LBL 00
28 .15
29 ÷
30▸LBL 01
31 "DEN: "
32 ARCL ST X
33 FS? 00
34 GTO 00
35 ├"KG/M3"
36 GTO 01
37▸LBL 00
38 ├"LB/GAL"
39▸LBL 01
40 AVIEW
41 STOP
42 FIX 00
43 "FPL FUEL?"
44 PROMPT
45 "FOB?"
46 PROMPT
47 -
48 X<>Y
49 ÷
50 "NEED: "
51 ARCL ST X
52 FS?C 00
53 GTO 00
54 ├"L"
55 GTO 01
56 ├"G"
57▸LBL 01
58 AVIEW
59 FIX 09
60 END

It should also work with the HP-41C after the obvious transformations.

We end up with a program with 20 fewer lines, using 191 bytes instead of 230, and using no registers.
 « Next Oldest | Next Newest »

 Messages In This Thread (41) Jet fuel Density calculator - WrongWay - 02-23-2022, 05:38 AM RE: (41) Jet fuel Density calculator - Thomas Klemm - 06-25-2022 03:47 AM

User(s) browsing this thread: 1 Guest(s)