Что такое inf в c
Перейти к содержимому

Что такое inf в c

  • автор:

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:

Renan Lopes's user avatar

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.

What is INFINITY In C?

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

INFINITY is a macro constant defined in the <math.h> library, and programmers use it to perform mathematical comparisons in C.

Example

C allows us to define INFINITY as positive INFINITY or negative INFINITY .

The snippet below shows how positive or unsigned INFINITY may be defined, and subsequently used in a mathematical comparison:

Infinity in C

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

Abnormal termination can be a severe issue for life-critical software. The programmers never want an abnormal termination; thereby, the if-else checks are used, or exception handling is performed.

Consider a simple code:

In this program, we are using a hardcoded division of 5 with 0 to check the program’s behavior; however, there can be a case where a programmer may use a variable as a divider whose value somehow becomes zero. We have tried it in Programiz C online compiler, and the output is below.

We have tried the same code in another online compiler, and the output is below.

This program is terminated (crash) at the first print statement. We have another print statement, which is not executed because the program has already been terminated (called abnormal termination).

Representation of Infinity in C

In C, infinity is represented by INF or inf . Typically, it results from a division by zero or null value.

See this example code:

There are two print statements in the code. We call the function with non-zero parameters in the first print statement, whereas the second parameter is zero in the second print call.

The situation may look similar to the first code; however, it is slightly different. In the first code, we have an expression (having divided by zero) within the print statement, and as a result, the program is abnormally terminated.

However, this second program calls the divide function from the main() function. The divide function returns inf as a result of the call from the main function, which prints it accordingly.

We can obtain the same results if we store the result in some variable in the main function.

Besides getting inf as a result, we can compare the result with infinity. Our next instructions may be based on the value of the expression, and many cases require not proceeding in case of the infinite result.

Therefore, we have to check the value before executing the next instructions.

For this purpose, we have a function isinf to check whether the result is infinity or not. See the example:

Notice the if statement where we pass our result to the isinf function to compare the result with infinity. If the res has an infinite value, we skip the printf statement.

It is evident from the output that we can’t proceed further in case of infinite results; however, the program is not doing any abnormal termination. In any case, the programmer can save any required data, can write logs, etc.

Negative Infinity in C

We also have negative infinity in C. For example, if we multiply infinity by a negative number, we will get negative infinity in the result.

See this simple code:

The output of this code is Result is -inf . Let’s look at another example to understand -INFINITY manipulations.

Here, the second function call to the divide function asks it to divide a negative number by 0, thereby returning a value equal to negative infinity.

In this tutorial, we have covered both aspects. First, we discussed the methods to save our programs from abnormal termination in case of infinite results.

After that, we further looked at how our programs can further manipulate infinity to develop conditional expressions involving infinite values.

C++ Infinity

With the implementation of floating-point infinities, the infinity expands to the constant expression of float type data type, which evaluates to unsigned as well as positive infinity. On the other hand, the execution doesn’t care about floating infinities, and macro infinity enlarges the optimistic worth that insured to run-off a float data type at compile-time.

Assign Infinity value to a variable:

If we need infinity, use double or floating-point numeric values; you can easily get infinity. If the execution helps the double data-type infinities, the macro INFINITY develops to the continual appearance of type double, which estimates the positive and unidentified infinity. Look at this example:

float Calcula ( double x, double y )

if ( x > y ) { return INFINITY ; }

else { /* your else if you have one */ }

double a = 4.0 , b = 2.0 ;

ret = isinf ( Calcula ( a, b ) ) ;

We use a header file. ‘#include <iostream>and #include <math.h>which describe one macro and several type of mathematical functions. This library contains all functions which we need in the library that take return double as a result that was taken double as an argument and as you can see in the code. When the consequence of an object is not representable as a floating numeric value, we use the macro. In the main body, we initialized variables with the data type of the double having name “a”, “b”, and “ret” respectively. Then we assign a function of “isinf” to “ret” with the parameters of “a” and “b”. After that, we display the set.

Setting an int Infinity:

Integers are inherently finite; that is why we cannot define them to a right infinity. The nearby value that we can get is by initializing an “int” to its extreme value. The closest we can get by setting a variable to the maximum value that is double “a = std: numeric_limits<int>:: max();”. Which would be 231-1 if it is 32 bits wide on our implementation. With this expression, we can assign this variable to the maximum value of int, which means it could be equal or greater than any other integer value.

using namespace std ;

int a = std :: numeric_limits < int > :: infinity ( ) ;

cout << "the value of a is \t " << a ;

We integrate a header file #include <iostream>and #include <limit>. These type of libraries defines the elements with the features of arithmetic types. More in detail, it describes a numeric limit class pattern and a specialization for individuals of the types. In the main body of the code, we initialized a variable with integer data-type, assign it a numeric limit with int, and apply infinity at the end of the statement. It is also called positive infinity because the value of ‘a’ equals zero. Then we display the result as we said before that integers are not finite, and we can’t set it to a true infinity.

Setting a float Infinity:

The only true infinities in C++ are the floating-point data-types if your platform supports the concept of a float; as we mentioned before, if we need infinity, use a floating-point number type, like float and double we will get infinity as it shows in the following example.

using namespace std ;

float f = std :: numeric_limits < float > :: infinity ( ) ;

cout << "the value of f is \t " << f ;

First of all, we use two header files ‘#include <iostream>and #include <limit>. Then we write the main body of the code, where we initialized a variable with float data-type and assigned it a numeric limit with float; you can also use double at the place of float and get infinity. We also apply infinity at the end by assigning the limit with float data type. Then we print the output, and you can see floating types are true infinities.

Negative Infinity:

The negative infinity result is less than zero so for the integer data-type, it does not have an infinity value rather we can use “std::numaric_limits<double>:: infinity();” to get the maximum value of an integer.

using namespace std ;

int b = std :: numeric_limits < double > :: infinity ( ) ;

cout << "the value of b is \t " << b ;

First of all, we wrote two header files ‘#include <iostream>and #include <limit>. Then we start the main body of the code, where we initialized a variable with float data-type and assigned it a numeric limit with float; you can also use double at the place of float and get infinity. By assigning the limit with the float data type, we also apply infinity at the end. Then we print the output, and you can see that integer data types with double or float data types result in the negative limit of the integer value.

Conclusion:

In this article, we define the infinity and the syntax of the infinity with the different data types. We discuss that infinity cannot be defined solely in terms of number or the combination of the numeric values with the examples of different types of infinity. We conclude that integer data type is not good for infinity, but float and double are the suitable data types for infinity.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *