Division In Python
We have seen division way back in one of our earlier tutorials. In Python 3, there are two different types of division we can do first one being true division and the second being floor division. Understanding what value you need to return to you is key when working with division in Python.
What Is True Division In Python
True division is represented by a single backslash(/) and we get our results as a floating point number which will return the remainder in the position after the decimal.
True Division Examples
#True Division Examples
>>> 3 /7
0.42857142857142855
>>> 8 / 9
0.8888888888888888
>>> 90 / 3
30.0
>>> 8 / 5
1.6
>>> 45890 / 78
588.3333333333334
>>> 89 / 12
7.416666666666667
>>> 90.0 / 3
30.0
Floating Point Accuracy
We have talked about the floating point accuracy a lot in our previous tutorials. When using division in Python we see a lot of numbers returned inaccurate do the fraction and floating point conversion. To fix these issues, we need to use the built-in function round() or the decimal module that is available to us. We will not cover them in this tutorial so if you have not seen those tutorial I suggest your visit the round() tutorial or decimal module tutorial.
What is Floor Division
Floor division is represented by a double backslash(//). Floor division will return with a rounded down floating point number or integer and this return type is based off which type we use in the equation. Which means that we will not get a remainder when we use the floor division operator.
Floor division Example
#Floor division Example
#integers
>>> 89 // 9
9
>>> 124345 // 67
1855
>>> 345 // 8
43
>>> 89 // -6
-15
>>> 787643 // 2345
335
#floats
>>> 689.90 // 987
0.0
>>> 8976.98 // 76
118.0
>>> 865 // 8
108
>>> 78.6768789789 // 2
39.0
>>> 765734.1 // 67.3
11377.0
Conclusion
We have just seen how to perform division in Python. When writing your program, you need to figure out how precisely you would like your numbers. If you need a precise number, then I would use true division if you need a number that was not as precise the floor division may be a better decision.
If you have any questions about our Python tutorial on division in Python leave, a comment below and we will help you out.
Division In Python - Python Numbers
SO INFORMATIVE CONTENT
ReplyDeletePython Training in Gurgaon
Thanks for sharing this valuable information and we collected some information from this blog.
ReplyDeletePython Training in Gurgaon