简体   繁体   中英

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.

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. (like what happened to division in future package: 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. 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. 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). anyhow I think the best solution for this problem so far is using Decimal in python and BigDecimal class in Java

Yes, take a look at the Decimal library: 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 .

and

print(a + b)

returns 0.9 .

Some other options are listed here: Clarification on the Decimal type in Python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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