1

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

Reza
  • 1,516
  • 14
  • 23
  • So what are some things you'd want such a package to do? – President James K. Polk Oct 05 '14 at 13:00
  • 1
    I've already knew about Decimal class in python. 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. Is it kind of package that if we import it, it takes care about floating point, like changing all float values to Decimal class automatically. I'm pretty sure that it can be doable in python (and probably it can be done with injection and using BigDeicmal class in java). And I know it's hard to do it in java but probably there should be something else rather than using Decimal in python. – Reza Oct 06 '14 at 16:31

1 Answers1

2

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

Community
  • 1
  • 1
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
  • Thank you for the answer. I've already resolved my particular problem just with adding an error bound and I asked the question just for curiosity. Please look at the comment at the below of my question. – Reza Oct 06 '14 at 16:35