Chapter 3 - Computer codes and arithmetic

Example No. 3_01 Pg No. 45

In [1]:
#Binary to decimal

b = '1101.1101'
def parse_bin(s):
    t = s.split('.')
    return int(t[0], 2) + int(t[1], 2) / 2.**len(t[1])

d = parse_bin(b) # #Integral and fractional parts
print 'Decimal value = ',d
Decimal value =  13.8125

Example No. 3_02 Pg No. 46

In [2]:
#hexadecimal to decimal

h = '12AF' 
d=int(h,16)
print 'Decimal value = ',d
Decimal value =  4783

Example No. 3_03 Pg No. 47

In [3]:
#Decimal to Binary

d = 43.375 #

def parse_float(num):
        exponent=0
        shifted_num=num
        while shifted_num != int(shifted_num):        
            shifted_num*=2
            exponent+=1
        if exponent==0:
            return '{0:0b}'.format(int(shifted_num))
        binary='{0:0{1}b}'.format(int(shifted_num),exponent+1)
        integer_part=binary[:-exponent]
        fractional_part=binary[-exponent:].rstrip('0')
        return '{0}.{1}'.format(integer_part,fractional_part)

b = parse_float(d) 
print 'Binary equivalent = ',b
Binary equivalent =  101011.011

Example No. 3_04 Pg No. 48

In [4]:
#Decimal to Octal

d = 163 #
def base10toN(num, base):
    """Change ``num'' to given base
    Upto base 36 is supported."""

    converted_string, modstring = "", ""
    currentnum = num
    if not 1 < base < 37:
        raise ValueError("base must be between 2 and 36")
    if not num:
        return '0'
    while currentnum:
        mod = currentnum % base
        currentnum = currentnum // base
        converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string
    return converted_string



Oct = base10toN(d,8)
print 'Octal number = ',Oct
Octal number =  243

Example No. 3_05 Pg No. 48

In [5]:
#Decimal to binary

d = 0.65

def parse_float(num):
        exponent=0
        shifted_num=num
        while shifted_num != int(shifted_num):        
            shifted_num*=2
            exponent+=1
        if exponent==0:
            return '{0:0b}'.format(int(shifted_num))
        binary='{0:0{1}b}'.format(int(shifted_num),exponent+1)
        integer_part=binary[:-exponent]
        fractional_part=binary[-exponent:].rstrip('0')
        return '{0}.{1}'.format(integer_part,fractional_part)


b=parse_float(d) # binary equibvalent
print 'Binary equivalent = ',b
Binary equivalent =  0.10100110011001100110011001100110011001100110011001101

Example No. 3_06 Pg No. 49

In [6]:
#Octal to Hexadecimal 

Oct = '243' 
dec=int(Oct,8)
h = hex(dec)[2:]

print 'Hexadecimal equivalent of octal number 243 is :',h
Hexadecimal equivalent of octal number 243 is : a3

Example No. 3_07 Pg No. 49

In [7]:
#Hexadecimal to Octal 


h = '39.B8' #
             
             
def float_to_binary(num):
    exponent=0
    shifted_num=num
    while shifted_num != int(shifted_num):        
        shifted_num*=2
        exponent+=1
    if exponent==0:
        return '{0:0b}'.format(int(shifted_num))
    binary='{0:0{1}b}'.format(int(shifted_num),exponent+1)
    integer_part=binary[:-exponent]
    fractional_part=binary[-exponent:].rstrip('0')
    return '{0}.{1}'.format(integer_part,fractional_part)

def floathex_to_binary(floathex):
    num = float.fromhex(floathex)
    return float_to_binary(num)

b= floathex_to_binary(h)
def parse_bin(s):
    t = s.split('.')
    return int(t[0], 2) + int(t[1], 2) / 2.**len(t[1])

d = parse_bin(b) # #Integral and fractional parts
print 'Octal number equivalent of Hexadecimal number 39.B8 is:',d
Octal number equivalent of Hexadecimal number 39.B8 is: 57.71875

Example No. 3_08 Pg No. 50

In [8]:
## -ve Integer to binary

negint = -13
def to_twoscomplement(bits, value):
    if value < 0:
        value = ( 1<<bits ) + value
    formatstring = '{:0%ib}' % bits
    return formatstring.format(value)

compl_2 = to_twoscomplement(5, negint)

print 'Binary equivalent of -13 is :',compl_2
Binary equivalent of -13 is : 10011

Example No. 3_09 Pg No. 51

In [9]:
#Binary representation

n = -32768

