Decimal to fraction conversion

Contributions to this software library are always welcome. Please ensure that you post program listings rather than .raw files. They give a reasonable idea of what your program does without having to load them into a DM42 and you can also include comments in your code. Check out the following link for a decoder/encoder: https://technical.swissmicros.com/decoders/dm42/

You can then copy/paste the listing and post it in "code" tags.
Post Reply
Jvi
Posts: 12
Joined: Fri Aug 09, 2019 6:03 am
Location: Greve Denmark

Decimal to fraction conversion

Post by Jvi »

This program takes the value in X and converts it to a fraction with 12 digits accuracy.
It uses the algoritm made by John Kennedy. You can find his article here:

https://begriffs.com/pdf/dec2frac.pdf

It is very fast, and since it only uses named variables, it will not change any registers.
it will however change change the stack.

As an example, i will convert Pi to a fraction. I just enter Pi into the X register and start the program.
The image you see here, is the result. The value in Z is the decimal value of the fraction, and the value in Y and X is the actual fraction.

20200311-11175767.bmp
20200311-11175767.bmp (12.31 KiB) Viewed 4832 times

you can change the accuracy by changing the value in line 37, but the more accurate the fraction gets, the bigger will the numbers, that make up the fraction become.

Code: Select all

00 { 154-Byte Prgm }
01▸LBL "FRAC"
02 STO "X"
03 STO "Z1"
04 0
05 STO "D0"
06 1
07 STO "D1"
08▸LBL 00
09 RCL "Z1"
10 FP
11 1/X
12 STO "Z2"
13 IP
14 RCL "D1"
15 ×
16 RCL "D0"
17 +
18 STO "D2"
19 RCL "X"
20 ×
21 0.5
22 +
23 IP
24 STO "N"
25 RCL "D1"
26 STO "D0"
27 RCL "D2"
28 STO "D1"
29 RCL "Z2"
30 STO "Z1"
31 RCL "X"
32 RCL "N"
33 RCL "D2"
34 ÷
35 -
36 ABS
37 1ᴇ-12
38 X<Y?
39 GTO 00
40 CLST
41 RCL "N"
42 RCL "D2"
43 ÷
44 RCL "N"
45 RCL "D2"
46 CLV "X"
47 CLV "Z1"
48 CLV "Z2"
49 CLV "D0"
50 CLV "D1"
51 CLV "D2"
52 CLV "N"
53 END
Here is the raw file:

FRAC.raw
(157 Bytes) Downloaded 288 times
Joe Horn
Posts: 108
Joined: Thu Oct 04, 2018 2:10 am

Re: Decimal to fraction conversion

Post by Joe Horn »

Although 4272943/1360120 does in fact evaluate to 3.14159265359 (rounded to 12 significant digits), why does the program not return the previous convergent, 1146408/364913, which also evaluates to 3.14159265359 but has a smaller numerator and denominator?
whuyse
Posts: 198
Joined: Thu Dec 21, 2017 1:23 pm

Re: Decimal to fraction conversion

Post by whuyse »

Joe: because it checks whether the error is less than 1e-12.
1146408/364913 - 3.14159265359 = 1.4e-12

Cheers, Werner
41CV†,42S,48GX,49G,DM42,DM41X,17BII,15CE, DM15L
Joe Horn
Posts: 108
Joined: Thu Oct 04, 2018 2:10 am

Re: Decimal to fraction conversion

Post by Joe Horn »

Aha! I see now. Thanks, Werner!
Post Reply