Decimal Module in Python For Accurate Floats
Key Takeaways
The video discusses the decimal module in Python, which is used to work with floating point arithmetics in a reliable way, and demonstrates how to use it to accurately represent decimal numbers and prevent rounding errors.
Full Transcript
what is going on guys welcome back in today's video we're going to learn about something quite interesting we're going to learn how to work with decimals in Python and why this is necessary so let us get right into it [Music] all right so we're going to keep this simple and straight to the point try the following thing in Python type print and then add two simple numbers like one plus two and then compare the result of this calculation to the result that it should have so one plus two is three so we want to know is one plus two equal to 3 and then run the script and you're going to see true this is the case obviously why shouldn't it be so let's try something else now and some of you might already know what I'm going to talk about here let's try to do 0.1 plus 0.2 and let's see if that is equal to 0.3 which is mathematically the case right 0.1 plus 0.2 is 0.3 so let's start this and you can see the result is false and this is not just because we're working with floating Point numbers because for other numbers we might actually get the correct results so let's see for example if 0.2 plus 0.2 is equal to 0.4 in this case we get it true so there seems to be a problem when working with some floating Point numbers and actually in this video I don't want to go into the full explanation behind why this is happening because I have done this on the channel already you can go to my channel and find the video where I try to explain or where I where I do explain to you guys why 0.1 plus 0.2 is not equal to 0.3 exactly and we can actually see that this is the case by just printing 0.3 because when we print 0.3 uh sorry not 0.3 0 0.1 plus 0.2 you can see that the result is actually not 0.3 it's 0.3 followed by a bunch of zeros and then a 4 in the end so it's not exactly 0.3 and if you want to find out exactly um the theory why this is the case what exactly is happening behind the scenes again check out the other video today we're going to talk more about the solution to that and also uh in detail how we can work with the decimal module which is a core python module so we're going to start by saying here import decimal and we can see right away that this can solve the problem if we just go ahead and say print and then instead of saying 0.1 plus 0.2 we're now going to turn those numbers into decimals and we're going to do that first of all by passing a string and then we're going to do it without passing a string to see the differences here so I'm going to say decimal um by the way we should say from decimal import decimal you can of course also say decimal dot decimal but I like to use the class directly so print decimal and then we're going to use the Constructor of decimal to pass 0.1 as a string here and we're going to say decimal 0.2 as a string here and we want to print the result when we do that you can see the result is in fact 0.3 so we can actually also say okay is this the same as decimal 0.3 and you can see in this case this is true so we solved this basic problem here and the whole goal of this library of the decimal Library which is again as I said a core python module um is in fact to make arithmetics work like they do for us we humans do mathematics a certain way computers do it a different way and by using the decimal module we have a more intuitive more accurate correctly rounded floating Point arithmetic as we know it in actual mathematics so this is a simple way to do that and you can see though if I now remove the strings here so if I remove the quotations here and make those floating Point numbers here uh you will see that we will get the same problem here so if I run this you can see false is the result and we can actually print the result here and you can see we get a different result even we get three followed by a bunch of zeros followed by a couple more digits here so we have a rounding Arrow here again and the reason for that is that we have a certain context that we operate in when we work with the decimal module we have a certain context and the context includes a bunch of different settings and uh properties that we can change for example one of them the most important one probably is the Precision how precise do we need to be with our calculations with our rounding so we can go ahead and import here the get context function and we can say uh print for me please get context the result of get context and you can see we have here the current context that we're operating in we have a Precision of 28 decimal places we have the rounding method of around half even and a bunch of other things that we're not now gonna go deeper into but the Precision here is 28 which means that we have a very very high precision and um this of course allows all surrounding errors to happen because if you need all these numbers to be accurate yeah sooner or later you will fail probably due to the nature of the floating Point arithmetic in computers again if you want to know the details the theoretical details uh watch the other video here so the good thing is we can change the context here so we can say getcontext dot Precision so dot pretz and then we can set this for example to two which is let's do this before the calculation here and then you can see that this is in fact 0.30 so if I now compare this is this equal to decimal 0.3 uh we still have a problem why is that probably because 0.3 is not rounded correctly there you go so you can see we still have the problem because um other settings uh might might be problematic maybe if we go ahead and change the Precision to a higher number this might oh actually not this might actually um that this doesn't solve the problem but one thing that could solve the problem is to type cast these numbers into floats so we can go ahead and Typecast this into a float and then you can see that the result is exactly 0.3 so we have a Precision that we set here let's say six let's keep six foreign for now and let's say we have the variable a which is decimal and we're not going to use strings we're just going to use a floating Point number so that uh which didn't work up until now I'm going to say b equals decimal 0.3 and again let me show you once again if I just compare those a being equal to B we will get false even though the Precision is not uh super high even if I set this to 2 it's going to be false but if I now go ahead and say float of a and Float of B we're gonna Round Up um the number here and we're going to have the exact same number left and right because from 0.2999 whatever we're now operating here um with lower Precision now if I change this though if I change this back to 28 it should not work because then we have again way more Precision to work with because we have way more decimal places to consider and then we don't round up or we don't round up to three at least so to 0.3 so we can change the context in the context um changes the result of the calculations the whole purpose of this is that you specify the context that you want to work in or that you want to work uh with and then you can operate inside of that context and you know whatever I do here the results are going to be in that context I'm going to have I'm going to have this Precision this accuracy and you can prevent rounding errors because if you don't do anything like that if you don't work with decimal if you don't change the context you're just going to get the rounding errors no matter what you do if you say 0.1 plus 0.2 you're gonna get not zero point three you're gonna get something else of course you can just go math dot round or actually I think round is not even a math function you can just go around you can do that of course and you can also truncate and all that stuff but using decimal is the more professional way to go the more uh best practice go-to weight so let's talk a little bit more about the context here we can also create the context so we can create a context as an actual object we can say for example new context is equal now what is happening here new context is equal to um decimal actually let's import this let's say we import context so we don't have to use decimal we can just say this is a context from the decimal module here and we can specify now as keyword arguments the respective settings so I can say Precision is six or let's say 10 and then we can say the rounding that is happening here is um then we have to let's just import decimal here for a bunch of things as well we can say the rounding is equal to decimal Roundup for example and then we can go ahead and say decimal dot set context so this is the opposite of get context get context gives us the current context set context sets a new context and here we can just say new context and then um we can we can see how the results change when we change the context again so 0.1 um or actually let's do something else let's do 0.123 uh plus decimal 0.5678 let's see what we get here's the result we get this number here if I say Precision two probably we're going to get a different number because we have less decimal places to care about so you can see that the context changes here we can also do even some more advanced stuff with the context so for example let's say uh we all know that that we cannot divide by zero we get actually uh an undefined result if you say for example 5 divided by zero that's not defined in mathematics because it leads to all sorts of problems but you can go ahead now and say decimal one uh or let's go five this was the example decimal five divided by decimal zero and you're gonna get the problems you get division by zero error however we can also Define in our context here that we don't want this to happen we might want to say here for the purpose of what we are doing here for whatever reason we want the result of dividing by zero to be Infinity because that is one possible thing that you could say you know if you have five resources and you have to distribute them to zero people one person is going to have infinitely many resource sources might not make sense but maybe you want to do it first for a specific reason so what you can do here is you can go ahead and say uh get context and you can say dot traps and uh then you can say decimal dot division by zero equals false so this is no longer a trap so to say which basically means we allow this to happen and if I run this now you can see Infinity is the result and then I can work with that result I can say infinity times two it's still going to be Infinity so we can work with that um that is one thing what else do we have um yeah so so that's basically about the context now we can also do some some other stuff that is not just adding multiplying and so on so we can use all the mathematical functions for example um I can say import math and then I can say print uh math dot square root of 0.3 this is one thing that I can do and then I can also do decimal 0.3 and then dot sqrt let's see if we get the same result I'm actually not sure uh okay we get basically the same result this one is more accurate so if we change the context we get uh different accuracy whatever but you can use mathematical functions like this so you can go with with square root with x uh with the X function so e to the power off whatever we have here uh or the logarithm base 10 is also an option here you can play around with the different functions now one thing that I would like to mention is that the reason why the results differ when we pass a floating Point number or a string is because when we pass a string we limit the accuracy to what we have so if I pass 0.1 that is exactly 0.1 if I pass it as a string if I don't pass it as a string if I pass it as a floating Point number it's going to be more accurate it's going to take into account all the decimal places and so on um so yeah when we when you enter a string here when you pass a string you're going to have less problems usually so uh then what what else do we have we can quantize basically meaning that if I have something like um a is a decimal 0.3 or something and then I can print a there you go um and in this case I can also say print a DOT quantize and then I can say decimal zero let's use a string here 0.000 and then I can pass decimal Dot round up and you're gonna see that we get the number in this format so this is the format 0 and then three decimal places and then I take this I quantize it and I get the same format this is one little thing that we can do here as well and last but not least I would like to show you some special values that we can use uh we talked about Infinity already so I can say decimal and pass as a string infinity and then we can work with infinity as a value I cannot just pass anything here so if I pass something else it's going to say invalid operation Infinity works and I can also calculate I can do calculations with infinity I can say 20 times infinity uh I'm not sure if I can say infinity times negative one if I get Negative Infinity then yeah I do get Negative Infinity okay that's nice so we can do that and we can also do uh not a number so we know nands from numpy and from pandas and so on but you can get another number value here as well representing just something that is not a number uh and the absolute last thing that I want to do here is I want to show you the um how to create how to map the decimal Constructor onto value so if you have a bunch of values you can map the decimal construction turn all these values into decimals so what you can do is you can say um list so the whatever we get here as a result we want to turn into a list and uh we're going to say map we want to map the decimal Constructor onto a list of values so 0.1 0.2 0.3 and 0.4 for example there you go and then we have these decimal results here of course when we change the context we're going to get less accuracy but in this case you get very very accurate numbers uh with the respective rounding errors so you can see that those numbers are not exactly 0.1 when we humans talk about 0.1 we mean 0.1000 until eternity no other values afterwards computers cannot do that so when we want to work with floating Point arithmetics the way we humans understand them and not the way computers operate we would be advised to use the decimal module in Python so that's it for today's video I hope you enjoyed it and hope you learned something if so let me know by hitting a like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this Channel and hit the notification Bell to not miss a single future video for free other than that thank you much for watching see you next video and bye [Music]
Original Description
In this video, we will discuss the decimal module in Python, which is used to work with floating point arithmetics in a reliable way.
◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾
📚 Programming Books & Merch 📚
🐍 The Python Bible Book: https://www.neuralnine.com/books/
💻 The Algorithm Bible Book: https://www.neuralnine.com/books/
👕 Programming Merch: https://www.neuralnine.com/shop
🌐 Social Media & Contact 🌐
📱 Website: https://www.neuralnine.com/
📷 Instagram: https://www.instagram.com/neuralnine
🐦 Twitter: https://twitter.com/neuralnine
🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/
📁 GitHub: https://github.com/NeuralNine
🎙 Discord: https://discord.gg/JU4xr8U3dm
🎵 Outro Music From: https://www.bensound.com/
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeuralNine · NeuralNine · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
Python Beginner Tutorial #5 - Loops
NeuralNine
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
Python Beginner Tutorial #7 - Functions
NeuralNine
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
Python Beginner Tutorial #9 - File Operations
NeuralNine
Python Beginner Tutorial #10 - String Functions
NeuralNine
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
Python Intermediate Tutorial #6 - Queues
NeuralNine
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
Python Intermediate Tutorial #9 - Recursion
NeuralNine
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
Python Intermediate Tutorial #11 - Logging
NeuralNine
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
Python Machine Learning #4 - Support Vector Machines
NeuralNine
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
Making Text Images Readable Again with Python and OpenCV
NeuralNine
Neural Networks Simply Explained (Theory)
NeuralNine
Motion Filtering with OpenCV in Python
NeuralNine
Top 5 Programming Languages To Learn in 2020
NeuralNine
Simple TCP Chat Room in Python
NeuralNine
Image Classification with Neural Networks in Python
NeuralNine
Edge Detection with OpenCV in Python
NeuralNine
S&P 500 Web Scraping with Python
NeuralNine
Simple Sentiment Text Analysis in Python
NeuralNine
Introduction - Algorithms & Data Structures #1
NeuralNine
More on: AI Pair Programming
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Bloom Filters, Explained Properly
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Medium · Python
🎓
Tutor Explanation
DeepCamp AI