Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 25, 2022 08:55 pm

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.


Using the Decimal Module
































TaskTypical Functions 
Creating a Decimal Number
Decimal() constructor
 
Using Context to Set Rounding and Precision
getcontext().prec, getcontext().rounding
 
Math Operations on Decimals
sqrt(), exp(), log()
 
Working with Context in the Decimal Module
setcontext(), localcontext()
 

Using the Fractions Module
































TaskTypical Code 
Creating Fractions
Fraction() constructor
 
Arithmetic With Fractions
+, -, *, / operators
 
Numerator and Denominator Functions
limit_denominator() function, numerator, denominator properties
 
Fractions and the Math Module
math.sqrt(), math.floor()
 


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. After that, you can create decimals from integers, strings, floats, or tuples.



Creating a Decimal Number


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.




Using Context to Set Rounding and Precision


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.




Math Operations on Decimals


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




Working with Context in the Decimal Module


We briefly touched upon the concept of context in the previous section when we used the getcontext() function. The context objects in Python's decimal module are used to determine a lot of things like the precision, rounding rules and exception raising behavior while performing arithmetic calculations.


You can get and set the current context for calculations using the getcontext() and setcontext() functions. Using the localcontext() function alongside the with statement allows you to temporarily change the context for calculations.


There are three built-in contexts in the module that you can use for your calculations. The BasicContext sets precision to nine and rounding algorithm to ROUND_HALF_UP. The ExtendedContext also keeps precision at nine but sets the rounding algorithm to ROUND_HALF_EVEN. Finally, the DefaultContext sets the precision to 28 but keeps ROUND_HALF_EVEN as its rounding algorithm. Another difference among these contexts is the exception raising behavior. No exceptions are raised with ExtendedContext. Three exceptions are present in the DefaultContext related to numerical overflow, invalid operation and division by zero. Almost all exceptions are enabled for BasicContext.


This makes BasicContext ideal for debugging and ExtendedContext ideal for situations where you don't want to halt program execution. As you might have guessed, the DefaultContext is used as default context for the calculations.


Here is an example of using different contexts to get different results for a simple division:



Besides noticing the difference in precision and rounding algorithm for different contexts, you have probably also observed that a division by 0 under ExtendedContext did not raise an exception but output the result as Infinity.


A lot of functions in the decimal module also accept a context object as an argument for performing their calculations. This way you can avoid constantly setting context or precision values for computation.




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.



Creating Fractions


The fractions module 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:




Arithmetic With Fractions


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




Numerator and Denominator Functions


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.




Fractions and the Math Module


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.



Original Link: https://code.tutsplus.com/tutorials/mathematical-modules-in-python-decimal-and-fractions--cms-27691

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code