有没有办法禁止 python 中的舍入?

Is there a way to inhibit rounding in python?

有没有办法抑制 python 舍入,例如:

>>> getcontext().prec = 11; print (Decimal(1.1237836550999999999)*10**10)
11237836551

我需要显示小数的前 10 位小数,所以实际上我需要 11237836550 作为输出,我不需要在最后一位进行舍入(在本例中,0 舍入为 a 1).

有时我可以提高精度(在这种情况下不是)然后安全地执行计算,就像这样:

>>> getcontext().prec = 14; print (Decimal(1.12378365509978)*10**10)
11237836550.998

但是假设您不知道“0”之后数字的小数部分,例如它可能是 1.1237836550999999999999999999999999... 等等,然后你不能依赖这个 'workaround'.

那么,有没有办法告诉python,"for this calculation, I don't want any rounding to be performed, actually I want that you just return me the needed number of decimals (10 in this example), and throw away anything else after it"?

我看了这里 Truncating floats in Python,但基本上我需要的不是截断浮点数的字符串,而是用于执行计算的另一个小数。 此外,我链接的 post 中已接受答案的 trunc 函数在这种情况下将不起作用,因为 Decimal 将在传递给函数的 'f' 参数之前四舍五入:

>>> def trunc(f, n):
...     '''Truncates/pads a float f to n decimal places without rounding'''
...     return ('%.*f' % (n + 1, f))[:-1]
... 
>>> trunc(Decimal(1.12378365509978), 10)
'1.1237836551' # and not 1.1237836550 as needed

我怎样才能做到这一点?

这是您要查找的内容吗:

from decimal import *

getcontext().prec = 103

def precision(context, prec=100):

    return Decimal(context).quantize(Decimal('.'+'0'*(prec-1)+'1'), rounding=ROUND_DOWN)

print precision(Decimal(10).log10() / Decimal(2).log10())

输出:

3.3219280948873623478703194294893901758648313930245806120547563958159347766086252158501397433593701550

你的问题不是Decimal。是 float。即:

>>> 1.1237836550999999999
1.1237836551

但如果你这样做:

>>> int(Decimal("1.1237836550999999999")*10**10)
11237836550

一切顺利。以更高的精度初始化小数时使用字符串。