【发布时间】:2015-09-27 02:48:06
【问题描述】:
我有两个长度约为 10000 的大数 a 和 b,例如 a <= b。
现在,我必须找到c = a / b,最多小数点后10位,如何在不丢失精度的情况下做到这一点?
【问题讨论】:
标签: python python-2.7 python-3.x
我有两个长度约为 10000 的大数 a 和 b,例如 a <= b。
现在,我必须找到c = a / b,最多小数点后10位,如何在不丢失精度的情况下做到这一点?
【问题讨论】:
标签: python python-2.7 python-3.x
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)
【讨论】:
您可以使用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)
【讨论】:
您可以使用此函数计算任何类型的长度浮点数
def longdiv(divisor,divident):
quotient,remainder=divmod(divisor,divident)
return (str(quotient)+str(remainder*1.0/divident)[1:])
【讨论】: