如何检查浮点数是无穷大/零/非正规?

时间:2017-06-05 19:34:09

标签: c

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

这是我为检查浮动是否为负而做的,我想为其他功能做类似的事情,但我不确定如何

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

2 个答案:

答案 0 :(得分:3)

  

我想为其他功能做类似的事情

避免使用位字段@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);一步对数字进行分类。

  

将其参数值分类为NaN,无穷大,正常,次正常,零或另一个实现定义的类别。 C11§7.12.3.12

bool is_infinity_is_zero_is_denormal(float f) {
  return fpclassify(f) & (FP_INFINITE | FP_ZERO | FP_SUBNORMAL);
}

让编译器处理优化。

答案 1 :(得分:0)

ISO C99提供了可与之进行比较的INFINITYNAN宏。建议使用isfinite()isnormal()isnan()函数。请注意,当EOF指出时,与NAN宏进行比较不会确定值是否实际为NAN

对于C99:

https://www.gnu.org/software/libc/manual/html_node/Floating-Point-Classes.html#Floating-Point-Classes

https://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html

对于早期的代码,你运气不好:

http://c-faq.com/fp/nan.html