Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make infinity value in C? (especially integer value)

Tags:

c

graph

I made weight directed graph, just like this

6
0 3 4 INFINITY INFINITY INFINITY
INFINITY 0 INFINITY 7 INFINITY INFINITY
INFINITY 3 0 5 11 INFINITY
INFINITY INFINITY INFINITY 0 6 3
INFINITY INFINITY INFINITY INFINITY 0 4
INFINITY INFINITY INFINITY INFINITY INFINITY 0

at first, I used some integer value to express infinity like 99 or 20000. but when I find it is wrong, v5 -> v4 must be express infinity but some integer value is expressed.

ex : Shortest Path from v2 to v3 : v2 v3 (length : 200000)

is there any infinity value for integer?

friend of mine says ~(1<<31) but it doesn't work

like image 791
Silvester Avatar asked Nov 16 '11 14:11

Silvester


People also ask

How do you write infinity in C?

There is no representation of infinity in C. infinity, if available; else to a positive constant of type float that overflows at translation time.

How do you convert an int to infinity?

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();”.

How do you set a value to infinity?

With integers, there is no value that can represent infinity. Instead, it will set it to the largest value that an int can represent. If int happens to be a 32-bit integer, then INT_MAX == 2147483647 .


2 Answers

Unlike floating-point types, integer types don't have a standard value for infinity. If you have to have one, you'll have to pick a value yourself (e.g. INT_MAX) and correctly handle it throughout your code. Note that if you do this, you can use the special value in assignments and comparisons, but not in arithmetic expressions.

like image 88
NPE Avatar answered Oct 03 '22 14:10

NPE


Infinity doesn't exist for integers. What your friend suggested was the biggest number in a 32 bit signed integer, but that still is not infinity. That also introduces the possibility of overflow if you add it to something (for example in shortest path), you actually might end up getting a smaller number. So don't do it.

The proper way to do it, is to handle infinity case by case. Use a flag for infinity, for example that same ~(1<<31), or perhaps even better, -1 and in your code, whenever you want to add two values, check if either of them is equal to this flag (equal to infinity), set the result to infinity without actually doing any summations. Or when you are checking if one value is smaller than another, check if one is equal to this flag (equal to infinity), then the other is definitely smaller, again without actually doing the comparison.

like image 45
Shahbaz Avatar answered Oct 03 '22 16:10

Shahbaz