Nan ошибка что это

NaN в JavaScript

От автора: В данной статье мы познакомимся со специальным свойством NaN (Not-A-Number), которое является значением, представляющим не-число.

Тип числа в JavaScript содержит целые числа и числа с плавающей запятой:

const integer = 4;

const float = 1.5;

typeof integer; // => ‘number’

typeof float;   // => ‘number’

Плюс есть два специальных числовых значения: Infinity (число больше, чем любое другое число) и NaN (представляющее концепцию «не число»):

Профессия Frontend-разработчик PRO

Готовим Frontend-разработчиков с нуля

На курсе вы научитесь создавать интерфейсы веб-сервисов с помощью языков программирования и
дополнительных технологий. Сможете разрабатывать планировщики задач, мессенджеры, интернет-магазины…

Узнать подробнее

До 10 проектов в портфолио для старта карьеры

Подходит для новичков без опыта в программировании

Практика на вебинарах с разработчиками из крупных компаний

const infinite = Infinity;

const faulty = NaN;

typeof infinite; // => ‘number’

typeof faulty;   // => ‘number’

Хотя непосредственная работа с NaN редко встречается, оно может неожиданно появиться после неудачной операции с числами.

Давайте подробно рассмотрим специальное значение NaN: как проверить, содержит ли переменная NaN, и сценарии, которые в которых генерируется значения «не число».

1. Число NaN

Тип числа в JavaScript — это набор всех числовых значений, включая «не число», положительную бесконечность и отрицательную бесконечность.

«Not A Number» можно получить с помощью специального выражения NaN или как свойство глобального объекта или функции Number:

typeof NaN;        // => ‘number’

typeof window.NaN; // => ‘number’

typeof Number.NaN; // => ‘number’

«Не число» — это значение, которое не представляет действительное число, несмотря на то, что оно имеет тип числа. Через NaN полезно представлять ошибочные операции с числами. Например, умножение числа на undefined не является допустимой операцией, поэтому дает NaN:

Также попытка разобрать недопустимую числовую строку, например, ‘Joker’ приводит к NaN:

parseInt(‘Joker’, 10); // => NaN

2. Проверка на равенство с NaN

Интересным свойством NaN является то, что оно не равно ни одному значению, даже самому себе:

Это поведение полезно для определения, является ли переменная NaN:

const someNumber = NaN;

if (someNumber !== someNumber) {  console.log(‘Is NaN’);

} else {

  console.log(‘Is Not NaN’);

}

// logs «Is NaN»

Выражение someNumber !== someNumber равно true, только если someNumber является NaN. Таким образом, приведенный выше фрагмент регистрирует в консоли «Is NaN». JavaScript содержит встроенные функции для определения NaN: isNaN() и Number.isNaN():

isNaN(NaN); // => true

isNaN(1);   // => false

Number.isNaN(NaN); // => true

Number.isNaN(1);   // => false

Разница между этими функциями заключается в том, что Number.isNaN() не преобразуется свой аргумент в число:

isNaN(‘Joker12’);        // => true

Number.isNaN(‘Joker12’); // => false

isNaN(‘Joker12’) преобразует аргумент ‘Joker12’ в число, которое является NaN. Таким образом, функция возвращает true.

С другой стороны, Number.isNaN(‘Joker12’) проверяет аргумент без преобразования. Функция возвращает false, потому ‘Joker12’ не равно NaN.

3. Операции, дающие NaN

3.1 Парсинг чисел

В JavaScript вы можете преобразовать числовые строки в числа. Например, вы можете легко преобразовать строку ‘1.5’ в число с плавающей запятой 1.5:

const numberString = ‘1.5’;

const number = parseFloat(numberString);

number; // => 1.5

Когда строка не может быть преобразована в число, функция синтаксического анализа возвращает NaN: указывая, что синтаксический анализ не выполнен. Вот некоторые примеры:

parseFloat(‘Joker12.5’); // => NaN

parseInt(‘Joker12’, 10); // => NaN

