是否可以修改这段代码以使其在启用快速数学的情况下工作?
Can this piece of code be modified such that it works with fast-math enabled?
是否可以修改下面的代码,使其即使在启用快速数学运算的情况下由 GCC 编译时也能正常工作?
#include <iostream>
#include <float.h>
using namespace std;
int main()
{
char divider = 2;
float power = 1;
float number = 1;
float current = number + power;
cout.precision(20);
// Divide until rounded off
while(current != number)
{
power /= divider;
current = number + power;
//cout << current << endl;
}
cout << power * divider << endl;
cout << FLT_EPSILON << endl;
}
注意:我把它放在一个头文件中,但我还没有设法关闭头文件的快速数学运算。参见 Strange while loop behavior and How to disable fast math for a header file function
您可以在常量表达式中的 constexpr 函数中转换计算:
constexpr float compute_epsilon()
{
char divider = 2;
float power = 1;
float number = 1;
float current = number + power;
// Divide until rounded off
while(current != number)
{
power /= divider;
current = number + power;
}
return power * divider;
}
constexpr auto epsilon = compute_epsilon();
将这段代码添加到循环中解决了我的问题。
std::ostringstream buff;
buff << current
编辑:
即使将此添加到条件中也有效:
&& ! isinf(current)
是否可以修改下面的代码,使其即使在启用快速数学运算的情况下由 GCC 编译时也能正常工作?
#include <iostream>
#include <float.h>
using namespace std;
int main()
{
char divider = 2;
float power = 1;
float number = 1;
float current = number + power;
cout.precision(20);
// Divide until rounded off
while(current != number)
{
power /= divider;
current = number + power;
//cout << current << endl;
}
cout << power * divider << endl;
cout << FLT_EPSILON << endl;
}
注意:我把它放在一个头文件中,但我还没有设法关闭头文件的快速数学运算。参见 Strange while loop behavior and How to disable fast math for a header file function
您可以在常量表达式中的 constexpr 函数中转换计算:
constexpr float compute_epsilon()
{
char divider = 2;
float power = 1;
float number = 1;
float current = number + power;
// Divide until rounded off
while(current != number)
{
power /= divider;
current = number + power;
}
return power * divider;
}
constexpr auto epsilon = compute_epsilon();
将这段代码添加到循环中解决了我的问题。
std::ostringstream buff;
buff << current
编辑:
即使将此添加到条件中也有效:
&& ! isinf(current)