Post Reply 
50G fraction question Q-> function max denominator
10-29-2019, 02:16 PM (This post was last modified: 10-30-2019 03:44 AM by DavidM.)
Post: #12
RE: 50G fraction question Q-> function max denominator
After thinking about this question a bit, a slightly different idea came to mind. I was wondering how I would determine which fraction whose denominator is a power of two would be the best fit for a given real number. I'm sure there's a more elegant way to do this, but I came up with the following brute-force approach which simply checks each possibility starting with "/2" and multiplying the denominator by 2 up to the specified limit. The closest combination is then returned as a symbolic number in the form "a+b/c" (or simply "b/c" as appropriate).

The code pertaining to the flags is to avoid the "Turn on approximate mode?" prompt that would result if you were in exact mode when the program was invoked.

Code:
\<<
   PUSH -105. SF
   2.
   \-> targ max cur
   \<<
      1. DUPDUP
      WHILE
         cur max \<=
      REPEAT
         cur DUP targ *
         0. RND DUP2 SWAP /
         targ - ABS

         4. PICK OVER >
         { 6. ROLL 6. ROLL 6. ROLL }
         IFT
         DROP2 DROP

         'cur' 2. STO*
      END
   \>>
   DROP SWAP R\->I SWAP R\->I
   OVER IDIV2 ROT
   -105. CF / +
   PROPFRAC PROPFRAC
   POP
\>>

Examples:

π 128 => '3+9/64'
π 32 => '3+5/32'
e 512 => '2+23/32'
0.5 8 => '1/2'
0.4 32 => '13/32'
-5 16 => -5
-1.4 128 => '-1+-51/128'
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: 50G fraction question Q-> function max denominator - DavidM - 10-29-2019 02:16 PM



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