0

I am writing a program in c++ where I want to find the epsilon of my pc. I want the result to be double precision (which is 2.2204460492503131 E-16) but instead the output is 1.0842 E-019 which is the epsilon in long double precision.

My program is this:

#include <iostream>

double e = 1.0;
double x;

int main () 
{

    for (int i = 0; e + 1.0!=1.0 ; i++)
    {
        std::cout<<e<<'\n';
        x = e;
        e/=2.0;
    }

    std::cout << "The epsilon of this Computer is "<< x <<'\n';

    return 0;
}
bendaf
  • 2,981
  • 5
  • 27
  • 62
Jon Snow
  • 101

1 Answers1

0

Output std::numeric_limits<double>::epsilon() instead. std::numeric_limits is declared in the standard header <limits>.

A more usual technique, if you really must calculate it (rather than trusting your standard library to provide a correct value) is

double epsilon = 1.0;

while ((1.0 + 0.5 * epsilon) != 1.0)
    epsilon *= 0.5;

or to do the calculation.

Note that (although you haven't shown how you did it) it may actually be your long double calculation that is incorrect, since literal floating point values (like 1.0) default to being of type double, not long double - which might suggest the error is in your calculation of the long double result, not the double one.. If you want the result to be of type long double, it would be advisable to give all of that literal values (1.0, 0.5) the L suffix, to force them to be of type long double.

Also remember to use appropriate formatting when streaming the resultant value to std::cout, to ensure output also has the accuracy/precision you need. The default settings (what you get if you don't control the formatting) may differ.

Peter
  • 35,646
  • 4
  • 32
  • 74