Numbers In Python
Numbers In Python
Python int:
For example:
a=5
Python int hold a value of any length, the only limitation being the amount of
memory available.
For example:
a = 123456890000001234565
We can use type function to check the type of the value we have entered,
type(a)
<class ‘int’>
isinstance(a, bool)
it results False, because a is of type int.
We can create an exponential number using the letter ‘e’ between the
mantissa and the exponent.
a = 2e2 # It is equivalent to 2 * 10 ** 2
print(a)
print(type(a))
print()
b = 2 * 10 ** 2
print(type(b))
Remember that the exponential e here is used to create powered values with
the base 10. To raise a number to another’s base power, we use the **
operator.
Python float:
#%%
# providing coefficient for 'j' is mandatory to create complex number
z=3+j
print(z)
# It results an error.
#%%
# We can use 1 to create complex number with the imaginary part
z = 3 + 1j
print(z)
#%%
a = 2 + 2j
b = 1 + 1j
# We can perform arithmetic operations on complex numbers as well,
# Remember that j^2 = -1
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print((1j)**2)
#%%
# We can also use inplace assignment operator on complex number
a = 2 + 2j
a += 2 + 4j
print(a)
#%%
# Writing numbers in binary, octal, and hexadecimal in Python
# We can write a binary number using the prefix 0b or 0B
bn1 = 0b1011
print(bn1)
bn2 = 0B1011
print(bn2)
#%%
# We can convert the binary numbers in to an int using int function
print(int(0b1011))
#%%
# Octal Numbers in Python : Uses prefix 0o or 0O
oc1 = 0o1234
print(oc1)
oc2 = 0O1234
print(oc2)
#%%
# Octal number has the numbers from 0-7
oc3 = 0o12348
print(oc3)
#%%
# Hexadecimal Numbers in Python
# The hexadecimal number system has numbers 0-9 and then A-F.
# and the prefix as 0x or 0X.
hexa1 = 0x1234
print(hexa1)
hexa2 = 0x12A
print(hexa2)
#%%
print(0XA)
print(0XB)
#%%
Python Conversion Functions
Although most times Python does the conversion as needed, you can do it
explicitly if you want.
These functions allow us to convert one numeric type into another python
numeric data types.
#%%
# We can't convert complex to int
a = 2 + 2j
b = int(a)
c = 2j
d = int(c)
#%%
#%%
# hex() in Python
print(hex(255))
print(hex(234.9))
print(hex(0))
print(hex(1))
print(hex(9))
print(hex(10))
Number Type Conversion
Python allows the conversion of data from one type to another in two ways.
• Implicit type conversion
x = 99
y = 1.111
#addition
z = x+y
These two methods are used to round a float number to the nearest integer.
As the name suggests, ceil() method is used to round the number UP to the
nearest integer value while floor() is used to round a number DOWN to the
nearest integer value.
import math as m
a = 1.4
print(m.ceil(a))
print(m.floor(a))
In addition to the above methods, math module also provides some frequently used
constants like pi. Let us see this with an example below.
import math
pi = math.pi
print(pi)
#To find the degree equivalent of the radians
print("Degree value of pi is ::",math.degrees(pi))
We can find the trigonometric sin and cos values using built-in methods in the
python math module.
We can find the sin value of an angle in radians using the sin() method. Similarly, we
can find the cos value of the angle in radians using the cos() method.
#sin value of 90
radians_90=math.radians(90)
print("sin value of pi/2 is ::", math.sin(radians_90))
#cos value of 60
radians_60 = math.radians(60)
print("cos value of pi/2 is ::", math.cos(radians_60))
factorial()
#factorial of 6 : 6*5*4*3*2*1
print("factorial of 6 is ::", math.factorial(6))
We can truncate a number to its nearest integer using the trunc() method. This
method will not return the negative sign, if any.
import math
Checking Functions
In math module, there are methods to check whether a number is either finite
or infinite. We also have a method to check whether an argument is number or
not.
isnan()
We can also check whether the argument we pass is a number or not using
the isnan() method.This method will return true the passed argument is not a
number.
#checking whether it is a number or not
print("IS a number or not::", math.isnan(math.nan))
isclose()
In addition to the above methods, there are methods that are commonly used like
#finding sqrt
print("The square root of 25 is ::", math.sqrt(25))
print("The square root of 10 is ::", math.sqrt(10))
#exponential value
print("The value os e(x) is::", math.exp(-2))
#Number raised to power
print("The value of 9^3 is ::", math.pow(9, 3))
bit_length()
This method is used to find the number of bits to represent a number in binary
format excluding the sign and leading zeros.
i=-99
print("bit length::", i.bit_length())
to_bytes()
(24).to_bytes(3, byteorder='big')
The above output shows the array of bytes to represent the integer value 24.
The byteorder argument determines the byte order used to represent the integer. In
case the byteorder is “big”, the most significant byte is at the beginning of the byte
array. In case the byteorder is “little”, the most significant byte is at the end of the
byte array. The integer is represented using length bytes. If the integer cannot be
represented within that length then we will get Overflow error.
is_integer()
f=0.25
f.is_integer()
as_integer_ratio()
We can represent the floating number as an integer number ratio. In case of not a
perfect fraction ,then the nearest possible ratio will be returned.
f=0.25
f.as_integer_ratio()
Due to the limitations of the floating-point arithmetic some decimal numbers cannot
be represented exactly in base 2 binary fractions.
To prevent some data loss while performing mathematical operations, especially in
numbers with decimal digits, Python provides a separate module, ‘Decimal.’
With the help of the decimal module we can actually set the precision of the number
to be displayed up to 28 digits. Based on the requirements we can actually specify
the amount of precision while representing the decimal numbers.
• Passing a tuple inside the decimal() constructor: Tuple will have three-
part. The first part will be 0 for positive and 1 for negative. The second
part will be the Integer component.
We can even set flags like ROUND_CEILING,ROUND_FLOOR,ROUND_UP,ROUND_DOWN and traps to
raise a Python exception during conditions like Division by Zero.By default certain
conditions like the division by zero are set to true only.
import decimal
from decimal import *
print(Decimal(0.01))
print(Decimal('0.05'))
print(Decimal((1, (9,9,9,9), -2)))
Decimal Methods
getcontext()
We can set the precision using the getcontext() method and even set the flags to
mention whether we need to round the digits up or Down.
print(Decimal(3) / Decimal(77))
We can limit the number of digits in the above output by setting the precision using
the getcontext().
getcontext().prec = 2
getcontext().rounding = decimal.ROUND_UP
print(Decimal(3) / Decimal(77))
Mathematical Operations
In addition to this, we have the flexibility of using all the mathematical functions
like sqrt,log , etc; available in the decimal module as well.
import decimal
from decimal import Decimal, getcontext
getcontext().clear_flags()
print(Decimal(2).sqrt())
A fraction can be formed from a decimal , float, integers ,another rational number or
a string.Let us see each one with a small example. We have to import the fractions
module first.
limit_denominator()
Some fractions are lengthy, and we can use the limit_denominator() method to limit
the number of digits in the denominator. Let us see this with an example.
As fractions have two parts, namely a numerator and a denominator, there are
methods to access both.
from_float()
Fraction.from_float(0.25)
Output
Fraction(1, 4)
We can use the ceil() and floor() methods of the math module to find the nearest
integer above or below the fraction value.
import math
math.ceil(Fraction(300, 124))