Number(‘Joker12’);       // => NaN

При парсинге чисел рекомендуется проверить, не является ли результат парсинга NaN:

let inputToParse = ‘Invalid10’;

let number;

number = parseInt(inputToParse, 10);

if (isNaN(number)) {  number = 0;

}

number; // => 0

Парсинг inputToParse не удался, поэтому parseInt(inputToParse, 10) возвращается NaN. Условие if (isNaN(number)) оценивается, как true, и 0 назначается number.

3.2 undefined в качестве операнда

При использовании undefined в качестве операнда в арифметических операциях, таких как сложение, умножение и т д. мы получаем NaN. Например:

function getFontSize(style) {

  return style.fontSize;

}

const fontSize = getFontSize({ size: 16 }) * 2;

const doubledFontSize = fontSize * 2;

doubledFontSize; // => NaN

getFontSize() — это функция, которая обращается к свойству fontSize из объекта стиля. При вызове getFontSize({ size: 16 }) результатом будкт undefined (свойство fontSize не существует в объекте { size: 16 }). fontSize * 2 оценивается как undefined * 2, что дает NaN.

«Not A Number» генерируется, когда в качестве значения в арифметических операциях используется отсутствующее свойство или функция, возвращающая undefined. Отсутствие undefined в арифметических операциях — это хороший способ предотвратить получение NaN.

3.3 NaN как операнд

Значение NaN также генерируется, когда операндом в арифметических операциях является NaN:

1 + NaN; // => NaN

2 * NaN; // => NaN

NaN распространяется на арифметические операции:

let invalidNumber = 1 * undefined;

let result = 1;

result += invalidNumber; // appendresult *= 2;             // duplicate

result++;                // increment

result; // => NaN

Операции с переменной result прерываются после добавления к result значения invalidNumber (которое является NaN).

3.4 Неопределенные формы

Значение NaN создается, когда арифметические операции имеют неопределенные формы. Деление 0 / 0 и Inifinity / Infinity:

0 / 0;               // => NaN

Infinity / Infinity; // => NaN

Умножение 0 и Infinity:

Сложение бесконечных чисел с разными знаками:

Infinity + Infinity; // => NaN

3.5 Неверные аргументы математических функций

Квадратный корень из отрицательного числа:

Math.pow(2, 0.5); // => NaN

(2) ** 0.5;       // => NaN

Или логарифм отрицательного числа:

4. Заключение

Понятие «не число», выраженное в JavaScript с помощью NaN, полезно для представления ошибочных операций над числами. NaN не равно ни одному значению, даже самому себе. Рекомендуемый способ проверить, содержит ли переменная NaN — использовать Number.isNaN(value).

Преобразование числовых строк в числа, в случае неудачи может дать NaN. Рекомендуется проверять, не возвращают ли parseInt(), parseFloat() или Number() NaN.

Если undefined или NaN используются в качестве операнда в арифметических операциях, это обычно приводит к NaN. Правильная обработка undefined (предоставление значений по умолчанию для отсутствующих свойств) является рекомендованным подходом для предотвращения этой ситуации.

Неопределенные формы или недопустимые аргументы для математических функций также приводят получению NaN. Но это случается редко. Вот мой практический совет: «Получили NaN? Ищите undefined!»

Автор: Dmitri Pavlutin

Источник: //dmitripavlutin.com

Профессия Frontend-разработчик PRO

Готовим Frontend-разработчиков с нуля

На курсе вы научитесь создавать интерфейсы веб-сервисов с помощью языков программирования и
дополнительных технологий. Сможете разрабатывать планировщики задач, мессенджеры, интернет-магазины…

Узнать подробнее

До 10 проектов в портфолио для старта карьеры

Подходит для новичков без опыта в программировании

Практика на вебинарах с разработчиками из крупных компаний

Редакция: Команда webformyself.

