为什么小数不与浮点数互操作

sanyash:

关于十进制的注释说:

## Decimal has all of the methods specified by the Real abc, but it should
## not be registered as a Real because decimals do not interoperate with
## binary floats (i.e.  Decimal('3.14') + 2.71828 is undefined).  But,
## abstract reals are expected to interoperate (i.e. R1 + R2 should be
## expected to work if R1 and R2 are both Reals).

我不明白为什么Decimal('3.14') + 2.71828 is undefined可以从浮点数构造小数,因此我认为__add__可以如下实现:

def __add__(self, other):
    if isinstance(other, float):
        return self + Decimal(other)
    ...

有了它,我们将能够得到 Decimal('3.14') + 2.71828 = Decimal('3.14') + Decimal(2.71828) = 5.858280000000000153903556566

您能否解释一下为什么它们在当前实施中不互操作?

编辑:在将float转换为十进制时,可以先将其转换为str,以节省精度:

def __add__(self, other):
    if isinstance(other, float):
        return self + Decimal(str(other))
    ...

这样就Decimal('3.14') + 2.71828 = Decimal('3.14') + Decimal('2.71828') = 5.85828不会失去精度。

冷:

密钥以Decimal初始化的方式进行

请注意,在文档中的所有示例中,Decimal都是如何由制成的string它使我们可以在存储数字时传递数字而不会降低精度。

number = Decimal('1.1')
print(number)

上面代码的输出将始终为 Decimal('1.1')

完全可以Decimal使用a进行初始化float,但是我们首先失去了要使用Decimal的精度。考虑下面的代码行。

number = Decimal(1.1)

里面的值是number什么?在我的例子中,输出是

Decimal('1.100000000000000088817841970012523233890533447265625')

1.1存储在中float,这意味着精度下降。然后我们用它来初始化一个Decimal这就是为什么您应该Decimals使用string而不是进行初始化float以避免丢失精度的原因,这Decimal毕竟是首先使用的全部要点

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章