无法在代码块中找到用于 c++ 浮点数的计算机 epsilon

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

本文关键字:c++ 用于 浮点数 epsilon 计算机 代码      更新时间:2023-10-16

我想通过C++找出浮点型和双精度型的机器epsilon,但是对于我正在使用的变量x的每种数据类型,我一次又一次地得到相同的答案,即长双精度和O(1e-20)的顺序。我正在使用代码块在我的 Windows 10 机器上运行它。

我尝试在 Ubuntu 和 Windows 本身的 DevC++ 中使用相同的代码,我得到了正确的答案。我在代码块中做错了什么。是否有任何默认设置?

#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;
}
while(one+x != one)

one+x的计算很可能是一个扩展的精度倍数。编译器可以自由地这样做。在这样的实现中,无论onex的类型如何,您确实会看到相同的iter值。

以下内容在我的计算机上运行良好。

#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>();
}   

您可以尝试以下代码来获取float值的机器 epsilon:

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