Post Reply 
How do you enter a repeating decimal
04-29-2021, 01:07 PM (This post was last modified: 04-29-2021 01:13 PM by Albert Chan.)
Post: #5
RE: How do you enter a repeating decimal
I had coded repeating decimal conversion in Python, long time ago.
Code:
def dratio(s):
    'Return decimals (with no exponent) as ratio'
    s = s.rstrip(') \t')
    i = s.find('.')
    if i < 0: return int(s), 1  # assume integer, if no decimal point
    j = s.find('(', i+1)        # repeating decimal start
    if j < 0: return int(s[:i]+s[i+1:]), 10 ** (len(s)-i-1)
    r = 10 ** (len(s)-j-1)      # handle repeating decimals
    k = int( s[:i] + s[i+1:j] + s[j+1:] )
    return k - k//r - (k<0), (r-1) * 10 ** (j-i-1)

>>> map(dratio, ['2.(777)', '71.23(4)', '71.234(56)'])
[(2775, 999), (64111, 900), (7052222, 99000)]
>>> [n/d for (n,d) in _]
[2.7777777777777777, 71.234444444444449, 71.23456565656565]


Code get the correct ratio, but not fully reduced. Fix is easy, if needed.

>>> import fractions
>>> dtoF = lambda s: fractions.Fraction(*dratio(s))
>>> map(dtoF, ['2.(777)', '71.23(4)', '71.234(56'])
[Fraction(25, 9), Fraction(64111, 900), Fraction(3526111, 49500)]
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: How do you enter a repeating decimal - Albert Chan - 04-29-2021 01:07 PM



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