Python Tutorial : Part 4 : Python Numbers

_Python Numbers: _

Numbers are immutable datatype that is used to store numeric values. Python supports four different types of numeric types: integer, long, float and complex numbers. Long is available only in python 2.x, but not in 3.x.

Integer is abbreviated to int. An integer is a whole number. e.g. 2, 3, 0, -7 all are integers. 2 is an integer but 2.0 is not. They are known as float in python. So, integer and floats are separated by the presence or absence of a decimal point.

Long integers are denoted by appending an ‘L’ or ‘l’ after a number. Like 1L or 2L are long integers. It is recommended to use ‘L’ instead of ‘l’ as ‘l’ and ‘1’ can be mismatched. 

We can use isinstance() function to check if a number is of a particular datatype.

print isinstance(0,int)
print isinstance(1,int)
print isinstance(-7,int)
print isinstance(0L,int)
print isinstance(0L,long)

For the above program, the results will be:

True
True
True
False
True

Mathematical Operations with Integers :

_a) Addition ( + ), Subtraction ( - ), Multiplication( * ) and Division ( / ): _

Order : Multiplication and Division are done first. Then addition and substraction.

Division: The result will always a float

print (2+2)
print (2*2)
print (2*2-2)
print (2/2-2)
print (4*2/2-2)
print (5*3/5-2+6)
print (5*3/5+2-6)

The answers will be:

4
4
2
-1
2
7
-1

Floor division: As we have noticed, the division always results a float. Using floor division, we can have an integer. Two forward slashes ( // ) are used for this.

Modulo: Modulo operation is used to get the reminder of a number. Percent sign ( % ) is used for this.

 

Power: We can get the power of a number by using two asterisk keys ( ** )

print (4 // 2)
print (10 % 3)
print (5 ** 2)

The output will be: 

2
1
25

_Binary, Octal, and Hexadecimal:  _

In the real word, we normally use decimal or 10 base numbers. But in computer science, mainly Binary, Octal and Hexadecimal numerical system is used. In python, we can represent these numbers by placing a prefix:

Binary number ( base 2 ) prefix = ‘0b’ or ‘0B’
Octal number ( base 8 ) prefix = ‘0o’ or ‘0O’
Hexadecimal number ( base 16 ) prefix = ‘0x’ or ‘0X’
print (0B10)
print (0B10 + 0B10)
print (0o12)
print (0o12 + 0o12)
print (0xFE)
print (0xFE + 0xFE)

The output will be:

2
4
10
20
254
508

Python floats:

Integers are only positive numbers, 0 and negative numbers. i.e. they are whole numbers, not real numbers. To represent real numbers like 2.4, 4.0 etc, we use floats in python. 2 is an integer but 2.0 is a float.

The arithmetic operations we have performed for integers are also worked for floats.

print ( 2.3 + 2.4 )
print ( 5.4 - 2.1 )
print ( 4.4 * 1.1 )
print ( 4.4 / 2.2 )
print ( 4.4 // 2.2 )
print ( 4.4 % 2.2 )
print ( 1.1 ** 1.1 )

The output will be:

4.7
3.3
4.84
2.0
2.0
0.0
1.11053424105

Complex Numbers:

Complex numbers are represented as a + bj in python where ‘a’ and ‘ b’ are real number, ‘j’ is an imaginary number. ‘a’ and ‘b’ both treated as floats. We cannot use ‘j’ without ‘b’. To get the real part of an imaginary number, use ‘.real’ and to get the imaginary part, use ‘.imag’.

print ( 1 + 3j )
# print ( 2 + j ) #it will throw an error
print ( (1 + 2j).real )
print ( ( 1 + 2j).imag )

The output will be:

(1+3j)
1.0
2.0

_ Conversion :_

We can convert one number type into another. Built in function int( ) , float( ), complex( ) are used to convert from one type to another.

print int(3.4)
print float(4)
print complex(3)
print (1 + 3.0)

Following will be the output:

3
4.0
(3+0j)
4.0

In the fourth case, you can see that if one integer is added with a float, the result will also be a float.

Decimal :

Open a terminal, type “python” and hit enter. Now write “0.1 + 0.2” and hit enter. You can see the output is 0.30000000000000004. Shouldn’t it 0.3 only?

This is not a bug, it is because floating point numbers are represented as base 2 in computer hardware. Check this link for more information:

To overcome this problem, we can use Decimal class of python. Using this class, we can do mathematical operations normally. 

from decimal import Decimal as D
 
a = '0.1'
b = '0.2'
 
print ("adding "+str((D(a)+D(b))))
print ("multiplying "+str((D(a) * D(b))))

Above program will result: 

adding 0.3
multiplying 0.02

Remember that floating point operations are always faster than Decimal operations.

Fractions and mathematics:

Fraction: Fraction has a numerator and denominator.  Python has a fraction module we can use to create fraction from numbers. The following example will explain you how:

import fractions
 
for numerator,denominator in [ (2,3),(4,5),(6,7)] :
    f = fractions.Fraction( numerator, denominator )
    print ' %s/%s = %s ' % ( numerator, denominator , f)

The output will be :

 2/3 = 2/3
 4/5 = 4/5
 6/7 = 6/7

We can also use fraction for Strings:

import fractions
 
for s in [ '2/3','4/5','6/7'] :
    f = fractions.Fraction( s )
    print ' %s = %s ' % ( s , f)

The result will be same as above. 

Strings can also be used that are in the form ..

import fractions
 
for s in [ '2.3','4.5','6.7'] :
    f = fractions.Fraction( s )
    print ' %s = %s ' % ( s , f)

Output : 

 2.3 = 23/10
 4.5 = 9/2
 6.7 = 67/10

For floating point values , it may yield the unexpected result:

import fractions
 
print 'Fraction of 0.1 ',fractions.Fraction(0.1)

output is:

Fraction of 0.1  3602879701896397/36028797018963968

We can use decimal.Decimal('0.1’) to get the correct value.

Math and Random:

Python has math module that can be used to perform different mathematical calculations and random module to create a random number.

import math
import random
 
print (math.cos(90))
 
print (math.sin(90))
 
print (math.e)
 
print (math.pow(2,10))
 
print (random.random())
 
print (random.randrange(10,20))

Try to run this program and check the result.