2016-01-24 32 views
2

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

我试过在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; 

} 
+0

'机器epsilon浮法和双类型',它不是它的工作方式。在2附近浮动或双倍之间,epsilon不是一个常数。 float和double不是以整数形式存储的。 –

+0

您正在使用的epsilon的确切定义是什么,以及您的算法与此有关?这就是说,你的问题是无关紧要的,请参阅发布指南。 –

+1

你能给我们提供codeblocks使用的完整编译选项吗? (如快速数学,O3等)。 – fjardon

回答

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

你可以试试这个代码,以获得机器精度为float值:

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

尽管真实且更正确,但我猜测OP对手动查找epsilon更感兴趣。 – edmz

+2

@black我同意,但我认为这可能有助于指出STL包含这样一个函数,希望它可以用于OP或其他。 – RHertel

+1

您也可以添加关于['std :: nextafter']的注释(http://en.cppreference.com/w/cpp/numeric/math/nextafter)。 –