In this article you will learn about types of numbers in python and their mathematical operations.
So these are the contents of this article :
Introduction
Python supports integer, floating-point number and complex number. as we discussed about previous.
Numbers we deal with every day are decimal (base 10) number system. But computer programmers (generally embedded programmer) need to work with binary (base 2), hexadecimal (base 16) and octal (base 8) number systems.
In Python, we can represent these numbers by appropriately placing a prefix before that number. The following table lists these prefix.
- Binary : ‘0b’ or ‘0B’
- Octal: ‘0o’ or ‘0O‘
- Hexadecimal : ‘0x’ or ‘0X‘
Python Decimal
We all know the sum of 1.1 and 2.2 is 3.3. But Python disagrees it.
It turns out that floating-point numbers are implemented in computer hardware as binary fractions, as the computer only understands binary (0 and 1). Due to this reason, most of the decimal fractions we know, cannot be accurately stored in our computer.
This will only approximate 0.1 but never be equal. Hence, it is the limitation of our computer hardware and not an error in Python.
In order to overcome this problem, the module has been introduced in python is the decimal numbers. The floating-point numbers have been set 15 decimal places.
The output of the above code will be:
Need of Decimal
Here might be a question arises that why we need decimal though there’s float. The answer is that :
- In the field of financial applications that need exact decimal representation.
- To implement the notion of significant decimal places in numerical methods.
Python Fractions
Python provides a module called fraction which supports rational numbers in mathematics.
import fractions
# Output: 1/2
print(fractions.Fraction(0.5))
# Output: 10
print(fractions.Fraction(10))
# Output: 1/4
print(fractions.Fraction(1,4))
The following is the output of the above code
Python Mathematics
Python offers different modules like math, random, trigonometry etc. which we will discuss in another article named as “Python Modules”.
Happy coding….