Thursday, October 20, 2011

floating point data range and precision

#include <iomanip>
#include <iostream>
using namespace std;

int main()
{
  cout << fixed << setprecision(25) << endl;
  cout << "--------- round-off error------------" << endl;
  double x = 3;
  cout << x << endl;
  cout << (x + 0.0000000000000001) << endl;
  cout << (x + 0.000000000000001) << endl << endl;

  cout << "--------- more round-off -------------" << endl;
  cout << scientific << setprecision(25) << endl;
  double d;
  for (d = 0; d != 2.0; d += 0.4)
    cout << d << endl;
  cout << d << endl << endl;

  float f;
  for (f = 0; f != 2.0; f += 0.4)
    cout << f << endl;
  cout << f << endl << endl;

  cout << "--------- boundary test -------------" << endl;
  f = 3.402823866e37;
  cout << f << endl;
  f = 3.402824036e37;
  cout << f << endl;
  f = 3.402824136e37;
  cout << f << endl << endl;

  f = 3.402823567e38;
  cout << f << endl;
  f = 3.402823568e38;
  cout << f << endl;
  f = 3.402823866e38;
  cout << f << endl << endl;

  return 0;
}

No comments:

Post a Comment