python实现无限精度除法运算

来源:互联网 发布:数据透视表差异百分比 编辑:程序博客网 时间:2024/05/21 11:18

python3的int支持超大数的乘法运算,但是除法运算貌似还没有实现无限精度。对于浮点数乘法可以扩大转换为整数,运算完毕以后再缩小保存为str,即可实现高精度,但是对于除法,这种方法貌似行不通。

通过思考手算除法的过程,以a/b=c余r为例,过程如下:

1.a = r*10

2.计算a/b,结果为c余r

3.把c写在已经计算出来的结果后面

4.重复1~3步,直到想要的精度

用python实现,代码如下:

def hdiv(dividend, divisor, precision=0):    """高精度计算除法,没有四舍五入        @author: cidplp        @param dividend:被除数    @type dividend:int    @param divisor:除数    @type divisor:int    @param precision:小数点后精度    @type precision:int    @return:除法结果    @rtype:str    """        if isinstance(precision, int) == False or precision < 0:        print('精度必须为非负整数')        return        a = dividend    b = divisor        #有负数的话做个标记    if abs(a+b) == abs(a) + abs(b):        flag = 1    else:        flag = -1            #变为正数,防止取模的时候有影响    a = abs(a)    b = abs(b)    quotient = a // b    remainder = a % b        if remainder == 0:        return quotient        ans = str(quotient) + '.'    i = 0    while i < precision:        a = remainder * 10        quotient = a // b        remainder = a % b         ans += str(quotient)        if remainder == 0:            break        i += 1        if precision == 0:        ans = ans.replace('.', '')        if flag == -1:        ans = '-' + ans        return ans


原创粉丝点击