0

Recently I got to know the decimal python module. While I got to understand how to work with this, I still have a question that persists:

What is/are the main case(s) where coders should use decimal.Decimal for float comparison?

For example, at the past I have already performed some automatic tests for installable packages. At this ones, I always performed the comparison among floats with pytest.aprox() or by comparing the absolute difference with an epsilon value.

Maybe my experience is still not enough to see which cases the decimal module is better. Could anyone provide some insights to me?

2
  • 3
    You don't use it for comparison, you use it for calculation. Commented Dec 2, 2024 at 12:33
  • 3
    PEP 327, which introduces Decimal, might be worth reading, especially the PEP's Motivation section. If you can't identify a case for using Decimal, then you probably don't have a use case for it. Commented Dec 2, 2024 at 12:50

1 Answer 1

1

The main reasons to use decimal.Decimal over float type:

1. High-Precision

decimal.Decimal is better chice if you want to get more accurate calculations, and to avoid rounding errors (because of Floating-point error mitigation).

2. Exact Representation of Decimal Numbers

Because of binary nature of float numbers, they sometimes cannot exactly represent many decimal numbers, for example:

0.1 + 0.2 == 0.3  # False

But when using decimal.Decimal:

from decimal import Decimal
Decimal("0.1") + Decimal("0.2") == Decimal("0.3")  # True

3. Using on different platforms

float arithmetic operations results can be different across platform because different IEEE 754 implementation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.