在python中获取十进制的Ceil()?
有没有办法在python中获得高精度十进制的ceil在python中获取十进制的Ceil()?,python,decimal,rounding,ceil,Python,Decimal,Rounding,Ceil,有没有办法在python中获得高精度十进制的ceil >>> import decimal; >>> decimal.Decimal(800000000000000000001)/100000000000000000000 Decimal('8.00000000000000000001') >>> math.ceil(decimal.Decimal(800000000000000000001)/100000000000000000000) 8
>>> import decimal;
>>> decimal.Decimal(800000000000000000001)/100000000000000000000
Decimal('8.00000000000000000001')
>>> math.ceil(decimal.Decimal(800000000000000000001)/100000000000000000000)
8.0
math对值进行舍入并返回非精确值您可以使用上下文构造函数的精度和舍入模式选项执行此操作
ctx = decimal.Context(prec=1, rounding=decimal.ROUND_CEILING)
ctx.divide(decimal.Decimal(800000000000000000001), decimal.Decimal(100000000000000000000))
编辑:你应该考虑改变接受的答案。虽然
prec
可以根据需要增加,但是到积分精确
是一个更简单的解决方案。获取小数实例上限的最直接方法x
是使用x.to积分精确(四舍五入=圆形上限)
。这里没有必要弄乱上下文。请注意,这将在适当的情况下设置不精确
和舍入
标志;如果您不想触摸标志,请使用x.to\u integral\u value(舍入=舍入\u天花板)
。例如:
>>> decimal.Context(rounding=decimal.ROUND_CEILING).quantize(
... decimal.Decimal(800000000000000000001)/100000000000000000000, 0)
Decimal('9')
>>> 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
实例。这是因为Python 3中的自定义类型可以重载math.ceil
。在Python2中,math.ceil
首先简单地将Decimal
实例转换为float
,在这个过程中可能会丢失信息,因此您可能会得到不正确的结果。只需使用有效性即可。
输入数学
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
完美:)---完成角色限制---@Alex抱歉在6分钟超时前离开。谢谢你的提醒。这不能很好地概括;它只在这种情况下起作用,因为结果在[1,10]范围内。例如,尝试使用十进制(123)/十进制(10)进行相同的计算,您将得到
Decimal('2E+1')
。这很好,但不需要在此处更改上下文精度to_integral\u exact
还需要一个舍入
参数,因此您可以避免完全混淆上下文。请注意,此解决方案对于具有大值的十进制
实例存在问题:例如,如果您尝试使用上下文c.quantize(Decimal.Decimal('1e100'),1)
,您将得到一个invalidooperation
异常。我是python新手,事实上昨天刚开始。在我的第二个练习项目中偶然发现了这个问题(第一个当然是强制性的“打印‘你好,世界!;”)。所以,我发现很难判断最好的答案。Matthew Flaschen的decimal.Context解决方案在我的特殊情况下有效。但我希望其他人能投票选出最好的解决方案(如果你能解释为什么某种方法效果更好,对我这样的新手也会很有帮助),我会回来接受。只是为了完整性:在Python2.xmath中,ceil
无法按预期工作:它首先将十进制转换为浮点。正因为如此,int(ceil(D('1.000000000000000 1'))
在Python2.x中计算为1,在Python3中计算为2。x@AntonyHatchkins:谢谢,说得好。我已经把这些信息编辑成了答案。
>>> from decimal import getcontext
>>> getcontext().prec = 2
>>> x.to_integral_exact(rounding=ROUND_CEILING)
Decimal('-123')
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