Mathematical Modules in Python: Decimal and Fractions

Even the most basic mathematical operations can sometimes give an erroneous result. This happens due to limitations in storing the exact value of some numbers. You can overcome these limitations by using the decimal module in Python. Similarly, neither the math nor the cmath module that we learned about in our last tutorial can help us in doing fraction-based arithmetic. However, the fractions module in Python does exactly that.

In this tutorial, you will learn about both these modules and the different functions they make available. 

Why Do We Need a Decimal Module?

You are probably wondering why we need a module to do basic arithmetic with decimal numbers when we can already do the same using floats.

Before I answer this question, I want you to take a guess about the output value if you type 0.1 + 0.2 in the Python console. If you guessed that the output should be 0.3, you will be surprised when you check out the actual result, which is 0.30000000000000004. You can try some other calculation like 0.05 + 0.1 and you will get 0.15000000000000002. 

To understand what's going on here, try to represent 1/3 in decimal form, and you will notice that the number is actually non-terminating in base 10. Similarly, some numbers like 0.1 or 1/10 are non-terminating in base 2. Since these numbers still need to be represented somehow, a few approximations are made while storing them, which results in those errors.

The number 0.30000000000000004 is actually very close to 0.3, so we can get away with this approximation most of the time. Unfortunately, this approximation is not going to cut it when you are simulating a satellite launch or dealing with money. Another problem with these approximations is that the errors keep piling up. 

To get precise results like the ones we are used to dealing with when doing calculations by hand, we need something that supports fast, correctly rounded, decimal floating point arithmetic, and the decimal module does exactly that.

Using the Decimal Module

Before using the module, you need to import it first. After that, you can create decimals from integers, strings, floats, or tuples. When the decimal is constructed from an integer or a float, there is an exact conversion of the value of that number. Take a look at the examples below to see what I mean:

As you can see, the value of Decimal(0.05) is slightly different from Decimal('0.05'). This means that when you add 0.05 and 0.1, you should use decimal.Decimal('0.05') and decimal.Decimal('0.1') to construct the decimals.

Now that you can perform various operations on decimals, you might want to control the precision or rounding for those operations. This can be done by using the getcontext() function. This function allows you to get as well as set the value of the precision and rounding options, among other things. 

Please keep in mind that both rounding and precision come into play only during arithmetic operations and not while you are creating the decimals themselves.

You can also use some of the mathematical functions like sqrt(), exp(), and log() with decimals. Here are a few examples:

Using the Fractions Module

Sometimes, you might face situations where you need to perform various operations on fractions or the final result needs to be a fraction. The fractions module can be of great help in these cases. It allows you to create a Fraction instance from numbers, floats, decimals, and even strings. Just like the decimal module, there are a few issues with this module as well when it comes to creating fractions from floats. Here are a few examples:

You can also perform simple mathematical operations like addition and subtraction on fractions just like regular numbers.

The module also has a few important methods like limit_denominator(max_denominator) which will find and return a fraction closest in value to the given fraction whose denominator is at most max_denominator. You can also return the numerator of a given fraction in the lowest term by using the numerator property and the denominator by using the denominator property.

You can also use this module with various functions in the math module to perform fraction-based calculations.

Final Thoughts

These two modules should be sufficient to help you perform common operations on both decimals and fractions. As shown in the last section, you can use these modules along with the math module to calculate the value of all kinds of mathematical functions in the format you desire.

In the next tutorial of the series, you will learn about the random module in Python.



Related Articles