Что такое inf в c
SlavicG → Codeforces Round #799 (Div. 4)
ibraGYM → How to choose university?
awoo → Educational Codeforces Round 130 [рейтинговый для Div. 2]
ezraft → rip 400+ day streak
Contesting_pov → How to activate tex commands in my browser
ciara → give 1 problem i can’t think
ciara → help .
Flavanoid → GNU G++ Problems
spiritedExit0 → help needed with finding a recurrence for the number of ways to fill grid
kamack38 → My GitHub
BiNARy__Beast__ → How Is o(n^2) accepted for problem C(n <= 1e5)?
eng3zim → Is beethoven97 a hacking bot?!
Erering → Why am I not getting rating even though I solved a question in a competition?
r1ddle → Getting Accpted in C++20 but TLE in C++17 With Same Code
n0sk1ll → Editorial for Codeforces Round #798 (Div. 2)
don0thing → Your daily routine!
Svlad_Cjelli → Using Rust for programming contests
Nil_paracetamol → All Div-4 Contest link
chenjb → XXII Open Cup: GP of EDG
pushpavel → (AutoCp) Competitive Programming Plugin for Intellij-Based IDEs
MrPaul_TUser → Разбор задач Codeforces Round #748 (Div.3)
Flavanoid → GNU G++ Problems
ldyllic → Facebоok (Meta) Hacker Cup 2022
YouKn0wWho → Congruence Shortest Path Problem
sachinjaiswal → TLE or Not
Блог пользователя difask
ll ans = INFINITY; //long_long_max
if (smth < INFINITY) //int_max by default
if (smth < (long long)INFINITY) //long_long_max
с++, gnu, макросы, фишки, трюки, никто не читает тэги
Infinity in C
In this tutorial, we will discuss infinity in C. We will start with the discussion on infinity in general.
Next, we will discuss infinity as a run-time error in C and conclude with a discussion on storing and using infinity in C.
What is Infinity
We all know the number line from our elementary school. This number line is represented by arrows having no ending or beginning.
However, theoretically, we have both of them. The numbers terminate on positive ∞ (sometimes written as +∞ ) infinity and start from negative infinity -∞ .
Every real number x lies between – ∞ < x < ∞ . Infinity refers to a number whose weight is beyond any describable limit.
When we say we have infinite numbers, this means we have a non-ending amount of numbers.
We all know that when we divide a thing, we get pieces or parts of the actual thing. The smaller the divider, the more pieces we have.
To get more pieces, we have to divide the thing into smaller pieces. Therefore, if we divide something that approaches zero, we get infinite pieces (uncountable pieces).
Conversely, if we divide any real number by infinity, the result will be zero as it is the same as distributing a limited amount to infinite pieces; thereby, each piece will get nearly zero shares.
Infinity in Programming
Normally, programmers have a typical issue with infinity; whenever the divider is zero (usually by mistake) in an expression, it crashes the program (abnormal termination).
How to use nan and inf in C?
I have a numerical method that could return nan or inf if there was an error, and for testing purposed I’d like to temporarily force it to return nan or inf to ensure the situation is being handled correctly. Is there a reliable, compiler-independent way to create values of nan and inf in C?
After googling for about 10 minutes I’ve only been able to find compiler dependent solutions.
10 Answers 10
You can test if your implementation has it:
The existence of INFINITY is guaranteed by C99 (or the latest draft at least), and «expands to a constant expression of type float representing positive or unsigned infinity, if available; else to a positive constant of type float that overflows at translation time.»
NAN may or may not be defined, and «is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN.»
Note that if you’re comparing floating point values, and do:
is false. One way to check for NaN would be:
You can also do: a != a to test if a is NaN.
There is also isfinite() , isinf() , isnormal() , and signbit() macros in math.h in C99.
C99 also has nan functions:
![]()
There is no compiler independent way of doing this, as neither the C (nor the C++) standards say that the floating point math types must support NAN or INF.
Edit: I just checked the wording of the C++ standard, and it says that these functions (members of the templated class numeric_limits):
wiill return NAN representations «if available». It doesn’t expand on what «if available» means, but presumably something like «if the implementation’s FP rep supports them». Similarly, there is a function:
which returns a positive INF rep «if available».
These are both defined in the <limits> header — I would guess that the C standard has something similar (probably also «if available») but I don’t have a copy of the current C99 standard.
Русские Блоги
При обработке и вводе и обработке данных очень вероятно возникновение чтения данных в нулевых значениях (максимальных и минимальных), знаменатель операции равен 0 или 0,0, а операция взятия логарифма 0 будет генерировать nan или inf. Этот пост предназначен для анализа работы C / C ++ для генерации nan и inf и определения того, генерируются ли nan или inf.
Причины НАН
nan: не число, что означает «недопустимое число».
- Возведите в квадрат отрицательные числа, например: −1.0 −−−− √ − 1.0;
- Найти логарифм отрицательных чисел, например: log (−1.0) log (−1.0);
- 0.00.00.00.0;
- 0.0*inf;
- infinfinfinf;
- Инф-инф за эти операции получит нан.
(0000 сгенерирует исключение операции; 0.00.00.00.0 не сгенерирует исключение операции, но получит nan);
Примечание: nan неупорядочен и не может быть логически обработан. Это не больше, меньше или равно любому числу (включая себя), <,>, <= и> = воздействуют на nan, чтобы вызвать исключение. Когда вы получите nan, проверьте, есть ли недопустимая операция. Если выражение содержит nan, то результатом выражения будет nan.
Причины INF
INF: бесконечный, что означает «бесконечность».
Превышен диапазон представления чисел с плавающей запятой (переполнение, то есть часть кода заказа превышает максимально допустимое значение).
- 1.00.01.00.0 равно inf;
- −1.00.0−1.00.0 невероятно похож на -inf;
- 0.0+inf=inf;
- log(0);
Примечание: + inf больше любого числа (кроме себя и nan), -inf меньше любого числа (кроме себя и nan), когда вы получаете inf, проверьте, есть ли переполнение или разделите на 0. Inf в выражении языка C означает понятие бесконечности в математике, например 1,0 / inf равно 0,0, и его можно сравнить с другими числами с плавающей запятой (вы можете участвовать в таких операциях, как <=,> +, == ,! = и т. Д.)
Суждение нана и инф
Следующие макросы включены в заголовочный файл math.h и могут использоваться для определения того, является ли результат выражения inf, nan или другим. При использовании include include <math.h> include <math.h>.
Откройте math.h, чтобы увидеть определение:
Способ использования и результаты:
- int isfinite (x), чтобы определить, ограничен ли x, он возвращает 1, другой возвращает 0;
- int isnormal (x), чтобы определить, является ли x числом (не inf или nan), он возвращает 1, другие возвращают 0;
- int isnan (x), nan возвращает 1, когда x, остальные возвращают 0;
- int isinf (x), возвращает 1, когда x — положительная бесконечность, возвращает -1, когда x — отрицательная бесконечность, и возвращает 0 для других. Некоторые компиляторы не различают.
Генерация операций Nan или Inf, используйте библиотечные функции (макро), чтобы судить
——————— Автор: Лу свинья не плохо Источник: CSDN Оригинал: https: //blog.csdn.net/wokaowokaowokao12345/article/details/72846436 ? utm_source = copy Заявление об авторском праве: Эта статья является оригинальной статьей блоггера. При перепечатке прикрепите ссылку на сообщение в блоге!
Интеллектуальная рекомендация
Меч относится к предложению + 43: количество N сиша + Java
Оригинальное название: бросить кубики на землю, все точки кости сталкиваются с точкой точки кости. Введите n, напечатали вероятность всех возможных значений. (6 сторон каждой кости, точки от 1 до 6) Р.
![]()
Введение в Python 4
функция ввода Использование функции Функция input () является функцией ввода. Функция input () — это функция ввода. Когда вы пишете вопрос в скобках функции, функция input () будет отображать вопрос в.
Основные операции в R 01
Повторите основную операцию секретной книги ниндзя языка R учителя Се Иихуэй.
Мастерство, создание американской легенды очистки воды
Мастера — это не только технические специалисты и квалифицированные мастера, которые могут решить некоторые практические проблемы в производстве и жизни, но также авангарды, которые могут руководить п.
курсы памяти Лу Feifei (а, понимать память понимания мозга)
Понимание памяти, что память? Понимание памяти, что память? 1 Понимание мозга 2 Что такое память Функция 3 Память 3.1 общие воспоминания путь 3.2 Факторы, влияющие на память 4 запоминающий материал Че.