(02-01-2016 09:36 PM)Dieter Wrote: And maybe we can also get this RCL d thing working... ;-)
Here is a version that adds some benefits:
- Mode settings (register d) are preserved.
- Output can be displayed as a mixed number or improper fraction.
Clear resp. set flag 01.
- Denominator can be minimized or fixed.
Clear resp. set flag 02.
- Input can be positive or negative.
- Integer output is displayed without "0/1" part.
And here is the code:
Code:
01 LBL"D2F"
02 RCL d
03 X<>Y ' Save status register on stack
04 CF 05
05 X<0?
06 SF 05 ' Set sign flag
07 ABS
08 RCL 00 ' A simple constant like 32 or 64 can be used here as well
09 STO 02 ' Store denominator in R02
10 *
11 FIX 0
12 CF 29
13 RND
14 STO 01 ' Store nominator in R01
15 FS? 02 ' Constant denominator mode?
16 GTO 02 ' Then skip GCD calculation
17 RCL 02
18 LBL 01 ' Use Euclidean algorithm
19 MOD ' to compute gcd(R01, R02)
20 LASTX
21 X<>Y
22 X≠0?
23 GTO 01
24 + ' = GCD
25 ST/ 01 ' reduce fraction
26 ST/ 02
27 LBL 02
28 CLX ' Set integer part "a" = 0
29 FS? 01 ' Improper fraction mode?
30 GTO 03 ' Then skip conversion to mixed number
31 RDN
32 RCL 01
33 RCL 02
34 MOD ' Compute "b" = nominator mod denominator
35 X<> 01 ' and store it in R01
36 RCL 02
37 /
38 INT ' Compute "a" = nominator DIV denominator
39 FS? 05 ' If input was negative
40 CHS ' adjust sign of integer part
41 LBL 03 ' Start of formatting routine for result "a b/c"
42 CLA ' Here "a" is in X while "b" and "c" are in R01 and R02
43 X=0? ' if a = 0
44 GTO 04 ' do not display it
45 X>0? ' else if a ≥ 0
46 " " ' start with a blank
47 ARCL X ' then append integer part to output string
48 LBL 04
49 RCL 01
50 FS? 05 ' if input was negative
51 CHS ' adjust sign of nominator
52 STO 01
53 X=0? ' if nominator = 0
54 GTO 05 ' skip adding b/c
55 X>0? ' else if nominator ≥ 0
56 "├ " ' append a blank
57 ARCL 01 ' append nominator,
58 "├/" ' fraction bar
59 ARCL 02 ' and denominator
60 LBL 05 ' At this point the output line is complete
61 RCL 02 ' Now calculate a + b/c
62 ST/ 01 ' R01 = b/c
63 R↑ ' Recall status bits from stack
64 STO d ' and restore original mode settings
65 RDN
66 RCL Z ' add integer part
67 ST+ 01 ' to R01
68 X<> 01 ' and move result = a + b/c to X
69 X=0? ' The (AFAIK) only case that's not handled properly
70 " 0" ' is x=0, so use a pragmatic solution. ;-)
71 AVIEW ' Display result
72 END ' Quit with a, b, c and a+b/c on the stack.
Here are some examples:
Code:
64 [STO] 00
[CF] 01
[CF] 02
1,35 XEQ"D2F" 1 11/32
[SF] 02
1,35 XEQ"D2F" 1 22/64
[SF] 01
[CF] 02
-2,5 XEQ"D2F" -5/2
[CF] 01
-2,5 XEQ"D2F" -2-1/2
0,17 XEQ"D2F" 11/64
3 XEQ"D2F" 3
Note: in improper fraction mode integer results are returned as x/1.
Now try this version and see what you get. There may be errors, so as usual all remarks and error reports are welcome.
Dieter