简体   繁体   English

Python和Java包可实现浮点精度

[英]Python and java package for floating point accuracy

During writing a program in python (the same in Java) I faced the following problem which I know it's because of rounding error. 在用python编写程序(与Java相同)的过程中,我遇到了以下问题,我知道这是由于舍入错误引起的。

a = 0.3
b = 0.6;
print(a+b) #returns 0.8999999999999999 which makes a+b==0.9 false

I was wondering is there any package in python (and Java) which can make life easier for such situation and instead of defining an error bound in the application and checking it by yourself just import the package and it takes care of the rest. 我想知道在python(和Java)中是否有任何软件包可以使这种情况的生活变得更轻松,而不是在应用程序中定义错误绑定并自己检查它,只需导入该软件包,其余的就交给您了。 (like what happened to division in future package: http://legacy.python.org/dev/peps/pep-0238/ ) (例如将来的软件包中划分所发生的事情: http : //legacy.python.org/dev/peps/pep-0238/

EDIT: So far(July 2016) as I know it's only Decimal class that you can use it. 编辑:到目前为止(2016年7月),我知道它是唯一可以使用的Decimal类。 The problem is that I don't like the way that we should define every time Decimal class instead of just assigning the value for variable. 问题是我不喜欢每次定义Decimal类的方式,而不仅仅是为变量赋值。 I was just looking for a package that after importing , it takes care of the numbers and converted them to decimal automatically( like what happens in future package that after importing it takes care of division operation). 我只是在寻找一个导入后会处理数字并将其自动转换为十进制的程序包(就像future程序包中发生的情况一样,导入后会进行除法运算)。 anyhow I think the best solution for this problem so far is using Decimal in python and BigDecimal class in Java 无论如何,我认为到目前为止,此问题的最佳解决方案是在python中使用Decimal和在Java中使用BigDecimal

Yes, take a look at the Decimal library: https://docs.python.org/2/library/decimal.html 是的,看看Decimal库: https : //docs.python.org/2/library/decimal.html

from decimal import Decimal
a = Decimal('0.3')
b = Decimal('0.6')
a + b == Decimal('0.9')

returns True . 返回True

and

print(a + b)

returns 0.9 . 返回0.9

Some other options are listed here: Clarification on the Decimal type in Python 这里列出了一些其他选项: 在Python中对Decimal类型的澄清

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM