While other answers use very large values ββto handle accuracy, this implements a long separation.
def divide(num, denom, prec=30, return_remainder=False): "long divison" remain=lim=0 digits=[] #whole part for i in str(num): d=0;remain*=10 remain+=int(i) while denom*d<=remain:d+=1 if denom*d>remain:d-=1 remain-=denom*d digits.append(d) #fractional part if remain:digits.append('.') while remain and lim<prec: d=0;remain*=10 while denom*d<=remain:d+=1 if denom*d>remain:d-=1 remain-=denom*d digits.append(d) lim+=1 #trim leading zeros while digits[0]==0 and digits[1]!='.': digits=digits[1:] quotient = ''.join(list(map(str,digits))) if return_remainder: return (quotient, remain) else: return quotient
Because it is a division algorithm, each digit will be correct, and you can get the remainder (as opposed to dividing the sexes, which will have no remainder). I implemented accuracy here as the number of digits after the decimal place.
>>> divide(2,7,70) '0.2857142857142857142857142857142857142857142857142857142857142857142857' >>> divide(2,7,70,True) ('0.2857142857142857142857142857142857142857142857142857142857142857142857', 1)
source share