Что значит nan в с

от admin

what does NaN mean for doubles?

What’s the difference between NaN and Infinity ? When does NaN appear? What is it?

6 Answers 6

In computing, NaN (Not a Number) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations. Systematic use of NaNs was introduced by the IEEE 754 floating-point standard in 1985, along with the representation of other non-finite quantities like infinities.

  • Represents a value that is not a number (NaN). This field is constant.

  • The value of this constant is the result of dividing zero by zero.

  • This constant is returned when the result of an operation is undefined.

  • Use IsNaN to determine whether a value is not a number. It is not possible to determine whether a value is not a number by comparing it to another value equal to NaN.

Where as Infinity (positive infinity and negative infinity) is the result of a floating point operation that causes an overflow (For example 3.0 / 0 ).

Infinity is a mathematical construct:

For instance, In euclidean space, the division through the null-element (zero in that case) should yield Infinity:

Not a Number or NaN is a computational construct, that came along with parsers and programmatic limitations, and its output can be assigned different meaning depending on the function in question.

For instance, a result may only be mathematically tractable using a different number system, which is easy for a mathematician to do, but in your function you may be left as the only pragmatic option to return NaN . Consider, the square root of -1 :

. an operation which is easily tractable in complex and phase space .

Experiment:

Open up the JavaScript.Console (CTRL+SHIFT+J) in your browser, and type

In C# the typical ‘NaN-situations’ are mostly handled through Exceptions:

Dynamic typed languages:

Overall, the usage of NaN is somewhat flexibly assigned in different programming languages. Using NaN at the loss of some ‘contextual information’, is convenient in dynamically typed scripting languages, where programmers generally do not want to bother with complex exception-types and handling thereof.

C2018/Вещественные числа

В школе на уроках физики изучают, как записывать числа «в стандартном виде»:

[math]x = m \cdot 10^n[/math] ,

[math]1 \le m \lt 10,\:n\in\mathbb[/math] .

Число [math]m[/math] называют мантиссой, число [math]p[/math] называют порядком.

В компьютере в качестве основания вместо числа [math]10[/math] используется число [math]2[/math] .

Стандарт IEEE 754

IEEE 754 (IEC 60559) — широко используемый стандарт IEEE, описывающий формат представления чисел с плавающей точкой.

binary32 binary64
Название число одинарной точности число двойной точности
Тип в C float double
Биты знака 1 1
Биты экспоненты 8 11
Биты мантиссы 23 52
Мин. положит. денорм. значение [math]1.401298464 \times 10^<-45>[/math] [math]4.9406564584124654 \times 10^<-324>[/math]
Макс. значение [math]3.402823 \times 10^<38>[/math] [math]1.7976931348623157 \times 10^<308>[/math]
Число десятичных цифр 7—8 15—17

Стандартом языка C гарантируется только, что

На большинстве платформ применяются типы с плавающей точкой в соответствии со стандартом IEEE 754.

Важным нюансом является форма записи вещественных констант разных типов. Например,

  • 1 — это константа типа int,
  • 1. или 1.0 — это константа типа double,
  • 1.f или 1.0f — это константа типа float.

На следующих занятиях мы разберём, почему смешивать в одном выражении операнды типов float и double может быть плохо.

Представление в памяти

  • знак числа
  • экспонента (показатель)
  • мантисса

Число одинарной точноcти (float)

Занимает в памяти 32 бита (4 байта).

Числа одинарной точности с плавающей запятой обеспечивают относительную точность 7-8 десятичных цифр в диапазоне от 10 −38 до примерно 10 38 .

[math](-1)^> \times (1.b_<22>b_ <21>\dots b_0)_2 \times 2^<(b_<30>b_ <29>\dots b_<23>)_2 — 127>[/math]

Число двойной точноcти (double)

Занимает в памяти 64 бита (8 байт).

Числа двойной точности с плавающей запятой обеспечивают точность в 15—17 десятичных цифр и масштабы в диапазоне примерно от 10 −308 до 10 308 .

Double.png

Распределение

Множество вещественных чисел в математике бесконечно и даже несчётно.

Множество чисел, представимых в формате с плавающей точкой, не только счётно, но и конечно. Все эти числа являются рациональными.

Однако расстояние между соседними числами непостоянно.

Рассмотрим гипотетический 8-битный тип, с 4-битной мантиссой и 3-битной экспонентой.

Fltscale-wh.png

Промежуток между соседними числами удваивается при переходе через каждую степень двойки.

Чем дальше от нуля, тем реже и реже встречаются на числовой прямой числа, которые представимы вещественным типом.

Точное представление

Точно представляются только несократимые дроби, у которых знаменатель является степенью двойки.

Что значит nan в с

IEEE 754 floating point numbers can represent positive or negative infinity, and NaN (not a number). These three values arise from calculations whose result is undefined or cannot be represented accurately. You can also deliberately set a floating-point variable to any of them, which is sometimes useful. Some examples of calculations that produce infinity or NaN:

When a calculation produces any of these values, an exception also occurs; see FP Exceptions.

The basic operations and math functions all accept infinity and NaN and produce sensible output. Infinities propagate through calculations as one would expect: for example, 2 + ∞ = ∞, 4/∞ = 0, atan (∞) = π/2. NaN, on the other hand, infects any calculation that involves it. Unless the calculation would produce the same result no matter what real value replaced NaN, the result is NaN.

In comparison operations, positive infinity is larger than all values except itself and NaN, and negative infinity is smaller than all values except itself and NaN. NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. You can use this to test whether a value is NaN or not, but the recommended way to test for NaN is with the isnan function (see Floating-Point Number Classification Functions). In addition, < , > , <= , and >= will raise an exception when applied to NaNs.

math.h defines macros that allow you to explicitly set a variable to infinity or NaN.

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.

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 Number Classification Functions.

This macro was introduced in the ISO C99 standard.

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.

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 .)

Macro: float SNANF ¶ Macro: double SNAN ¶ Macro: long double SNANL ¶ Macro: _FloatN SNANFN ¶ Macro: _FloatNx SNANFNx

These macros, defined by TS 18661-1:2014 and TS 18661-3:2015, are constant expressions for signaling NaNs.

Macro: int FE_SNANS_ALWAYS_SIGNAL

This macro, defined by TS 18661-1:2014, is defined to 1 in fenv.h to indicate that functions and operations with signaling NaN inputs and floating-point results always raise the invalid exception and return a quiet NaN, even in cases (such as fmax , hypot and pow ) where a quiet NaN input can produce a non-NaN result. Because some compiler optimizations may not handle signaling NaNs correctly, this macro is only defined if compiler support for signaling NaNs is enabled. That support can be enabled with the GCC option -fsignaling-nans .

IEEE 754 also allows for another unusual value: negative zero. This value is produced when you divide a positive number by negative infinity, or when a negative result is smaller than the limits of representation.

Что значит nan в с

The macro NAN expands to constant expression of type float which evaluates to a quiet not-a-number (QNaN) value. If the implementation does not support QNaNs, this macro constant is not defined.

The style used to print a NaN is implementation defined.

Contents

[edit] Notes

There are many different NaN values, differentiated by their payloads and their sign bits. The contents of the payload and the sign bit of the NaN generated by the macro NAN are implementation-defined.

Читать:
Как убрать корзину в woocommerce

Похожие статьи