c - 如何检查 float 是否无穷大/零/非正规?

标签 c floating-point

int is_infinity/is_zero/is_denormal(float f){
    //do something, return 0 or 1
}

这就是我检查float是否为负数所做的事情。我想对其他功能做类似的事情,但我不知道如何做。

int is_negative(float val){
    union sp_object copy;
    copy.frep = val;
    if((copy.irep & 0x80000000) != 0)
        return 1;
    else
        return 0;
}

最佳答案

I want to do something similar for the other functions

避免位字段,@David ,因为这取决于实现细节。 <math.h>包含对 float 进行分类的宏。这些宏适用于 doublelong double也是。

#include <math.h>

// Adjust returns values as desired.
int is_infinity_is_zero_is_denormal(float f) {
  if (isinf(f)) return 'i';
  if (f == 0.0f) return 'z';
  if (isnan(f)) return 'n';
  if (isnormal(f)) return 0;  // neither zero, subnormal, infinite, nor NaN

  // All that is left is de-normal/sub-normal.
  return 'd';
}

或者只是简单

bool is_infinity_is_zero_is_denormal(float f) {
  return !(isnormal(f) || isnan(f));
}
<小时/>

另请参阅int fpclassify(real-floating x);一步对数字进行分类。

classifies its argument value as NaN, infinite, normal, subnormal, zero, or into another implementation-defined category. C11 §7.12.3.1 2

The number classification macros FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL FP_ZERO represent the mutually exclusive kinds of floating-point values. They expand to integer constant expressions with distinct values. §7.12 6

bool is_infinity_is_zero_is_denormal(float f) {
  // return fpclassify(f) & (FP_INFINITE | FP_ZERO | FP_SUBNORMAL);  // not good
  switch (fpclassify(f)) {
    case FP_INFINITE:
    case FP_ZERO:
    case FP_SUBNORMAL:
      return true;
  }
  return false;
}

让编译器处理优化。

关于c - 如何检查 float 是否无穷大/零/非正规?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44376382/

相关文章:

C:如何读取文本文件并在某个点之后获取某些值?

c - 静态内存分配和可移植性

random - 接近零的均匀真实分布

c++ - 如何在 C++ 中将 uint8_t 和 uint16_t 转换为 float ?

c - 这个 fabs() 的实现是如何工作的?

c - 两个指针的段错误

c - 为什么当外部 if 不为 true 时它会进入 else block ?

c - 如何回应用户输入并跳过标点符号和空格? (语言C)

c++ - 在 C++ 中 float 比 IEEE 754 更小的范围

python - 如何在python中转换 float ?