Post Reply 
(12C) Decimal to Fraction
08-08-2018, 10:26 PM
Post: #21
RE: (12C) Decimal to Fraction
(08-08-2018 06:05 PM)Thomas Klemm Wrote:  
Code:
def dec2frac(f, c):
    if c < 2 and int(f) == f: return
    u, v, F = 0, 1, f
    while v < c and f:
        g = 1 / f
        f, _ = modf(g)
        u, v = v, u + v * int(g)
    if v > c: v -= u * ceil((v - c) / u)
    q = u if diff(F, u) < diff(F, v) else v
    p = round(q * F, 0)
    return p, q

Hi, Thomas

I noticed some issues with above Python code.

dec2frac(2.0, 10) crashes with ZeroDivisionError. "if c < 2 and" should be "if c < 2 or"
-> since it is translated from calculator code, you might want to check this.

Although not a bug in Python, when code running in a calculator, v can be huge.
-> v might be much bigger than c, corrected v below c might be off.

Below is the patched code:
Code:
def dec2frac(f, c):
    if c < 2 or int(f) == f: return
    u, v, F = 0, 1, f
    while f:
        f = 1/f
        w = u + v * int(f)  # check before update
        if w > c: break     # guaranteed v <= c
        u, v, f = v, w, f - int(f)
    q = u + (c - u)//v * v  # biggest quotient
    if diff(F, q) >= diff(F, v): q = v
    return int(q * F + 0.5), q
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 - Albert Chan - 08-08-2018 10:26 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 - 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)