C语言 如何在c中生成NaN浮点数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7212356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:30:19  来源:igfitidea点击:

How to produce a NaN float in c?

cfloating-pointnan

提问by Je Rog

float f = (float)'a';
if(f < 0){ 
}   
else if(f == 0){ 
}   
else if(f > 0){ 
}   
else{
    printf("NaN\n");                                                          
}   

fwon't be greater/equal/less than 0if it's a NaN.

f不会大于/等于/小于0如果它是NaN.

But how to produce such a fin the first place?

但首先如何产生这样的东西f

I tried various ways to produce a NaN,but none work..

我尝试了各种方法来制作一个NaN,但没有一个工作..

采纳答案by Dan Cecile

Using floating point numbers, 0.0 / 0.0isn't a "divide by zero" error; it results in NaN.

使用浮点数,0.0 / 0.0不是“除以零”错误;它导致NaN.

This C program prints -nan:

这个 C 程序打印-nan

#include <stdio.h>

int main()
{
    float x = 0.0 / 0.0;
    printf("%f\n", x);
    return 0;
}

In terms what NaNlooks like to the computer, two "invalid" numbers are reserved for "signaling" and "quiet" NaN (similar to the two invalid numbers reserved for positive and negative infinity). The Wikipedia entryhas more details about how NaN is represented as an IEE floating point number.

NaN计算机的外观而言,两个“无效”数字保留用于“信令”和“安静”NaN(类似于为正无穷大和负无穷大保留的两个无效数字)。在维基百科条目有大约NaN被如何表示为IEE浮点数的更多细节。

回答by Foo Bah

To produce a nan, there are a few ways:

要产生nan,有几种方法:

1) generate it manually (read ieee754to set up the bits properly)

1)手动生成(读取ieee754以正确设置位)

2) use a macro. GCC exposes a macro NAN. It's defined in math.h

2)使用宏。GCC 公开了一个宏NAN。它在 math.h 中定义

The general way to check for a nan is to check if (f == f)(which should fail for nan values)

检查 nan 的一般方法是检查if (f == f)(对于 nan 值应该失败)

For nan, the exponent bits in the float representation should all be set to 1 (float consists of a signed bit, a set of exponent bits and a set of mantissa bits)

对于 nan,浮点表示中的指数位应全部设置为 1(浮点由一个有符号位、一组指数位和一组尾数位组成)

回答by Rika

You can either use NANmacro, or simply one of nan/nanffunctions to assign a nan value to a variable.
to check if you are dealing with a nan value, you can use isnan(). Here is an example:

您可以使用NAN宏,也可以仅使用其中一个nan/nanf函数将 nan 值分配给变量。
要检查您是否正在处理 nan 值,您可以使用isnan(). 下面是一个例子:

#include <stdio.h>
#include <math.h>

int main(void) {

    float a = NAN;//using the macro in math.h
    float f = nanf("");//using the function version 
    double d = nan("");//same as above but for doubles!

    printf("a = %f\nf = %f\nd = %f\n",a,f,d);

    if(isnan(a))
        puts("a is a not a number!(NAN)\n");

    return 0;
}

Running the code snippet above will give you this output:

运行上面的代码片段将为您提供以下输出:

a = nan
f = nan
d = nan
a is a not a number!(NAN)

Run the code yourself : http://ideone.com/WWZBl8
read more information : http://www.cplusplus.com/reference/cmath/NAN/

自己运行代码:http: //ideone.com/WWZBl8
阅读更多信息:http: //www.cplusplus.com/reference/cmath/NAN/

回答by A. K.

From the GNU GCC manual math.hdefines macros that allow you to explicitly set a variable to infinity or NaN. Since this is a part of C99 you can use the following macros with other c99 compliant compilers i hope.

GNU GCC 手册中math.h定义的宏允许您将变量显式设置为无穷大或 NaN。由于这是 C99 的一部分,您可以将以下宏与我希望的其他 c99 兼容编译器一起使用。

— Macro: float INFINITY An expression representing positive infinity. It is equal to the value produced by mathematical operations like 1.0 / 0.0. -INFINITY represents negative infinity.

— 宏:float INFINITY 表示正无穷大的表达式。它等于数学运算产生的值,如 1.0 / 0.0。-INFINITY 表示负无穷大。

You can test whether a floating-point value is infinite by comparing it to this macro. However, this is not recommended; you should use the isfinite macro instead. See Floating Point Classes.

您可以通过将浮点值与此宏进行比较来测试浮点值是否为无穷大。但是,不建议这样做;您应该改用 isfinite 宏。请参阅浮点类。

This macro was introduced in the ISO C99 standard.

这个宏是在 ISO C99 标准中引入的。

— Macro: float NAN An expression representing a value which is “not a number”. This macro is a GNU extension, available only on machines that support the “not a number” value—that is to say, on all machines that support IEEE floating point.

— 宏:float NAN 表示“非数字”值的表达式。这个宏是一个 GNU 扩展,仅在支持“非数字”值的机器上可用——也就是说,在所有支持 IEEE 浮点的机器上。

You can use ‘#ifdef NAN' to test whether the machine supports NaN. (Of course, you must arrange for GNU extensions to be visible, such as by defining _GNU_SOURCE, and then you must include math.h.)

