The following warnings occurred:
Warning [2] count(): Parameter must be an array or an object that implements Countable - Line: 795 - File: showthread.php PHP 7.4.33 (FreeBSD)
File Line Function
/showthread.php 795 errorHandler->error





Post Reply 
fraction between 2 number, minimum denominator
09-16-2023, 07:47 PM
Post: #1
fraction between 2 number, minimum denominator
From thread Companion program for Joe Horn’s continued fractions article.
Python code, translated for HP Prime (if micro-Python available, that should work too)

Code:
d_convergent(a,b, d1,d2)
BEGIN
LOCAL ia, ib;
ia, ib := floor(a), floor(b);
IF ia == a  THEN RETURN d2, d1+(ia-1)*d2 END;
IF ia != ib THEN RETURN d2, d1+ia*d2 END;
d_convergent(1/(b-ib), 1/(a-ia), d2, d1+ia*d2);
END;

frac_between(a,b)
BEGIN
LOCAL d, d2;
IF a>b THEN a,b := b,a END;
d, d2 := d_convergent(a,b, 1,0);
REPEAT d += d2 UNTIL (a*d) <= floor(b*d);
RETURN ceiling(a*d)/d;
END;

Once minimum denominator are picked, program pick minimum numerator too.
Code assumed number are *exact* fractions, not float.

Cas> frac_between(18/10,19/10) --> 9/5
Cas> frac_between(18/10,18/10) --> 9/5
Cas> frac_between(18/10,17/10) --> 7/4
Cas> frac_between(18/10,16/10) --> 5/3
Cas> frac_between(18/10,15/10) --> 3/2
Cas> frac_between(18/10,14/10) --> 3/2

Cas> frac_between(999999999977/10^12,999999999978/10^12) --> 43478260869/43478260870
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
fraction between 2 number, minimum denominator - Albert Chan - 09-16-2023 07:47 PM



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