NaN (Not a Number) – это специальное значение вещественного типа (float), которое возникает, когда выражение не имеет смысла. Ошибка NaN происходит, когда происходит некорректная арифметическая операция, например деление на ноль, или когда происходит попытка выполнить математическую операцию с некорректными данными.

Причины возникновения ошибок NaN

Ошибки NaN могут возникать по разным причинам:

  • Деление на ноль
  • Корень отрицательного числа
  • Неверное математическое выражение
  • Неверный тип данных

Способы устранения ошибок NaN

Как исправить ошибки NaN в своей программе? Вот несколько способов, которые помогут вам устранить эту проблему:

Проверка деления на ноль

Чтобы избежать деления на ноль, нужно проверить, что знаменатель не равен нулю, перед тем как производить деление. Это можно сделать с помощью условного оператора. Пример:

x = 10
y = 0

if y != 0:
   z = x / y
else:
   z = 0

Проверка на отрицательные числа

Если в вашем выражении используется корень, необходимо проверять, что извлекаемое число является неотрицательным, чтобы избежать ошибки NaN. Например:

x = -4

if x >= 0:
   y = math.sqrt(x)
else:
   y = 0

Проверка типов данных

Если используются некорректные типы данных в математических выражениях, это также может привести к ошибке NaN. Нужно убедиться, что заданные переменные имеют правильный тип данных.

Использование функций проверки на NaN

В некоторых языках программирования существуют специальные функции, которые могут проверить, является ли число NaN. Например, в Python функция isnan проверяет, является ли переменная числом NaN:

import math

x = float('nan')

if math.isnan(x):
   print('x is NaN')

Избегание использования переменных со значением NaN

Если переменная имеет значение NaN, она может влиять на результат выражения. Поэтому, прежде чем использовать переменную в выражении, нужно убедиться, что ее значение не NaN:

import math

x = float('nan')
y = 10

if not math.isnan(x):
   z = x * y
else:
   z = 0

Заключение

Ошибки NaN могут привести к некорректным результатам вычислений и даже к аварийному завершению программы. Используйте вышеописанные методы, чтобы избежать ошибок NaN в своей программе. Если ничего не помогает, обратитесь за помощью к коллегам или к сообществу разработчиков.

Not to be confused with N/A.

In computing, NaN (), standing for Not a Number, is a particular value of a numeric data type (often a floating-point number) which is undefined or unrepresentable, such as the result of zero divided by zero. Systematic use of NaNs was introduced by the IEEE 754 floating-point standard in 1985, along with the representation of other non-finite quantities such as infinities.

In mathematics, zero divided by zero is undefined[a] and is therefore represented by NaN in computing systems. The square root of a negative number is not a real number, and is therefore also represented by NaN in compliant computing systems. NaNs may also be used to represent missing values in computations.[1][2]

Two separate kinds of NaNs are provided, termed quiet NaNs and signaling NaNs. Quiet NaNs are used to propagate errors resulting from invalid operations or values. Signaling NaNs can support advanced features such as mixing numerical and symbolic computation or other extensions to basic floating-point arithmetic.

Floating point[edit]

In floating-point calculations, NaN is not the same as infinity, although both are typically handled as special cases in floating-point representations of real numbers as well as in floating-point operations. An invalid operation is also not the same as an arithmetic overflow (which would return an infinity or the largest finite number in magnitude) or an arithmetic underflow (which would return the smallest normal number in magnitude, a subnormal number, or zero).

IEEE 754 NaNs are encoded with the exponent field filled with ones (like infinity values), and some non-zero number in the significand field (to make them distinct from infinity values); this allows the definition of multiple distinct NaN values, depending on which bits are set in the significand field, but also on the value of the leading sign bit (but applications are not required to provide distinct semantics for those distinct NaN values).

For example, an IEEE 754 single precision (32-bit) NaN would be encoded as

s111 1111 1xxx xxxx xxxx xxxx xxxx xxxx

where s is the sign (most often ignored in applications) and the x sequence represents a non-zero number (the value zero encodes infinities). In practice, the most significant bit from x is used to determine the type of NaN: «quiet NaN» or «signaling NaN» (see details in Encoding). The remaining bits encode a payload (most often ignored in applications).

