簡體   English   中英

可以修改這段代碼以使其在啟用快速數學的情況下工作嗎?

[英]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;
}

注意:我有它在 header 文件中,我還沒有設法關閉 header 的快速數學。 請參閱奇怪的 while 循環行為如何禁用 header 文件 function 的快速數學

您可以在常量表達式中轉換 constexpr function 中的計算:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM