无法在代码块中找到用于 c++ 浮点数的计算机 epsilon
Unable to find the machine epsilon for float in c++ in codeblocks
我想通过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
的计算很可能是一个扩展的精度倍数。编译器可以自由地这样做。在这样的实现中,无论one
和x
的类型如何,您确实会看到相同的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;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 用于访问容器<T>数据成员的正确 API
- 重载操作程序时出错>>用于类中的字符串 memebr
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- C++中的cin.ignore()函数不适用于整个流
- 没有用于初始化C++中的变量模板的匹配构造函数
- 用于C++中带有数组和指针的循环
- 为什么它不适用于Visual 2019的原因
- 使用在用于SFINAE的void_t中具有参数的方法
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 重载==不适用于二进制树
- Insert函数不适用于2 if语句C++
- 用于矢量处理的多个线程
- 使外部项目可用于find_package CMake
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 为什么模数运算符不适用于该代码
- 并行用于C++17中数组索引范围内的循环
- 将fold表达式与std::一起用于两个元组
- 在用于格式4的arm模拟器中实现功能时的一个问题