def to_twoscomplement(bits, value):
    if value < 0:
        value = ( 1<<bits ) + value
    formatstring = '{:0%ib}' % bits
    return formatstring.format(value)

binfinal = to_twoscomplement(16, n)


print 'Binary equivalent of -32768 in a 16 bit word is:',binfinal 
Binary equivalent of -32768 in a 16 bit word is: 1000000000000000

Example No. 3_10 Pg No. 52

In [10]:
#Floating Point Notation

def float_notation(n):
    m = n #
    for i in range(1,17):
        if abs(m) >= 1:
            m = n/10**i
            e = i
        elif abs(m) < 0.1:
            m = n*10**i
            e = -i
        else:
            if i == 1:
                e = 0
        
            break 
    return [m,e]
    

[m,e] = float_notation(0.00596)
print '\n 0.00596 is expressed as  %f*10**%d \n'%(m,e)
[m,e] = float_notation(65.7452)
print '\n 65.7452 is expressed as  %f*10**%d \n'%(m,e)
[m,e] = float_notation(-486.8)
print '\n -486.8 is expressed as  %f*10**%d \n'%(m,e)
 0.00596 is expressed as  0.596000*10**-2 


 65.7452 is expressed as  0.657452*10**2 


 -486.8 is expressed as  -0.486800*10**3 

Example No. 3_11 Pg No. 53

In [11]:
#Interger Arithmetic

print '25+12 =',int(25 + 12)
print '25-12 =',int(25 - 12) 
print '12-25 =',int(12 - 25)
print '25*12 =',int(25*12)
print '25/12 =',int(25/12)
print '12/25 =',int(12/25)
25+12 = 37
25-12 = 13
12-25 = -13
25*12 = 300
25/12 = 2
12/25 = 0

Example No. 3_12 Pg No. 53

In [12]:
#Integer Arithmetic

a = 5 #
b = 7 #
c = 3 #
Lhs = int((a + b)/c)
Rhs = int(a/c) + int(b/c)
print '(a+b)/c = ',Lhs,'\n a/c + b/c = ',Rhs
if Lhs != Rhs:
    print 'The results are not identical.This is because the remainder of an integer division is always truncated'
(a+b)/c =  4 
 a/c + b/c =  3
The results are not identical.This is because the remainder of an integer division is always truncated

Example No. 3_13 Pg No. 54

In [13]:
#Floating Point Arithmetic

fx = 0.586351 #
Ex = 5 #
fy = 0.964572 #
Ey = 2 #
v=[Ex,Ey]
Ez= max(v)
n=v.index(Ez)+1
if n == 1:
    fy = fy*10**(Ey-Ex)
    fz = fx + fy
    if fz > 1:
        fz = fz*10**(-1) 
        Ez = Ez + 1
    
    print 'Ez=',Ez,'\n fy=',fy,'\n fz=',fz
else:
    fx = fx*10**(Ex - Ey)
    fz = fx + fy
    if fz > 1:
        fz = fz*10**(-1)
        Ez = Ez + 1
    
    print 'Ez=',Ez,'\n fy=',fy,'\n fz=',fz

print '\n z = %f E%d \n'%(fz,Ez)
Ez= 5 
 fy= 0.000964572 
 fz= 0.587315572

 z = 0.587316 E5 

Example No. 3_14 Pg No. 54

In [14]:
#Floating Point Arithmetic

fx = 0.735816 #
Ex = 4 #
fy = 0.635742 #
Ey = 4 #
v=[Ex,Ey]
Ez= max(v)
n=v.index(Ez)+1
if n == 1:
    fy = fy*10**(Ey-Ex)
    fz = fx + fy
    if fz > 1:
        fz = fz*10**(-1)
        Ez = Ez + 1
    
    print 'Ez=',Ez,'\n fy=',fy,'\n fz=',fz
else:
    fx = fx*10**(Ex - Ey)
    fz = fx + fy
    if fz > 1:
        fz = fz*10**(-1) 
        Ez = Ez + 1
    
    print 'Ez=',Ez,'\n fy=',fy,'\n fz=',fz

print '\n z = %f E%d \n'%(fz,Ez)
Ez= 5 
 fy= 0.635742 
 fz= 0.1371558

 z = 0.137156 E5 

Example No. 3_15 Pg No. 54

In [15]:
#Floating Point Arithmetic

fx = 0.999658 #
Ex = -3 #
fy = 0.994576 #
Ey = -3 #
Ez = max(Ex,Ey)
fy = fy*10**(Ey-Ex)
fz = fx - fy
print 'Ez =',Ez,'fz =',fz
print '\n z = %f E%d \n'%(fz,Ez)
if fz < 0.1 :
     fz = fz*10**6      #Since we are using 6 significant digits
     n = len(str(fz))
     fz = fz/10**n
     Ez = Ez + n - 6
     print '\n z = %f E%d (normalised) \n'%(fz,Ez)
Ez = -3 fz = 0.005082

 z = 0.005082 E-3 


 z = 0.005082 E-3 (normalised) 

Example No. 3_16 Pg No. 55

In [16]:
#Floating Point Arithmetic

fx = 0.200000 #
Ex = 4 #
fy = 0.400000 #
Ey = -2 #
fz = fx*fy
Ez = Ex + Ey 
print '\n fz = %f \n Ez = %d \n z = %f E%d \n'%(fz,Ez,fz,Ez)
if fz < 0.1:
    fz = fz*10
    Ez = Ez - 1
    print '\n z = %f E%d (normalised) \n'%(fz,Ez)
 fz = 0.080000 
 Ez = 2 
 z = 0.080000 E2 


 z = 0.800000 E1 (normalised) 

Example No. 3_17 Pg No. 55

In [17]:
#Floating Point Arithmetic

fx = 0.876543 #
Ex = -5 #
fy = 0.200000 #
Ey = -3 #
fz = fx/fy
Ez = Ex - Ey 
print '\n fz = %f \n Ez = %d \n z = %f E%d \n'%(fz,Ez,fz,Ez)

if fz > 1:
    fz = fz/10
    Ez = Ez + 1
    print '\n z = %f E%d (normalised) \n'%(fz,Ez)
 fz = 4.382715 
 Ez = -2 
 z = 4.382715 E-2 


 z = 0.438271 E-1 (normalised) 

Example No. 3_18 Pg No. 56

In [18]:
#Floating Point Arithmetic

fx = 0.500000 #
Ex = 1 #
fy = 0.100000 #
Ey = -7 #
Ez= max([Ex,Ey])
n=[Ex,Ey].index(Ez)
if n == 1:
    fy = fy*10**(Ey-Ex)
    fz = fx + fy
    if fz > 1:
        fz = fz*10**(-1) 
        Ez = Ez + 1
    
    print 'Ez =',Ez,'\n fy =',fy
else:
    fx = fx*10**(Ex - Ey)
    fz = fx + fy
    if fz > 1:
        fz = fz*10**(-1)
        Ez = Ez + 1
    
    print 'Ez =',Ez,'\n fx =',fx

print '\n fz = %f \n z = %f E%d \n'%(fz,fz,Ez)
Ez = 2 
 fx = 50000000.0

 fz = 5000000.010000 
 z = 5000000.010000 E2 

Example No. 3_19 Pg No. 56

In [19]:
#Floating Point Arithmetic

fx = 0.350000 #
Ex = 40 #
fy = 0.500000 #
Ey = 70 #
fz = fx*fy
Ez = Ex + Ey 
print '\n fz = %f \n Ez = %d \n z = %f E%d \n'%(fz,Ez,fz,Ez)
if fz < 0.1:
    fz = fz*10
    Ez = Ez - 1
    print '\n z = %f E%d (normalised) \n'%(fz,Ez)
 fz = 0.175000 
 Ez = 110 
 z = 0.175000 E110 

Example No. 3_20 Pg No. 56

In [20]:
#Floating Point Arithmetic

fx = 0.875000 #
Ex = -18 #
fy = 0.200000 #
Ey = 95 #
fz = fx/fy
Ez = Ex - Ey 
print '\n fz = %f \n Ez = %d \n z = %f E%d \n'%(fz,Ez,fz,Ez)

if fz > 1:
    fz = fz/10
    Ez = Ez + 1
    print '\n z = %f E%d (normalised) \n'%(fz,Ez)
 fz = 4.375000 
 Ez = -113 
 z = 4.375000 E-113 


 z = 0.437500 E-112 (normalised) 

Example No. 3_21 Pg No. 57

In [21]:
#Floating Point Arithmetic

fx = 0.500000 #
Ex = 0 #
fy = 0.499998 #
Ey = 0 #
Ez = 0 #
fz = fx - fy
print 'Ez =',Ez,'\n fz =',fz
print '\n z = %f E%d \n'%(fz,Ez)
if fz < 0.1 :
     fz = fz*10**6
     n  = len(str(fz))
     fz = fz/10**n
     Ez = Ez + n - 6
     print '\n z = %f E%d (normalised) \n'%(fz,Ez)
