c++ - 无法在代码块中的 C++ 中找到 float 的机器 epsilon

标签 c++

我想通过 C++ 找出 float 和 double 类型的机器 epsilon,但是对于我正在使用的变量 x 的每种数据类型,我一次又一次地得到相同的答案,那就是long double 和 O(1e-20) 的顺序。我使用 Codeblocks 在我的 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 的计算很可能是扩展精度 double 。编译器可以很自由地这样做。在这样的实现中,无论 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>();
}   

关于c++ - 无法在代码块中的 C++ 中找到 float 的机器 epsilon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34975239/

相关文章:

c++ - 如何解决 C++ 中的 namespace 冲突?

c++ - C++程序无输入后如何退出

c++ - 是否可以检测是否声明了局部变量?

c++ - 如何有效地避免使用 goto 和中断嵌套循环

c++ - 使用qmake下载并构建第三方库

c++ - 几个排序问题

c++ - KDevelop4:在CMake之前设置环境变量

c++ - 如何创建包含不同图层的 pdf 文件

c++ - 记录 std::function 参数的最佳实践

c++ - 为什么在三元运算符的分支之间返回 lambda 对某些 lambda 有效?