In what contexts do programming languages make real use of an Infinity value?


Question

So in Ruby there is a trick to specify infinity:

1.0/0
=> Infinity

I believe in Python you can do something like this

float('inf')

These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance

(0..1.0/0).include?(number) == (number >= 0) # True for all values of number
=> true

To summarize, what I'm looking for is a real world reason to use Infinity.

EDIT: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people actually used it.

1
28
4/11/2015 1:28:24 PM

Accepted Answer

Dijkstra's Algorithm typically assigns infinity as the initial edge weights in a graph. This doesn't have to be "infinity", just some arbitrarily constant but in java I typically use Double.Infinity. I assume ruby could be used similarly.

34
1/26/2010 7:09:08 PM

Off the top of the head, it can be useful as an initial value when searching for a minimum value.

For example:

min = float('inf')

for x in somelist:
  if x<min: 
    min=x

Which I prefer to setting min initially to the first value of somelist

Of course, in Python, you should just use the min() built-in function in most cases.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon