代码之家  ›  专栏  ›  技术社区  ›  Gunjan

在python中获取decimal的ceil()?

  •  8
  • Gunjan  · 技术社区  · 16 年前

    有没有办法在python中获得高精度小数的ceil?

    >>> import decimal;
    >>> decimal.Decimal(800000000000000000001)/100000000000000000000
    Decimal('8.00000000000000000001')
    >>> math.ceil(decimal.Decimal(800000000000000000001)/100000000000000000000)
    8.0
    

    数学对值进行舍入并返回非精确值

    6 回复  |  直到 16 年前
        1
  •  5
  •   Robert Clark    16 年前
    x = decimal.Decimal('8.00000000000000000000001')
    with decimal.localcontext() as ctx:
        ctx.prec=100000000000000000
        ctx.rounding=decimal.ROUND_CEILING
        y = x.to_integral_exact()
    
        2
  •  20
  •   Mark Dickinson Alexandru    11 年前

    获取十进制实例上限的最直接方法 x 是用来 x.to_integral_exact(rounding=ROUND_CEILING) . 这里没必要乱来。注意,这将设置 Inexact Rounded 适当时使用标志;如果不想触摸标志,请使用 x.to_integral_value(rounding=ROUND_CEILING) 相反。例子:

    >>> from decimal import Decimal, ROUND_CEILING
    >>> x = Decimal('-123.456')
    >>> x.to_integral_exact(rounding=ROUND_CEILING)
    Decimal('-123')
    

    与大多数十进制方法不同的是, to_integral_exact to_integral_value 方法不受当前上下文精度的影响,因此不必担心更改精度:

    >>> from decimal import getcontext
    >>> getcontext().prec = 2
    >>> x.to_integral_exact(rounding=ROUND_CEILING)
    Decimal('-123')
    

    顺便说一下,在Python3.x中, math.ceil 完全按照您的要求工作,只是它返回一个 int 而不是 Decimal 实例。那是因为 数学.ceil 对于Python3中的自定义类型可重载。在python 2中, 数学.ceil 简单地转换 十进制的 实例到 float 首先,在这个过程中可能会丢失信息,因此可能会导致错误的结果。

        3
  •  3
  •   Matthew Flaschen    16 年前

    可以使用上下文构造函数的precision和rounding mode选项来执行此操作。

    ctx = decimal.Context(prec=1, rounding=decimal.ROUND_CEILING)
    ctx.divide(decimal.Decimal(800000000000000000001), decimal.Decimal(100000000000000000000))
    

    编辑:您应该考虑更改接受的答案。虽然 prec 可以根据需要增加, to_integral_exact 是一个简单的解决方案。

        4
  •  0
  •   Ignacio Vazquez-Abrams    16 年前
    >>> decimal.Context(rounding=decimal.ROUND_CEILING).quantize(
    ...   decimal.Decimal(800000000000000000001)/100000000000000000000, 0)
    Decimal('9')
    
        5
  •  0
  •   fviktor    16 年前
    def decimal_ceil(x):
        int_x = int(x)
        if x - int_x == 0:
            return int_x
        return int_x + 1
    
        6
  •  0
  •   Pedro Moreno    13 年前

    用效力来做这个。 导入数学

    def lo_ceil(num, potency=0): # Use 0 for multiples of 1, 1 for multiples of 10, 2 for 100 ...
          n = num / (10.0 ** potency)
          c = math.ceil(n)
          return c * (10.0 ** potency)
    
    lo_ceil(8.0000001, 1) # return 10
    
    推荐文章