Floating-point operations other than ordered comparisons normally propagate a quiet NaN (qNaN). Most floating-point operations on a signaling NaN (sNaN) signal the invalid operation exception; the default exception action is then the same as for qNaN operands and they produce a qNaN if producing a floating-point result.

The propagation of quiet NaNs through arithmetic operations allows errors to be detected at the end of a sequence of operations without extensive testing during intermediate stages. For example, if one starts with a NaN and adds 1 five times in a row, each addition results in a NaN, but there is no need to check each calculation because one can just note that the final result is NaN. However, depending on the language and the function, NaNs can silently be removed from a chain of calculations where one calculation in the chain would give a constant result for all other floating-point values. For example, the calculation x0 may produce the result 1, even where x is NaN, so checking only the final result would obscure the fact that a calculation before the x0 resulted in a NaN. In general, then, a later test for a set invalid flag is needed to detect all cases where NaNs are introduced[3] (see Function definition below for further details).

In section 6.2 of the old IEEE 754-2008 standard, there are two anomalous functions (the maxNum and minNum functions, which return the maximum and the minimum, respectively, of two operands that are expected to be numbers) that favor numbers — if just one of the operands is a NaN then the value of the other operand is returned. The IEEE 754-2019 revision has replaced these functions as they are not associative (when a signaling NaN appears in an operand).[4][5]

Comparison with NaN[edit]

Comparisons are specified by the IEEE 754 standard to take into account possible NaN operands.[6] When comparing two real numbers, or extended real numbers (as in the IEEE 754 floating-point formats), the first number may be either less than, equal to, or greater than the second number. This gives three possible relations. But when at least one operand of a comparison is NaN, this trichotomy does not apply, and a fourth relation is needed: unordered. In particular, two NaN values compare as unordered, not as equal.

As specified, the predicates associated with the <, ≤, =, ≥, > mathematical symbols (or equivalent notation in programming languages) return false on an unordered relation. So, for instance, NOT(x < y) is not logically equivalent to xy: on unordered, i.e. when x or y is NaN, the former returns true while the latter returns false. However, ≠ is defined as the negation of =, thus it returns true on unordered.

Comparison between NaN and any floating-point value x
(including NaN and ±∞)

Comparison NaN ≥ x NaN ≤ x NaN > x NaN < x NaN = x NaN ≠ x
Result False False False False False True

From these rules, xx or x = x can be used to test whether x is NaN or non-NaN.

The comparison predicates are either signaling or non-signaling on quiet NaN operands; the signaling versions signal the invalid-operation exception for such comparisons (i.e., by default, this just sets the corresponding status flag in addition to the behavior of the non-signaling versions). The equality and inequality predicates are non-signaling. The other standard comparison predicates associated with the above mathematical symbols are all signaling if they receive a NaN operand. The standard also provides non-signaling versions of these other predicates. The predicate isNaN(x) determines whether a value is a NaN and never signals an exception, even if x is a signaling NaN.

The IEEE floating-point standard requires that NaN ≠ NaN hold. In contrast, the 2022 private standard of posit arithmetic has a similar concept, NaR (Not a Real), where NaR = NaR holds.[7]

Operations generating NaN[edit]

There are three kinds of operations that can return NaN:[8]

  • Most operations with at least one NaN operand.
  • Indeterminate forms:
    • The divisions (±0) / (±0) and (±∞) / (±∞).
    • The multiplications (±0) × (±∞) and (±∞) × (±0).
    • Remainder x % y when x is an infinity or y is zero.
    • The additions (+∞) + (−∞), (−∞) + (+∞) and equivalent subtractions (+∞) − (+∞) and (−∞) − (−∞).
    • The standard has alternative functions for powers:
      • The standard pow function and the integer exponent pown function define 00, 1, and 0 as 1.
      • The powr function defines all three indeterminate forms as invalid operations and so returns NaN.
  • Real operations with complex results, for example:
    • The square root of a negative number.
    • The logarithm of a negative number.
    • The inverse sine or inverse cosine of a number that is less than −1 or greater than 1.

