Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Python Decimal equivalent isclose method

I'm trying to compare two Decimals in Python with a tolerance of 0.01. When using Math isclose I receive False because of floating point inaccuracy. For example:

d = Decimal('123.12')
d1 = Decimal('123.11')
print(isclose(d,d1,abs_tol=0.01))

Will print out False. I know the reason for this I'm just trying to understand if there is a good way to compare Decimals in Python.

like image 210
royeet Avatar asked Oct 14 '25 09:10

royeet


1 Answers

The Decimal class implements many methods with which you can define the comparison easily as follows:

abs(d - d1) <= Decimal('0.01')
like image 138
ikkuh Avatar answered Oct 16 '25 21:10

ikkuh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!