Ez = 0 
 fz = 2e-06

 z = 0.000002 E0 


 z = 0.002000 E-3 (normalised) 

Example No. 3_22 Pg No. 57

In [22]:
#Laws of Arithmetic

def add_sub(fx,Ex,fy,Ey): #addition and subtraction fuction
    if fx*fy >= 0:
        #Addition
        Ez = max([Ex,Ey])
        n=[Ex,Ey].index(Ez)
        if n == 1:
            fy = fy*10**(Ey-Ex)
            fz = fx + fy
            if fz > 1:
                fz = fz*10**(-1)
                Ez = Ez + 1
        
            else:
                fx = fx*10**(Ex - Ey)
                fz = fx + fy
                if fz > 1:
                    fz = fz*10**(-1) 
                    Ez = Ez + 1
        
    
    
    else:
        #Subtraction
        Ez = max([Ex,Ey])
        n=[Ex,Ey].index(Ez)
        if n == 1:
            fy = fy*10**(Ey-Ex)
            fz = fx + fy
            if abs(fz) < 0.1:
                fz = fz*10**6
                fz = floor(fz)
                nfz = len(str(abs(fz)))
                fz = fz/10**nfz
                Ez = nfz - 6           
        
        else:
            fx = fx*10**(Ex - Ey)
            fz = fx + fy
            if fz < 0.1:
                fz = fz*10**6
                fz = int(fz)
                nfz = len(str(abs(fz)))
                fz = fz/10**nfz
                Ez = nfz - 6
        
    
  
    return [fz,Ez]

fx = 0.456732
Ex = -2
fy = 0.243451
Ey = 0
fz = -0.24800
Ez = 0

[fxy,Exy] = add_sub(fx,Ex,fy,Ey)
[fxy_z,Exy_z] = add_sub(fxy,Exy,fz,Ez)
[fyz,Eyz] = add_sub(fy,Ey,fz,Ez)
[fx_yz,Ex_yz] = add_sub(fx,Ex,fyz,Eyz)
print ' fxy = %f\n Exy = %d \n fxy_z = %f\n Exy_z = %d \n fyz = %f \n Eyz = %d \n fx_yz = %f \n Ex_yz = %d \n'%(fxy,Exy,fxy_z,Exy_z,fyz,Eyz,fx_yz,Ex_yz)

if  fxy_z != fx_yz | Exy_z != Ex_yz:
    print ' (x+y) + z != x + (y+z)' 
 fxy = 2.480183
 Exy = 1 
 fxy_z = 24.553832
 Exy_z = 1 
 fyz = -1.000000 
 Eyz = -2 
 fx_yz = -1.000000 
 Ex_yz = 0 

 (x+y) + z != x + (y+z)

Example No. 3_23 Pg No. 58

In [23]:
#Associative law
x = 0.400000*10**40
y = 0.500000*10**70
z = 0.300000*10**(-30)
print 'In book they have considered the maximum exponent can be only 99, since 110 is greater than 99 the result is erroneous'
print 'but in scilab the this value is much larger than 110 so we get a correct result '
print 'xy_z = ',(x*y)*z
print 'x_yz = ',x*(y*z)
In book they have considered the maximum exponent can be only 99, since 110 is greater than 99 the result is erroneous
but in scilab the this value is much larger than 110 so we get a correct result 
xy_z =  6e+78
x_yz =  6e+78

Example No. 3_24 Pg No. 58

In [24]:
from math import floor
#Distributive law
x = 0.400000*10**1 #
fx = 0.400000
Ex = 1
y = 0.200001*10**0 #
z = 0.200000*10**0 #
x_yz = x*(y-z)
x_yz = x_yz*10**6
x_yz = floor(x_yz) #considering only six significant digits
n = len(str(x_yz))
fx_yz = x_yz/10**n
Ex_yz = n - 6
x_yz = fx_yz *10**Ex_yz
print 'x_yz = ',x_yz

fxy = fx*y
fxy = fxy*10**6
fxy = floor(fxy) #considering only six significant digits
n = len(str(fxy))
fxy = fxy/10**n
Exy = n - 6
xy = fxy * 10**Exy

fxz = fx*z
fxz = fxz*10**6
fxz = floor(fxz) #considering only six significant digits
n = len(str(fxz))
fxz = fxz/10**n
Exz = n - 6
xz = fxz * 10**Exz

xy_xz = xy - xz
print 'xy_xz = ',xy_xz
x_yz =  4e-06
xy_xz =  0.0