NaNs may also be explicitly assigned to variables, typically as a representation for missing values. Prior to the IEEE standard, programmers often used a special value (such as −99999999) to represent undefined or missing values, but there was no guarantee that they would be handled consistently or correctly.[1]

NaNs are not necessarily generated in all the above cases. If an operation can produce an exception condition and traps are not masked then the operation will cause a trap instead.[9] If an operand is a quiet NaN, and there is also no signaling NaN operand, then there is no exception condition and the result is a quiet NaN. Explicit assignments will not cause an exception even for signaling NaNs.

Quiet NaN[edit]

Quiet NaNs, or qNaNs, do not raise any additional exceptions as they propagate through most operations. The exceptions are where the NaN cannot simply be passed through unchanged to the output, such as in format conversions or certain comparison operations.

Signaling NaN[edit]

Signaling NaNs, or sNaNs, are special forms of a NaN that, when consumed by most operations, should raise the invalid operation exception and then, if appropriate, be «quieted» into a qNaN that may then propagate. They were introduced in IEEE 754. There have been several ideas for how these might be used:

  • Filling uninitialized memory with signaling NaNs would produce the invalid operation exception if the data is used before it is initialized
  • Using an sNaN as a placeholder for a more complicated object, such as:
    • A representation of a number that has underflowed
    • A representation of a number that has overflowed
    • Number in a higher precision format
    • A complex number

When encountered, a trap handler could decode the sNaN and return an index to the computed result. In practice, this approach is faced with many complications. The treatment of the sign bit of NaNs for some simple operations (such as absolute value) is different from that for arithmetic operations. Traps are not required by the standard. There are other approaches to this sort of problem that would be more portable.[citation needed]

Payload operations[edit]

IEEE 754-2019 recommends the operations getPayload, setPayload, and setPayloadSignaling be implemented,[10] standardizing the access to payloads to streamline application use.[11] According to the IEEE 754-2019 background document, this recommendation should be interpreted as «required for new implementations, with reservation for backward compatibility».[12]

Encoding[edit]

In IEEE 754 standard-conforming floating-point storage formats, NaNs are identified by specific, pre-defined bit patterns unique to NaNs. The sign bit does not matter. Binary format NaNs are represented with the exponential field filled with ones (like infinity values), and some non-zero number in the significand field (to make them distinct from infinity values). The original IEEE 754 standard from 1985 (IEEE 754-1985) only described binary floating-point formats, and did not specify how the signaling/quiet state was to be tagged. In practice, the most significant bit of the significand field determined whether a NaN is signaling or quiet. Two different implementations, with reversed meanings, resulted:

  • most processors (including those of the Intel and AMD’s x86 family, the Motorola 68000 family, the AIM PowerPC family, the ARM family, the Sun SPARC family, and optionally new MIPS processors) set the signaling/quiet bit to non-zero if the NaN is quiet, and to zero if the NaN is signaling. Thus, on these processors, the bit represents an is_quiet flag;
  • in NaNs generated by the PA-RISC and old MIPS processors, the signaling/quiet bit is zero if the NaN is quiet, and non-zero if the NaN is signaling. Thus, on these processors, the bit represents an is_signaling flag.

The former choice has been preferred as it allows the implementation to quiet a signaling NaN by just setting the signaling/quiet bit to 1. The reverse is not possible with the latter choice because setting the signaling/quiet bit to 0 could yield an infinity.[13]

The 2008 and 2019 revisions of the IEEE 754 standard make formal requirements and recommendations for the encoding of the signaling/quiet state.

  • For binary interchange formats, the most significant bit of the significand field is exclusively used to distinguish between quiet and signaling NaNs.[14] Moreover, it should be an is_quiet flag.[15] That is, this bit is non-zero if the NaN is quiet, and zero if the NaN is signaling.
  • For decimal interchange formats, whether binary or decimal encoded, a NaN is identified by having the top five bits of the combination field after the sign bit set to ones. The sixth bit of the field is the is_signaling flag. That is, this bit is zero if the NaN is quiet, and non-zero if the NaN is signaling.[16]

