比较python中的小数 [英] Compare decimals in python

查看:291
本文介绍了比较python中的小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够比较Python中的小数。为了用钱进行计算,聪明的人告诉我使用小数而不是浮点数,所以我这样做了。但是,如果我想验证计算是否会产生预期的结果,该如何处理?

I want to be able to compare Decimals in Python. For the sake of making calculations with money, clever people told me to use Decimals instead of floats, so I did. However, if I want to verify that a calculation produces the expected result, how would I go about it?

>>> a = Decimal(1./3.)
>>> a
Decimal('0.333333333333333314829616256247390992939472198486328125')
>>> b = Decimal(2./3.)
>>> b
Decimal('0.66666666666666662965923251249478198587894439697265625')
>>> a == b
False
>>> a == b - a
False
>>> a == b - Decimal(1./3.)
False

所以在此例如a = 1/3和b = 2/3,因此显然ba = 1/3 = a,但是,不能使用小数。

so in this example a = 1/3 and b = 2/3, so obviously b-a = 1/3 = a, however, that cannot be done with Decimals.

我想这样做的方法是说我期望结果是1/3,在python中,我将其写为

I guess a way to do it is to say that I expect the result to be 1/3, and in python i write this as

Decimal(1./3.).quantize(...)

然后我可以像这样比较

(b-a).quantize(...) == Decimal(1./3.).quantize(...)

所以,我的问题是:有没有更清洁的方法?您将如何编写十进制测试?

So, my question is: Is there a cleaner way of doing this? How would you write tests for Decimals?

推荐答案

您未使用十进制

You are not using Decimal the right way.

>>> from decimal import *

>>> Decimal(1./3.)                  # Your code
Decimal('0.333333333333333314829616256247390992939472198486328125')

>>> Decimal("1")/Decimal("3")       # My code
Decimal('0.3333333333333333333333333333')

在您的代码中,您实际上执行了经典浮点除法-然后将结果转换为小数。 floats 引入的错误会传播到您的 Decimal

In "your code", you actually perform "classic" floating point division -- then convert the result to a decimal. The error introduced by floats is propagated to your Decimal.

在我的代码中,我执行十进制除法。产生正确(但被截断)的结果直到最后一位。

In "my code", I do the Decimal division. Producing a correct (but truncated) result up to the last digit.

关于四舍五入。如果使用货币数据,则必须知道用于业务四舍五入的规则。如果不是这样,使用 Decimal not 自动解决所有问题。这是一个示例:$ 100将要在3个股东之间分享。

Concerning the rounding. If you work with monetary data, you must know the rules to be used for rounding in your business. If not so, using Decimal will not automagically solve all your problems. Here is an example: $100 to be share between 3 shareholders.

>>> TWOPLACES = Decimal(10) ** -2

>>> dividende = Decimal("100.00")
>>> john = (dividende / Decimal("3")).quantize(TWOPLACES)
>>> john
Decimal('33.33')
>>> paul = (dividende / Decimal("3")).quantize(TWOPLACES)
>>> georges = (dividende / Decimal("3")).quantize(TWOPLACES)
>>> john+paul+georges
Decimal('99.99')

操作:缺少$ .01 (向银行免费赠送礼物吗?)

Oups: missing $.01 (free gift for the bank ?)

这篇关于比较python中的小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