【问题标题】:Float division of big numbers in pythonpython中大数的浮点除法
【发布时间】:2015-09-27 02:48:06
【问题描述】:

我有两个长度约为 10000 的大数 ab,例如 a <= b。 现在,我必须找到c = a / b,最多小数点后10位,如何在不丢失精度的情况下做到这一点?

【问题讨论】:

  • 听起来你在找decimal
  • 另一种选择是使用mpmath 模块。
  • a 和 b 都是 LONG INT。

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


【解决方案1】:

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)

【讨论】:

    【解决方案2】:

    您可以使用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)
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-16
        • 2022-01-05
        • 2018-04-03
        • 2023-02-14
        • 2012-01-08
        • 1970-01-01
        • 2011-05-06
        • 2011-03-29
        相关资源
        最近更新 更多