7 Jun 2011

python tips - 转分数为小数



UPDATE: 新函数cmpfrac()可以用来求循环节长度.

将分数转换为循环小数,默认处理1/d的情况,输出50位.稍加修改,可以变成处理互质的a/b的程序.

代码如下:

# compute decimal string of 1/d, defualt 50 length
def frac2num(d,n=50):
s = '0.' # result
rem = 10 # remainder
i = 0    # number of digits after dot
while i<n:
s += str(rem/d) # division
i += 1          # number increase
rem = rem%d     # get the remainder
if rem==0:      # fully divided
break
rem *= 10       # next division
return s
test code
print frac2num(884,100)

0.0011312217194570135746606334841628959276018099547511312217194570135746606334841628959276018099547511

updated version:
可以检测循环小数的循环节,写成1/3 = 0.(3)的形式,如果是整除,直接除尽,没有循环节.
def cmpfrac(a,b):
    flag = 0
    c,r = divmod(a,b)
##    print c,r
    s = []
    rs = [r]
##    print rs
    r *= 10
    while True:
        c1,r1 = divmod(r,b)
##        print s,r,'/',b,'=',c1,'...',r1
        if r1==0:
            flag = 1
            s.append(str(c1))
            break
        elif r1 in rs:
            flag = 0
            s.append(str(c1))
            s.append(str(s[rs.index(r1)]))
            rs.append(r1)
            break
        else:
            s.append(str(c1))
            rs.append(r1)
            r = r1*10
    print a,b,c
    if flag:
        return str(c)+'.'+''.join(s)
    else:
        # for 29/12 = 2.41(6)
##        print s
##        print ''.join([str(c) for c in rs])
        d = s.index(s[-1])
        result = str(c)+'.'+''.join(s[:d])+'('+''.join(s[d:-1])+')'
        print result
        return result

No comments :

Post a Comment