Post Reply 
(12C) Decimal to Fraction
08-09-2018, 03:39 PM (This post was last modified: 08-09-2018 04:49 PM by Albert Chan.)
Post: #37
RE: (12C) Decimal to Fraction
I removed \(0 < x < 1\) restriction of farey fraction.

Code:
>>> farey(0.10322, 1e8)   # fractions match, stop
(5161, 50000)
>>> farey(-0.10322, 1e8)  # negatives ok
(-5161, 50000)
>>> farey(1/pi, 700)      # pick the best estimate
(113, 355)
>>> farey(pi, 100)        # abs(x) > 1 ok
(311, 99)
>>> farey(3, 100)         # integer ok
(3, 1)

Code:
def farey(x, limit=100):
    'return Farey fraction (n,d) closest to x with denominator <= limit'
    n1, d1 = int(x), 1      
    if n1 == x: return n1, d1
    if x < 0: n1 -= 1       # lo = floor(x)
    n2, d2 = n1+1, 1        # hi = lo + 1
    while 1:
        n, d = n1 + n2, d1 + d2
        if d > limit: break
        if   x * d > n: n1, d1 = n, d
        elif x * d < n: n2, d2 = n, d
        else: return n, d   # exact match
    pick_hi = (n2/d2 - x) < (x - n1/d1)
    return (n2, d2) if pick_hi else (n1, d1)
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
(12C) Decimal to Fraction - Gamo - 08-06-2018, 12:33 PM
RE: (12C) Decimal to Fraction - Dieter - 08-06-2018, 08:44 PM
RE: (12C) Decimal to Fraction - Dieter - 08-07-2018, 07:29 AM
RE: (12C) Decimal to Fraction - Dieter - 08-07-2018, 01:02 PM
RE: (12C) Decimal to Fraction - Dieter - 08-07-2018, 11:38 AM
RE: (12C) Decimal to Fraction - Gamo - 08-07-2018, 09:29 AM
RE: (12C) Decimal to Fraction - Joe Horn - 08-07-2018, 06:28 PM
RE: (12C) Decimal to Fraction - Dieter - 08-07-2018, 07:10 PM
RE: (12C) Decimal to Fraction - Joe Horn - 08-08-2018, 12:28 AM
RE: (12C) Decimal to Fraction - Dieter - 08-08-2018, 07:04 PM
RE: (12C) Decimal to Fraction - Dieter - 08-09-2018, 09:27 AM
RE: (12C) Decimal to Fraction - Dieter - 08-08-2018, 09:44 PM
RE: (12C) Decimal to Fraction - Gamo - 08-09-2018, 12:51 AM
RE: (12C) Decimal to Fraction - Dieter - 08-09-2018, 07:46 AM
RE: (12C) Decimal to Fraction - Dieter - 08-09-2018, 08:09 AM
RE: (12C) Decimal to Fraction - Gamo - 08-09-2018, 09:16 AM
RE: (12C) Decimal to Fraction - Dieter - 08-09-2018, 10:30 AM
RE: (12C) Decimal to Fraction - Albert Chan - 08-09-2018 03:39 PM
RE: (12C) Decimal to Fraction - Dieter - 08-10-2018, 12:28 PM
RE: (12C) Decimal to Fraction - Gamo - 05-07-2019, 01:44 AM
RE: (12C) Decimal to Fraction - Dieter - 08-10-2018, 07:06 PM



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