Post Reply 
Companion program for Joe Horn’s continued fractions article
09-13-2023, 11:07 AM (This post was last modified: 09-14-2023 04:55 AM by dlidstrom.)
Post: #7
RE: Companion program for Joe Horn’s continued fractions article
(09-10-2023 12:50 AM)Joe Horn Wrote:  I hate to make your life more difficult, but another issue arises when the best fraction is one of the inputs. Sometimes your program returns that fraction, but other times not. For example:

Between 1.5 and 1.6, the simplest fraction is 3/2 (same as 1.5), which your program returns.
But between 1.8 and 1.9, the simplest fraction is 9/5, but your program returns 11/6.

In other words, the program should return EITHER the simplest fraction in the open interval (A, B), OR in the closed interval [A, B]. Right now it sometimes does the former and sometimes the latter.

This turned out to be much more difficult than I thought. My initial program was small and fast but wrong. Now it has ballooned. But I've tried my best to come up with a more complete program. I say more complete because I'm sure there are issues I haven't thought of or understood completely. Arbitrarily I decided the program can return in the interval (A, B]. That is, it is allowed to return the smallest decimal as the simplest fraction but not the largest decimal.

There are some cases which aren't covered. Such as equal decimals being supplied, and perhaps negative decimals. However, I think I'll leave it here.

Code:

« → ←a ←b
  « ←a →SF →CF DUP SIZE ←b →SF →CF DUP SIZE ROT SWAP DUP2 -
    « → ah at al bh bt bl
      «
        CASE 'ah<0'
          THEN bh "0" →TAG +
          END 'bh<0'
          THEN ah "1" →TAG +
          END '←a<←b AND al≤0.'
          THEN ah "2" →TAG +
          END '←a<←b AND bl≤0.'
          THEN ah "3" →TAG + at +
          END '←b<←a AND al≤0.'
          THEN bh "4" →TAG + bt +
          END '←b<←a AND bl≤0.'
          THEN bh "5" →TAG +
          END 'ah<bh'
          THEN ah 1 + "6" →TAG +
          END 'bh<ah'
          THEN bh 1 + "7" →TAG +
          END ah + at HEAD at TAIL al 1 -
            bt HEAD bt TAIL bl 1 - ←proc EVAL
        END
      »
    » → a b al bl c ←proc
    «
      CASE 'c<0'
        THEN 'a' a -1 c NEG
        END 'b' b -1 c
      END NDUPN →LIST + SWAP STO { } a HEAD a TAIL al 1 -
      b HEAD b TAIL bl 1 - ←proc EVAL DUP CF→ DUP →NUM
    »
  »
»

# A222h
887.5

2xHP48GX, HP 50g, two Retrotronik ram cards, DM42
/Daniel Lidström
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Companion program for Joe Horn’s continued fractions article - dlidstrom - 09-13-2023 11:07 AM



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