你可以使用'#ifdef NAN'来测试机器是否支持NaN。(当然,您必须安排 GNU 扩展可见,例如通过定义 _GNU_SOURCE,然后您必须包含 math.h。)

for further information you can see here: http://www.gnu.org/s/hello/manual/libc/Infinity-and-NaN.html

有关更多信息,您可以在此处查看:http: //www.gnu.org/s/hello/manual/libc/Infinity-and-NaN.html

回答by vinc17

For hosted C implementations, one can do a #include <math.h>and use the NANmacro if defined. For instance, with GCC, it is implemented by a builtin: (__builtin_nanf ("")).

对于托管 C 实现,可以执行 a#include <math.h>并使用已NAN定义的宏。例如,在 GCC 中,它是由一个内置函数实现的:(__builtin_nanf (""))

For freestanding C implementations (on which the <math.h>header may not be available) or when the NANmacro is not defined (which might happen even though NaN's may be supported), one can generate a NaN with a floating-point operation such as 0.0?/?0.0. However, there may be several issues with it.

对于独立的 C 实现(<math.h>标头可能不可用)或NAN未定义宏时(即使可能支持 NaN 也可能发生这种情况),可以使用浮点运算生成 NaN,例如0.0?/?0.0. 但是,它可能存在几个问题。

First, such an operation also generates an exception, with a possible trap on some C implementations. One can make sure that it is computed at compile time with:

首先,这样的操作也会产生一个异常,在某些 C 实现上可能存在陷阱。可以确保它是在编译时计算的:

static double my_nan = 0.0 / 0.0;

Another issue is that Microsoft Visual C++ (at least some versions) attempts to evaluate 0.0?/?0.0at compile time (even when this expression is in an arbitrary place in the code) and complains about its validity. So, the solution here is the opposite one: make sure that the compiler will not evaluate it at compile time, by doing:

另一个问题是 Microsoft Visual C++(至少某些版本)尝试0.0?/?0.0在编译时进行评估(即使此表达式位于代码中的任意位置)并抱怨其有效性。因此,这里的解决方案是相反的:通过执行以下操作,确保编译器不会在编译时对其进行评估:

static double zero = 0.0;

and then use zero?/?zero. Since these solutions are conflicting, one can test the compiler with preprocessor directives (#if...) on specific macros.

然后使用zero?/?zero. 由于这些解决方案相互冲突,因此可以使用特定宏#if上的预处理器指令 ( ...)来测试编译器。

One may also choose a solution based on the NaN encoding, but there are also portability issues. First, the IEEE 754 standard does not completely define the encoding of a NaN, in particular the way to distinguish quiet and signaling NaNs (and hardware differs in practice); signaling NaNs will yield undefined behavior. Moreover, the IEEE 754 standard does not define how the bit string is represented in memory, i.e. the endianness may need to be detected. If these problems are solved, a union or an array of unsigned charwith a pointer cast is fine to get the floating-point type. Do not use an integer with a pointer cast on its address to do type punning as this will break the C aliasing rules.

也可以选择基于 NaN 编码的解决方案,但也存在可移植性问题。首先,IEEE 754 标准没有完全定义 NaN 的编码,特别是区分安静和信令 NaN 的方式(和硬件在实践中不同);信号 NaN 将产生未定义的行为。此外,IEEE 754 标准没有定义位串在内存中的表示方式,即可能需要检测字节序。如果这些问题解决了,联合或unsigned char带有指针转换的数组就可以得到浮点类型。不要使用在其地址上强制转换指针的整数来进行类型双关,因为这会破坏 C 别名规则。

回答by tonyjosi

A -nancan also be produced by setting all 32 bits of a float variable as 1, as shown below:

-nan也可以通过将浮点变量的所有 32 位设置为 1 来生成A ,如下所示:

float nan_val = 0xffffffff;

Also, you can compare if a float variable is -nanexplicitly by checking if comparison with itself fails.

此外,您可以-nan通过检查与自身的比较是否失败来比较浮点变量是否明确。

if (nan_val != nan_val) {
// executes iff nan_val is -nan
}

This method of comparison should work for compilers that use IEEE floats.

这种比较方法应该适用于使用 IEEE 浮点数的编译器。

回答by Oliver Zendel

This works for constants too (0/0 will give a compiler error on vs):

这也适用于常量(0/0 会在 vs 上产生编译器错误):

const unsigned maxU = ~0;
const float qNan =  *((float*)&maxU);

回答by MNS

Following C program will produce a NaN. The second statement will result in a NaN.

以下 C 程序将产生一个 NaN。第二个语句将导致 NaN。

#include <stdio.h>
#include <tchar.h>
#include "math.h"

int _tmain(int argc, _TCHAR* argv[])
{
    double dSQRTValue = sqrt( -1.00 ); 
    double dResult = -dSQRTValue;  // This statement will result in a NaN.
    printf( "\n %lf", dResult );

    return 0;
}

Following will be the output of the program.

以下将是程序的输出。

1.#QNAN0

1.#QNAN0

回答by Vinod Kumar Chauhan

nan is produced when we program contain value like 0.0/0.0 as said by @Dan Cecile OR sqrt(-1).

正如@Dan Cecile 或 sqrt(-1) 所说,当我们编程包含 0.0/0.0 之类的值时,会产生 nan。