Thursday, October 20, 2011

floating point data representation

//
// This program is an illustration for potential floating point boundary error
// only the floating point number > 1 case is implemented.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
  ofstream fout;
  fout.open("data.txt");
  if (!fout.good()) throw "I/O error";

  double x, mant;
  int exp = 0;
  cout << "Enter a postive x > 1: ";

  //Now find exponent and mantissa
  cin >> x;
  cin.ignore(1000,10);
  fout << x << endl;

  //
  // shifting the decimal point left
  // until the number is smaller than 1
  // to obtain the exponent
  mant = x;
  while (mant >= 1)
  {
    mant /= 2;
    exp++; // At this point x = mant * 2^(exp)
  }
  while (mant < 0.5)
  {
    mant *= 2;
    exp--;
  }
  cout << x <<" is stored in exponent and mantisa, \n"
       << "as 2^(eee) *.mmm\n"
       << x <<" = ";
  cout << "2^(" <<exp<<") *.";
  fout << x <<" is stored as mmm.mmm\n"
       << x <<" = ";
  //
  // shifting the decimal point right
  // to convert decimal fraction to binary mantisa
  int i=0;
  string s = "";   // mantisa
  string ss = "";  // binary float
  float bfrac = 0; // binary fraction
  float weight = 1;      // fraction bit weight
  while (mant > 0)
  {
    mant *= 2;
    if (mant >= 1)
    {
      s = s + '1';
      ss = ss + '1';
      mant -= 1;
      if(i >= exp) bfrac += weight = weight/2;
    }
    else
    {
      s = s + '0';
      ss = ss + '0';
      if(i >= exp) weight = weight/2;
    }
    if(++i == exp) ss = ss + '.';
    if(i >= 23) break;
  }
  cout << s << endl;
  cout << "or, presented as: " << ss << endl;
  fout << ss << endl;

  cout << "regenerated decimal fraction from binary fraction: \n"
       << bfrac << endl;
  fout << "regenerated decimal fraction from binary fraction: \n"
       << bfrac << endl;
  return 0;
}

No comments:

Post a Comment