For IEEE 754-2008 conformance, the meaning of the signaling/quiet bit in recent MIPS processors is now configurable via the NAN2008 field of the FCSR register. This support is optional in MIPS Release 3 and required in Release 5.[17]

The state/value of the remaining bits of the significand field are not defined by the standard. This value is called the ‘payload’ of the NaN. If an operation has a single NaN input and propagates it to the output, the result NaN’s payload should be that of the input NaN (this is not always possible for binary formats when the signaling/quiet state is encoded by an is_signaling flag, as explained above). If there are multiple NaN inputs, the result NaN’s payload should be from one of the input NaNs; the standard does not specify which.

Function definition[edit]

There are differences of opinion about the proper definition for the result of a numeric function that receives a quiet NaN as input. One view is that the NaN should propagate to the output of the function in all cases to propagate the indication of an error. Another view, and the one taken by the ISO C99 and IEEE 754-2008 standards in general, is that if the function has multiple arguments and the output is uniquely determined by all the non-NaN inputs (including infinity), then that value should be the result. Thus for example the value returned by hypot(±∞, qNaN) and hypot(qNaN, ±∞) is +∞.

The problem is particularly acute for the exponentiation function pow(x, y) = xy. The expressions 00, ∞0 and 1 are considered indeterminate forms when they occur as limits (just like ∞ × 0), and the question of whether zero to the zero power should be defined as 1 has divided opinion.

If the output is considered as undefined when a parameter is undefined, then pow(1, qNaN) should produce a qNaN. However, math libraries have typically returned 1 for pow(1, y) for any real number y, and even when y is an infinity. Similarly, they produce 1 for pow(x, 0) even when x is 0 or an infinity. The rationale for returning the value 1 for the indeterminate forms was that the value of functions at singular points can be taken as a particular value if that value is in the limit the value[clarification needed] for all but a vanishingly small part of a ball around the limit value of the parameters.[citation needed] The 2008 version of the IEEE 754 standard says that pow(1, qNaN) and pow(qNaN, 0) should both return 1 since they return 1 whatever else is used instead of quiet NaN. Moreover, ISO C99, and later IEEE 754-2008, chose to specify pow(−1, ±∞) = 1 instead of qNaN; the reason of this choice is given in the C rationale:[18] «Generally, C99 eschews a NaN result where a numerical value is useful. … The result of pow(−2, ∞) is +∞, because all large positive floating-point values are even integers.»

To satisfy those wishing a more strict interpretation of how the power function should act, the 2008 standard defines two additional power functions: pown(x, n), where the exponent must be an integer, and powr(x, y), which returns a NaN whenever a parameter is a NaN or the exponentiation would give an indeterminate form.

Integer NaN[edit]

Most fixed-size integer formats cannot explicitly indicate invalid data. In such a case, when converting NaN to an integer type, the IEEE 754 standard requires that an invalid operation exception be signaled. For example in Java, such operations throw instances of java.lang.ArithmeticException.[19] In C, they lead to undefined behavior, but if annex F is supported, the operation yields an «invalid» floating-point exception (as required by the IEEE standard) and an unspecified value.

Perl’s Math::BigInt package uses «NaN» for the result of strings that do not represent valid integers.[20]

> perl -mMath::BigInt -e "print Math::BigInt->new('foo')"
NaN

Display[edit]

Different operating systems and programming languages may have different string representations of NaN.

nan (C, C++, Python)
NaN (ECMAScript, Rust, C#, Julia). Julia may show alternative NaN, depending on precision, NaN32, and NaN16; NaN is for Float64 type.
NaN% 
NAN (C, C++, Rust)
NaNQ (IBM XL and AIX: Fortran, C++ proposal n2290)
NaNS (ditto)
qNaN
sNaN
1.#SNAN (Excel)
1.#QNAN (Excel)
-1.#IND (Excel)
+nan.0 (Scheme)

Since, in practice, encoded NaNs have a sign, a quiet/signaling bit and optional ‘diagnostic information’ (sometimes called a payload), these will occasionally be found in string representations of NaNs, too. Some examples are:

  • For the C and C++ languages, the sign bit is always shown by the standard-library functions (e.g. -nan) when present. There is no standard display of the payload nor of the signaling status, but a quiet NaN value of a specific payload may either be constructed by providing the string nan(char-sequence) to a number-parsing function (e.g. strtod) or by providing the char-sequence string to nan() (or nans() for sNaN), both interpreted in an implementation-defined manner.
    • GCC and LLVM provides built-in implementations of nan() and nans(). They parse the char-sequence as an integer for strtoull (or a differently-sized equivalent) with its detection of integer bases.
    • The GNU C Library’s float-parser uses the char-sequence string in «some unspecified fashion».[21] In practice, this parsing has been equivalent to GCC/LLVM’s for up to 64 bits of payload.
    • Newlib does not implement nan() parsing, but strtod() accepts a hexadecimal format without prefix.
    • musl does not implement any payload parsing.

Not all languages admit the existence of multiple NaNs. For example, ECMAScript only uses one NaN value throughout.

References[edit]

Notes[edit]

  1. ^ 0/0 is undefined in both the real number and extended real number systems, while 1/±0, for example, could be consistently assigned a value of ±∞ in the latter system, assuming a signed zero.

Citations[edit]

  1. ^ a b Bowman, Kenneth (2006). An Introduction to Programming with IDL: Interactive Data Language. Academic Press. p. 26. ISBN 978-0-12-088559-6.
  2. ^ Press, William H.; Teukolsky, Saul A.; Vetterling, William T.; Flannery, Brian P. (2007). Numerical Recipes: The Art of Scientific Computing. Cambridge University Press. p. 34. ISBN 978-0-521-88068-8.
  3. ^ William Kahan (1 October 1997). «Lecture Notes on the Status of IEEE Standard 754 for Binary Floating-Point Arithmetic» (PDF).
  4. ^ David H.C. Chen (21 February 2017). «The Removal/Demotion of MinNum and MaxNum Operations from IEEE 754™-2018″ (PDF). Retrieved 6 May 2019.
  5. ^ «754R Minutes». 19 May 2017. Retrieved 25 June 2017.
  6. ^ IEEE 754 2019, §5.11
  7. ^ Standard for Posit Arithmetic (2022)
  8. ^ David Goldberg (1991). «What Every Computer Scientist Should Know About Floating-Point».
  9. ^ «Intel 64 and IA-32 Architectures Software Developer’s Manual Volume 1: Basic Architecture». April 2008. pp. 118–125, 266–267, 334–335.
  10. ^ IEEE 754 2019, §9.7
  11. ^ «Background discussion for the new Payload functions».
  12. ^ «IEEE Standard for Floating-Point Arithmetic revision due in 2019» (PDF).
  13. ^ «Re: (long) sNaNs not what they could be…» grouper.ieee.org. 15 October 2010. Retrieved 5 November 2020.
  14. ^ IEEE 754 2019, §3.4
  15. ^ IEEE 754 2019, §6.2.1
  16. ^ IEEE 754 2019, §3.5.2
  17. ^ «MIPS® Architecture For Programmers – Volume I-A: Introduction to the MIPS64® Architecture» (PDF). MIPS Technologies, Inc. 20 November 2013. p. 79. Retrieved 27 September 2017.
  18. ^ «Rationale for International Standard—Programming Languages—C, Revision 5.10» (PDF). April 2003. p. 180.
  19. ^ «ArithmeticException (Java Platform SE 8)». docs.oracle.com.
  20. ^ «Math::BigInt«. perldoc.perl.org. Retrieved 12 June 2015.
  21. ^ «Parsing of Floats (The GNU C Library)». www.gnu.org. Retrieved 9 September 2021. If chars… are provided, they are used in some unspecified fashion to select a particular representation of NaN (there can be several).

Standards[edit]

  • IEEE Computer Society (29 August 2008). IEEE Standard for Floating-Point Arithmetic. IEEE STD 754-2008. IEEE. pp. 1–70. doi:10.1109/IEEESTD.2008.4610935. ISBN 978-0-7381-5753-5. IEEE Std 754-2008.
  • IEEE Computer Society (22 July 2019). IEEE Standard for Floating-Point Arithmetic. IEEE STD 754-2019. IEEE. pp. 1–84. doi:10.1109/IEEESTD.2019.8766229. ISBN 978-1-5044-5924-2. IEEE Std 754-2019.

External links[edit]

  • Not a Number, foldoc.org
  • IEEE 754-2008 Standard for Floating-Point Arithmetic (subscription required)
  • IEEE 754-2019 Standard for Floating-Point Arithmetic (subscription required)

NaN возникает, когда случается попытка произвести арифметическую операцию с не числовыми данными. Когда один из аргументов например строка и никак не может быть преобразован в число.

Например вы считаете разницу: var r = a — b; Если a = 3, b = 2, то r будет 1, но если один из этих аргументов получит что-то странное, например вместо числа юзер введет скажем «вася», то в итоге получим 3 — «вася» = NaN

Решением вашей проблемы, будет проверка всех полей для ввода, так чтобы не допустить строк там, где ожидается число.

Некоторые операции с бесконечностями приводят к странному результату, например, деление бесконечности на бесконечность. В математике такая операция не имеет никакого числового эквивалента. В JavaScript вернется NaN.

Infinity / Infinity; // NaN

NaN — специальное значение «не число», которое обычно говорит о том, что была выполнена бессмысленная операция. Результатом практически любой операции, в которой участвует NaN, будет NaN.

NaN + 1; // NaN

NaN интересное значение, хотя оно обозначает «не число» — с точки зрения типов, оно является числом. Парадокс. NaN никогда не является желаемым значением и появляется только в результате ошибок. Если вы его встретили, то нужно отследить момент, в котором выполнилась операция, недопустимая для чисел, и поправить это место.

Задание

Выполните операцию, которая приводит к NaN, и распечатайте её результат на экран с помощью console.log().

Упражнение не проходит проверку — что делать? 😶

Если вы зашли в тупик, то самое время задать вопрос в «Обсуждениях». Как правильно задать вопрос:

  • Обязательно приложите вывод тестов, без него практически невозможно понять что не так, даже если вы покажете свой код. Программисты плохо исполняют код в голове, но по полученной ошибке почти всегда понятно, куда смотреть.

В моей среде код работает, а здесь нет 🤨

Тесты устроены таким образом, что они проверяют решение разными способами и на разных данных. Часто решение работает с одними входными данными, но не работает с другими. Чтобы разобраться с этим моментом, изучите вкладку «Тесты» и внимательно посмотрите на вывод ошибок, в котором есть подсказки.

Мой код отличается от решения учителя 🤔

Это нормально 🙆, в программировании одну задачу можно выполнить множеством способов. Если ваш код прошел проверку, то он соответствует условиям задачи.

В редких случаях бывает, что решение подогнано под тесты, но это видно сразу.

Прочитал урок — ничего не понятно 🙄

Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в «Обсуждениях». Идеально, если вы сформулируете непонятные моменты в виде вопросов. Обычно нам нужно несколько дней для внесения правок.

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

Полезное

  • NaN

Нашли ошибку? Есть что добавить? Пулреквесты приветствуются https://github.com/hexlet-basics

Понравилась статья? Поделить с друзьями:
  • Named entity expected got none ошибка html
  • Name ошибка excel
  • Name mglearn is not defined ошибка
  • Mvc обработка ошибок
  • Muz ge71va коды ошибок