我有两个大号a
和b
,长度大约为10000,这样a <= b
。
现在,我必须找到c = a / b
,最多10位小数,如何在不失去精度的情况下完成?
答案 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:])