在python中浮动大数字的划分

时间:2015-07-08 23:11:52

标签: python python-2.7 python-3.x

我有两个大号ab,长度大约为10000,这样a <= b。 现在,我必须找到c = a / b,最多10位小数,如何在不失去精度的情况下完成?

3 个答案:

答案 0 :(得分:2)

decimal模块应该有效。如TigerhawkT3的链接所示,您可以选择商数应该是小数位数。

from decimal import *
getcontext().prec = 6
a = float(raw_input('The first number:'))       #Can be int() if needed
b = float(raw_input('The second number:'))
c = Decimal(a) / Decimal(b)
print float(c)

答案 1 :(得分:1)

您可以使用decimal模块:

from decimal import localcontext, Decimal

def foo(a, b):
    with localcontext() as ctx:
        ctx.prec = 10   # Sets precision to 10 places temporarily
        c = Decimal(a) / Decimal(b) # Not sure if this is precise if a and b are floats, 
                                    # str(a) and str(b) instead'd ensure precision i think.
    return float(c)

答案 2 :(得分:1)

您可以使用此函数计算任何类型的长度浮点数

def longdiv(divisor,divident):
    quotient,remainder=divmod(divisor,divident)
    return (str(quotient)+str(remainder*1.0/divident)[1:])