HP42S / DM42 program: convert a floating point number into a fraction (numerator and denominator)
Start a new program with: GTO . . PRGM
key commands display
{ 45-Byte Prgm }
PGM.FCN LBL ALPHA FRACT LBL "FRACT"
CONVERT ABS ABS
STO ALPHA X STO "X"
1 1
STO ALPHA D STO "D"
PGM.FCN LBL 01 LBL 01
R-arrow_down R↓
1/x 1/X
STO * ALPHA D STO* "D"
CONVERT FP FP
0.00001 0.00001
PGM.FCN X?Y X<=Y X<=Y
GTO 01 GTO 01
RCL ALPHA X RCL "X"
RCL ALPHA D RCL "D"
* *
PGM.FCN PSE PSE
LAST X LASTX
.END.
This program is executed with XEQ FRACT
Using the program
Convert 0.15625 into a fraction:
You type: 0.15625 XEQ FRACT
The display shows "running" and then you see first 5 and a few sec later 32.
The fraction is therefore 5/32 (numerator=5 and denominator=32). 5 remains in the Y register of the stack and 32 in X.
Note that this program shows the resulting fraction always with positive numbers. That is: both 0.15625 and -0.15625 will result in 5/32. An extra step could be
added to add the sign at the end but that would make the program longer and it's not really needed.
If the program runs for a very long time and displays finally "Out of Range" then the number can not
be converted into a reasonable fraction.
Algorithm
0.15625 -> 1/0.15625 = 6.4
take the fraction part only: 0.4
0.4 -> 1/0.4 = 2.5
take the fraction part only: 0.5
0.5 -> 1/0.5 = 2
take the fraction part only: 0
0 -> end of program
denominator = 6.4 * 2.5 * 2 = 32
numerator = 0.15625 * denominator = 0.15625 * 32 = 5
Written by Guido Socher