Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
restrepo
GitHub Repository: restrepo/ComputationalMethods
Path: blob/master/activities/binary-representation.ipynb
934 views
Kernel: Unknown Kernel

Task 3

This homework is an activity intended to practice IPython notebooks and binary representation of real numbers.

Due to: Nov 15

Binary Representation

According to the IEEE 754-2008 standard, binary representation of real numbers may be done by using single-precision float32 or double-precision float64. float32 follows the next rules:

32-bits

  1. The fist digit (called s) indicates the sign of the number (s=0 means a positive number, s=1 a negative one).

  2. The next 8 bits represent the exponent of the number.

  3. The last 23 bits represent the fractional part of the number.

The formula for recovering the real number is then given by:

r=(1)s×(1+i=123b23i2i)×2e127r = (-1)^s\times \left( 1 + \sum_{i=1}^{23}b_{23-i}2^{-i} \right)\times 2^{e-127}

where ss is the sign, b23ib_{23-i} the fraction bits and ee is given by:

e=i=07b23+i2ie = \sum_{i=0}^7 b_{23+i}2^i

1. Write an IPython notebook and present (consult) the steps necessary for finding the binary float32 representation of a real number.

2. Write a routine (same notebook) that calculates the binary representation of a number following the steps of the previous item. Test your results with the next function number32, i.e., if your routine is called binary32, running number32( binary32( number ) ) should return the original number.

def number32( binary ): #Inverting binary string binary = binary[::-1] #Decimal part dec = 1 for i in xrange(1,24): dec += int(binary[23-i])*2**-i #Exponent part exp = 0 for i in xrange(0,8): exp += int(binary[23+i])*2**i #Total number number = (-1)**int(binary[31])*2**(exp-127)*dec return number

Advice: take advantage of all the taught functionalities of IPython notebooks, i.e., Markdown formatting, embedded code, LaTeX formatting, etc.