Manish
Manish

Reputation: 522

Unable to find the machine epsilon for float in c++ in codeblocks

I wanted to find out the machine epsilon for float and double types through C++, but I am getting the same answer again and again for each data type of variable x I am using, which is that of long double and of the order of O(1e-20). I am running it on my Windows 10 machine using Codeblocks.

I tried using the same code in Ubuntu and also in DevC++ in Windows itself, I am getting the correct answer. What is it that I am doing wrong in codeblocks. Is there any default setting?

#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;

int main()
{
    //double x = 5;
    //double one = 1;
    //double fac = 0.5;

    float x=1;
    float one = 1.0;
    float fac = 0.5;

    // cout <<"What is the input of number you are giving"<< endl;
    // cin >> x;

    cout <<"The no. you have given is: "<< x << endl;
    int iter = 1;

    while(one+x != one)
    {
         x = x * fac;
        iter = iter + 1;
    }

    cout<<"The value of machine epsilon for the given data type is "<<x<<endl;
    cout<<"The no.of iterations taken place are: "<<iter<<endl;

}

Upvotes: 2

Views: 558

Answers (2)

David Hammen
David Hammen

Reputation: 33136

while(one+x != one)

The computation of one+x might well be an extended precision double. The compiler is quite free to do so. In such an implementation, you will indeed see the same value for iter regardless of the type of one and x.

The following works quite nicely on my computer.

#include <iostream>
#include <limits>

template <typename T> void machine_epsilon()
{   
    T one = 1.0;
    T eps = 1.0;
    T fac = 0.5;
    int iter = 0;
    T one_plus_eps = one + eps;
    while (one_plus_eps != one)
    {   
        ++iter;
        eps *= fac;
        one_plus_eps = one + eps;
    }   
    --iter;
    eps /= fac;
    std::cout << iter << ' ' 
              << eps << ' ' 
              << std::numeric_limits<T>::epsilon() << '\n';
}   

int main ()
{   
    machine_epsilon<float>();
    machine_epsilon<double>();
    machine_epsilon<long double>();
}   

Upvotes: 4

RHertel
RHertel

Reputation: 23818

You could try this code to obtain the machine epsilon for float values:

#include<iostream>
#include<limits>
int main(){
  std::cout << "machine epsilon (float): "
            << std::numeric_limits<float>::epsilon() << std::endl;
}

Upvotes: 3

Related Questions